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/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1072/// forward projection on the M2 OTP-shape sibling-restart
1073/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1074/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1075/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1076/// on the caixa surface (`:supervisor :estrategia`), immediately after
1077/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1078/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1079/// 2×4 corner on this enum. Routes byte-for-byte through the
1080/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1081/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1082/// `&'static str`), so every consumer that binds a
1083/// [`RestartStrategy`] through the standard-library `.into()` /
1084/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1085/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1086/// running under `axum` + `tokio` whose per-arm structured-log field
1087/// crosses an `.await` boundary and demands the [`Sync`] +
1088/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1089/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1090/// forces every downstream `.clone()` through a heap allocation, while
1091/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1092/// resolves the same `.clone()` through a refcount bump), a future
1093/// wasm-operator's per-supervisor reconciliation scheduler that
1094/// dispatches the same per-strategy diagnostic key onto multiple
1095/// concurrent reconcile-loop tasks holding shared-ownership through
1096/// [`std::sync::Arc<str>`], a future
1097/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1098/// log recorder whose typing folds a shared-ownership envelope onto
1099/// the span-context axis, a generic
1100/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1101/// shared-ownership per-strategy cache — reaches the same four-arm
1102/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1103/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1104/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1105/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1106/// the sibling
1107/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1108/// forward-projection corner already returns.
1109///
1110/// First-mover on the substrate-wide trait-idiomatic
1111/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1112/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1113/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1114/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1115/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1116/// closed-set fieldless typed enum on the substrate that carries the
1117/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1118/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1119/// [`From<Self> for String`] / [`From<&Self> for String`] /
1120/// [`From<Self> for Cow<'static, str>`] /
1121/// [`From<&Self> for Cow<'static, str>`] /
1122/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1123/// but not the [`std::sync::Arc<str>`] axis forces every
1124/// `std::sync::Arc<str>`-parameterized call site through a
1125/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1126/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1127/// composition through the owned-`String` axis that allocates
1128/// twice — once into the intermediate `String`, once into the
1129/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1130/// have no compile-time link back to the substrate primitive. Opening
1131/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1132/// peer on the caixa substrate surface establishes the "route through
1133/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1134/// `&'static str`" discipline; every future closed-set fieldless
1135/// typed enum peer on the substrate ([`RestartPolicy`],
1136/// [`crate::aplicacao::PlacementStrategy`],
1137/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1138/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1139/// [`crate::kind::CaixaKind`],
1140/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1141/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1142/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1143/// tracking the same 14-peer emit-set every prior projection tier
1144/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1145/// converged onto.
1146///
1147/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1148/// (69ef45c) — same "opens a new substrate-wide projection tier"
1149/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1150/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1151/// value the [`Box<str>`] axis's owned-move return-shape cannot
1152/// provide.
1153///
1154/// Pinned load-bearing by
1155/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1156/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1157/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1158/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1159/// axis byte-parity pins against the sibling owned-input
1160/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1161/// axes).
1162impl From<RestartStrategy> for std::sync::Arc<str> {
1163    fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1164        std::sync::Arc::<str>::from(strategy.as_str())
1165    }
1166}
1167
1168/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1169/// forward projection on the M2 OTP-shape sibling-restart
1170/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1171/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1172/// forward-projection axis on the first M2 OTP-shape closed-set
1173/// fieldless typed enum peer on the caixa surface
1174/// (`:supervisor :estrategia`), companion to the paired owned-input
1175/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1176/// prior (bca2ec8). Routes byte-for-byte through the
1177/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1178/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1179/// `&'static str`), so every consumer that binds a
1180/// [`&RestartStrategy`] through the standard-library `.into()` /
1181/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1182/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1183/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1184/// `Sync` + `Send`-safe structured-log field across an `.await`
1185/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1186/// diagnostic-column dispatch, a future wasm-operator's per-
1187/// supervisor reconciliation pipeline whose
1188/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1189/// the shared-ownership per-strategy key without a spurious [`Copy`]
1190/// deref (which would only be reachable through the owned-input
1191/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1192/// calling `.copied()` on the iterator), a future
1193/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1194/// collector recording a borrowed-`&RestartStrategy` per-arm field
1195/// onto the parent span's shared-ownership context — reaches the
1196/// same four-arm lifted
1197/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1198/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1199/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1200/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1201/// the paired owned-input
1202/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1203/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1204/// forward-projection corner already return.
1205///
1206/// Second peer on the substrate-wide trait-idiomatic
1207/// [`std::sync::Arc<str>`] forward-projection family opened one
1208/// commit prior (bca2ec8) on the paired owned-input
1209/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1210/// the `{Self, &Self}` input-shape corner of the
1211/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1212/// fieldless typed enum peer on the caixa surface, exactly as
1213/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1214/// owning half (69ef45c) landed. Rust's standard library carries
1215/// `impl From<&str> for std::sync::Arc<str>` and
1216/// `impl From<String> for std::sync::Arc<str>` but no blanket
1217/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1218/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1219/// every closed-set fieldless typed enum peer on the substrate that
1220/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1221/// not the borrowed-input axis forces every borrowed-input
1222/// [`std::sync::Arc<str>`]-parameterized call site through a
1223/// spurious [`Copy`] deref
1224/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1225/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1226/// type bounds have no compile-time link back to the substrate
1227/// primitive.
1228///
1229/// Pinned load-bearing by
1230/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1231/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1232/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1233/// surface, plus a blanket-derived [`Into`] shape witness and a
1234/// cross-axis pin against the paired owned-input
1235/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1236/// borrowed-input `{&'static str, String, Cow<'static, str>,
1237/// Box<str>}` return-shape axes).
1238impl From<&RestartStrategy> for std::sync::Arc<str> {
1239    fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1240        std::sync::Arc::<str>::from(strategy.as_str())
1241    }
1242}
1243
1244/// Per-child restart policy.
1245///
1246/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1247#[derive(
1248    Serialize,
1249    Deserialize,
1250    Debug,
1251    Clone,
1252    Copy,
1253    PartialEq,
1254    Eq,
1255    Hash,
1256    gen_platform::TypedDispatcher,
1257    gen_platform::Discriminant,
1258    gen_platform::IsVariant,
1259    gen_platform::FromStrKind,
1260)]
1261pub enum RestartPolicy {
1262    /// Always restart the child, regardless of how it died. Used for
1263    /// long-running services that must always be up.
1264    Permanent,
1265    /// Never restart. Used for one-shot work whose completion is
1266    /// itself the success signal (`oneShot` triggers map here).
1267    Temporary,
1268    /// Restart only when the child died *abnormally* (non-zero exit
1269    /// or unhandled exception). A clean exit completes the child.
1270    Transient,
1271}
1272
1273impl Default for RestartPolicy {
1274    fn default() -> Self {
1275        // Route the [`Default for RestartPolicy`] impl's return arm through
1276        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1277        // `pub const` rather than a raw `Self::Permanent` arm — one source
1278        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1279        // default across the two production consumers that currently
1280        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1281        // and the serde-side `#[serde(default)]` on
1282        // [`ChildSpec::restart`] that resolves an author-omitted
1283        // `:children :restart` slot through `RestartPolicy::default()`).
1284        // Peer of the sibling per-`:supervisor` axis
1285        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1286        // route (95ffacc) — the two impls now share one substrate-primitive
1287        // lift discipline, so any future coherent rebrand of the OTP-shape
1288        // supervisor+child default set migrates through typed constants in
1289        // lockstep instead of splitting a lifted supervisor half against
1290        // an open-coded child half. Pinned by
1291        // `restart_policy_default_routes_through_lifted_default` +
1292        // `child_spec_serde_default_restart_routes_through_lifted_default`
1293        // in the tests module.
1294        SUPERVISOR_CHILD_RESTART_DEFAULT
1295    }
1296}
1297
1298impl RestartPolicy {
1299    /// Exhaustive iteration surface for every consumer that walks the
1300    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1301    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1302    /// per-child admission-webhook rejection body naming the accepted-
1303    /// `:restart` list, a future `feira supervisor --restart …` CLI
1304    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1305    /// over the slice, the future `feira app graph` per-child restart
1306    /// column, any future round-trip fuzz harness that sweeps every
1307    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1308    /// theory
1309    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1310    /// might reach for once the three canonical OTP restart policies
1311    /// stop covering the substrate's discovered load-shape) extends
1312    /// this slice as one edit and every consumer picks up the new entry
1313    /// by construction; the compiler-checked exhaustiveness on the
1314    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1315    /// is the build-time guarantee that no arm forgets to grow.
1316    ///
1317    /// Peer of the sibling closed-set typed enums'
1318    /// [`RestartStrategy::ALL`] (4eec29c) /
1319    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1320    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1321    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1322    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1323    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1324    /// closed-set typed enum on the caixa surface to converge onto the
1325    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1326    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1327    /// sibling-restart-strategy axis; this closes the per-child
1328    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1329    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1330
1331    /// Canonical PascalCase discriminator scalar this variant serializes
1332    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1333    /// arms return the paired
1334    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1335    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1336    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1337    /// constants so every substrate consumer that dispatches on the
1338    /// per-child restart-decision policy (the future wasm-operator's
1339    /// per-child post-exit restart-decision branch, the future M4
1340    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1341    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1342    /// reconciliation scheduler's per-child-policy fan-out) reads the
1343    /// same byte-string the `Serialize` derive emits — the pin test in
1344    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1345    /// asserts the two paths agree, peer of the M2
1346    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1347    /// sibling-restart-strategy axis and the M3
1348    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1349    /// per-Aplicacao distribution-strategy axis — the third of three
1350    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1351    /// surface to converge onto the same three-path-convergence
1352    /// (`Serialize` derive → `as_str` helper → lifted constant)
1353    /// drift-detection posture.
1354    #[must_use]
1355    pub const fn as_str(self) -> &'static str {
1356        match self {
1357            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1358            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1359            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1360        }
1361    }
1362
1363    /// Substrate-canonical reverse projection on the `:children :restart`
1364    /// closed-set axis — parses the `PascalCase` discriminator scalar
1365    /// back to the typed variant, or `None` when `s` is outside the
1366    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1367    /// the same lifted
1368    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1369    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1370    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1371    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1372    /// of the round-trip migrate through one caixa-core edit on any
1373    /// future arm addition.
1374    ///
1375    /// Prior to this lift the substrate carried only the forward
1376    /// `Self → &str` projection on the OTP per-child restart-policy
1377    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1378    /// impl routed through it, the `Serialize` derive that emits the
1379    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1380    /// plus the kebab-case dispatcher-catalog identity via
1381    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1382    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1383    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1384    /// "Transient" => …, _ => … }` cascade that expressed no
1385    /// compile-time link back to the typed variant's canonical lifted
1386    /// constant. A future variant rename or per-arm serde-attribute
1387    /// drift would silently split the wire byte-string one non-serde
1388    /// consumer parsed from the one the emitter wrote, with the failure
1389    /// surfacing at the operator's reconcile posture (a `:temporary`
1390    /// `oneShot` child being restarted on clean exit, treating the
1391    /// successful-completion signal as failure and re-running the
1392    /// completion-terminal one-shot indefinitely; a `:transient` child
1393    /// that clean-exited being restarted, masking the clean-completion
1394    /// contract) far from the rebrand commit and with no field naming
1395    /// the drift.
1396    ///
1397    /// Distinct axis from the [`std::str::FromStr`] impl the
1398    /// [`gen_platform::FromStrKind`] derive already installs on this
1399    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1400    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1401    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1402    /// this method inverts the `PascalCase` wire byte-string
1403    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1404    /// catalog identity live in kebab-case (where every peer catalog
1405    /// identifier already lives) without forcing a wire-format rename
1406    /// on the tatara-lisp author surface (`:restart Permanent`,
1407    /// `PascalCase`) — the same two-axis distinction the sibling
1408    /// [`RestartStrategy::from_wire`] (4eec29c) /
1409    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1410    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1411    /// carry on their peer closed-set typed-enum wire round-trips.
1412    ///
1413    /// Same closed-set-reverse-projection discipline the sibling
1414    /// [`RestartStrategy::from_wire`] (4eec29c) /
1415    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1416    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1417    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1418    /// carry on the peer wire-side `str → Self` axes — extended onto
1419    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1420    /// sixth substrate-side closed-set typed enum (and the third and
1421    /// final OTP-shape closed-enum discriminator axis) to converge on
1422    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1423    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1424    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1425    /// derive already installs on the sibling kebab-case axis. Returns
1426    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1427    /// shapes: the caller picks the diagnostic form appropriate for
1428    /// its use site.
1429    #[must_use]
1430    pub fn from_wire(s: &str) -> Option<Self> {
1431        match s {
1432            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1433            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1434            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1435            _ => None,
1436        }
1437    }
1438}
1439
1440/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1441/// pretty-printed byte-string every consumer that formats the policy as
1442/// user-facing text lands on (the future wasm-operator's per-child
1443/// post-exit restart-decision diagnostic line, the future `feira app
1444/// graph` per-child restart column, the future M4
1445/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1446/// admission-webhook rejection body) reaches for the same lifted
1447/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1448/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1449/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1450/// wire-format `Serialize` derive already emits under
1451/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1452/// [`RestartPolicy::as_str`] helper already returns.
1453///
1454/// Pre-convergence the two paths structurally disagreed — the
1455/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1456/// route (now retired here) sent [`std::fmt::Display`] through the
1457/// gen-platform discriminant catalog string, which arrives kebab-case as
1458/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1459/// (whose variant names each collapse to their own lowercase form under
1460/// the kebab-case transform), while the wire format ran as `PascalCase`
1461/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1462/// serde derive. Every consumer that formatted the policy for a
1463/// diagnostic line, a graph column, or a rejection body under
1464/// `format!("{v}")` therefore landed under a different byte-string than
1465/// the wire format the operator's per-child-policy dispatch keyed off —
1466/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1467/// diagnostic quoting `"permanent"` while the wire scalar the operator
1468/// probed was `"Permanent"`) surfaced as a confused correlate at
1469/// operator-log time far from the two-declaration site.
1470///
1471/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1472/// path: every `format!("{v}")` call reaches the same lifted
1473/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1474/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1475/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1476/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1477/// byte-string per variant. A future variant rename or
1478/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1479/// exactly one place, structurally.
1480///
1481/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1482/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1483/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1484/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1485/// registration keys the catalog off the same kebab identity. The two
1486/// naming worlds now live on separate typed methods (`Display` /
1487/// `as_str` for the wire byte-string, `discriminant` for the catalog
1488/// identity) rather than sharing one `Display` route that structurally
1489/// disagrees with the wire format.
1490///
1491/// Pin tests
1492/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1493/// and
1494/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1495/// assert the three paths agree byte-for-byte on every variant, so a
1496/// future variant rename or per-arm serde attribute drift is a build
1497/// error visible at caixa-core test time, not a silent per-consumer
1498/// dispatch miss at apply / reconcile time.
1499///
1500/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1501/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1502/// and the sibling [`RestartStrategy`] `Display` impl on the
1503/// per-supervisor sibling-restart-strategy axis — same three-path-
1504/// convergence discipline, extended to close the third and final of
1505/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1506/// surface.
1507impl std::fmt::Display for RestartPolicy {
1508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1509        f.write_str(self.as_str())
1510    }
1511}
1512
1513/// Substrate-canonical [`AsRef<str>`] projection on the M2
1514/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1515/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1516/// scalar accessor the paired [`std::fmt::Display`] impl and the
1517/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1518/// future consumer that binds a [`RestartPolicy`] through the
1519/// standard-library `impl AsRef<str>` bound (a future
1520/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1521/// composes the emitted `PascalCase` wire scalar into a
1522/// [`std::process::Command::arg`] shell-out of the future
1523/// wasm-operator's per-child admission gate, a per-child structured-
1524/// log recorder on the future `caixa-operator`'s hierarchical
1525/// reconciliation surface that accepts `impl AsRef<str>` at the
1526/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1527/// lookup keyed on the restart-policy wire byte through
1528/// `map.get::<str>(policy.as_ref())` on a future per-policy
1529/// dispatch table) reaches the paired
1530/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1531/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1532/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1533/// lifted-const through one substrate-primitive dispatch rather
1534/// than an open-coded `.as_str()` projection at every wire-up.
1535///
1536/// Peer of the sibling [`std::fmt::Display`] impl on the same
1537/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1538/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1539/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1540/// byte-string per instance by construction. A future variant rename
1541/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1542/// enum reaches every one of the three paths (plus the wire-format
1543/// `Serialize` derive that already routes through the same lifted
1544/// const) through exactly one caixa-core edit.
1545///
1546/// Same "route the trait impl through the substrate-primitive
1547/// accessor" discipline the sibling [`crate::CaixaVersion`]
1548/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1549/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1550/// the axis onto the paired per-child-restart-decision-policy
1551/// sibling on the same M2 `:supervisor` slot (the second M2
1552/// OTP-shape closed-set typed enum to converge onto the standard-
1553/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1554/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1555/// primitive so a caller who has one has both; before this lift,
1556/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1557/// [`AsRef<str>`] impl the convention names.
1558///
1559/// Pinned load-bearing by
1560/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1561/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1562/// three-arm closed set) and
1563/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1564/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1565/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1566/// arm) — any future silent detour that routes the impl through a
1567/// divergent projection (a per-arm inline `match self { … }`
1568/// re-inlining that opens a compile-time link to the un-lifted
1569/// arm-literal, a swap onto the kebab-case
1570/// [`gen_platform::Discriminant`] catalog identity that would
1571/// collide the wire axis with the dispatcher-catalog axis) trips at
1572/// caixa-core test time under `assert_eq!` rather than at a
1573/// downstream `impl AsRef<str>`-bound consumer's silent split.
1574impl AsRef<str> for RestartPolicy {
1575    fn as_ref(&self) -> &str {
1576        self.as_str()
1577    }
1578}
1579
1580/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1581/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1582/// byte-for-byte through the paired substrate-primitive
1583/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1584/// consumer that binds a `PascalCase` `:children :restart` wire
1585/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1586/// axis (a future [`caixa-feira`] `feira supervisor --restart
1587/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1588/// `let restart: RestartPolicy = s.try_into()?`, a future
1589/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1590/// `spec.children[*].restart: String` field through
1591/// `RestartPolicy::try_from(&s)?`, a generic
1592/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1593/// set typed enums) reaches the same three-arm accept-set the sibling
1594/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1595/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1596/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1597/// … }` cascade whose arm-set has no compile-time link back to the
1598/// substrate primitive.
1599///
1600/// Complements the pre-existing forward-projection triple
1601/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1602/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1603/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1604/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1605/// caller who can project *out to* a `&str` can also project *in from*
1606/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1607/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1608/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1609/// trigger under a `FromStr` impl and to avoid colliding with the
1610/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1611/// already installs on the paired *kebab-case dispatcher-catalog* axis
1612/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1613/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1614/// idiomatic reverse axis on the *`PascalCase` wire* half without
1615/// disturbing either the method-named `from_wire` shape every sibling
1616/// closed-set typed enum on the substrate already carries or the
1617/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1618/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1619///
1620/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1621/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1622/// caller picks the diagnostic form appropriate for its use site (a
1623/// future `feira supervisor --restart` arg-parse composes its own
1624/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1625/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1626/// wraps the `Err(())` outcome with the accepted-set enumeration for
1627/// operator diagnostics, a `Result::map_err` at the call site lifts the
1628/// unit-error to a per-verb error type). Same shape the peer
1629/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1630/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1631/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1632/// their peer closed-set typed enums' reverse projections.
1633///
1634/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1635/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1636/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1637/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1638/// might reach for once the three canonical OTP restart policies stop
1639/// covering the substrate's discovered load-shape) grows the trait-
1640/// idiomatic axis by construction — one caixa-core edit on
1641/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1642/// projection every existing consumer keys off and the trait-idiomatic
1643/// reverse projection this impl exposes, without a coordinated rewrite
1644/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1645///
1646/// Extends the substrate-wide closed-set-enum reverse-projection family
1647/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1648/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1649/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1650/// closed-enum discriminator axis on the caixa surface — the paired
1651/// per-child `:children :restart` closed set the future wasm-operator's
1652/// hierarchical reconciliation scheduler's per-child post-exit
1653/// restart-decision branch keys off end-to-end.
1654///
1655/// Pinned load-bearing by
1656/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1657/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1658/// three-arm accept-set),
1659/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1660/// (rejection witness against silent accept-set widening), and
1661/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1662/// (cross-axis partition pin locking the trait and method-named
1663/// projections onto one accept-set).
1664impl TryFrom<&str> for RestartPolicy {
1665    type Error = ();
1666
1667    fn try_from(s: &str) -> Result<Self, Self::Error> {
1668        Self::from_wire(s).ok_or(())
1669    }
1670}
1671
1672/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1673/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1674/// byte-for-byte through the paired substrate-primitive
1675/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1676/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1677/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1678/// &str` with `'static` lifetime, so the trait's return-type promise is
1679/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1680/// literal.
1681///
1682/// Every future consumer that specifically needs `&'static str` lifetime
1683/// bytes on the per-child restart-decision axis (a
1684/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1685/// arm's typing demands `&'static str`, a
1686/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1687/// on the future M4 admission-webhook rejection body where the
1688/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1689/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1690/// or error formatter that requires the `'static` bound) reaches the same
1691/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1692/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1693/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1694/// primitive dispatch rather than an open-coded per-arm literal cascade
1695/// whose arm-set has no compile-time link back to the substrate primitive.
1696///
1697/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1698/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1699/// the second (and second-of-two-in-M2) closed-set typed enum on the
1700/// caixa surface to converge onto the paired trait-idiomatic forward-
1701/// projection axis. With this lift the paired per-child
1702/// `:children :restart` closed-set typed enum carries the full sibling
1703/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1704/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1705/// lift) plus the round-trip witness through both the trait-idiomatic
1706/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1707/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1708/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1709/// (an OTP-`intrinsic` fourth arm the theory
1710/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1711/// might reach for once the three canonical OTP restart policies stop
1712/// covering the substrate's discovered load-shape) grows the trait-
1713/// idiomatic forward axis by construction: one caixa-core edit on
1714/// [`RestartPolicy::as_str`] extends every one of the five sibling
1715/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1716/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1717/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1718/// bytes) without a coordinated rewrite across every future
1719/// `Into<&'static str>`-bound consumer's arm-set.
1720///
1721/// Pinned load-bearing by
1722/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1723/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1724/// three-arm emit-set, plus a `const`-context materialization witness for
1725/// the `&'static str` lifetime promise) and
1726/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1727/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1728/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1729/// round-trip witness through the paired trait-idiomatic reverse-
1730/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1731/// `policy.into::<&'static str>()` output re-parses back through
1732/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1733/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1734impl From<RestartPolicy> for &'static str {
1735    fn from(policy: RestartPolicy) -> &'static str {
1736        policy.as_str()
1737    }
1738}
1739
1740/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1741/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1742/// companion to the paired owned-input [`From<RestartPolicy> for
1743/// &'static str`] impl immediately above. Routes byte-for-byte through
1744/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1745/// fn` accessor so every consumer that binds a `&RestartPolicy`
1746/// through the standard-library `.into()` / [`From<&Self> for &'static
1747/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1748/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1749/// whose iterator over `&'static [RestartPolicy]` yields
1750/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1751/// [`From<RestartPolicy>`] axis alone forces every call site through
1752/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1753/// rather than the direct trait-idiomatic projection; a future generic
1754/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1755/// that walks the `iter().map(Into::into)` shape verbatim across every
1756/// substrate-wide closed-set typed enum; the future wasm-operator's
1757/// per-child post-exit restart-decision diagnostic line that composes
1758/// the accepted-set enumeration from an iterated
1759/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1760/// per-arm `match p { … }` cascade; a future
1761/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1762///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1763/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1764/// cannot compose without this borrowed-input axis in place) reaches
1765/// the same three-arm lifted
1766/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1767/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1768/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1769/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1770/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1771/// [`RestartPolicy::as_str`] surfaces already return.
1772///
1773/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1774/// forward-projection family opened on [`crate::dep::DepList`]
1775/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1776/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1777/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1778/// (e941836). Rust's `From` trait does not auto-derive the
1779/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1780/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1781/// exist in `core`), so every closed-set typed enum that carries the
1782/// owned-input axis but not the borrowed-input axis forces every
1783/// borrowed-input call site through a `.copied()` /
1784/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1785/// type bounds have no compile-time link to the substrate primitive.
1786/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1787/// OTP-shape peer to converge onto this campaign — sibling of the
1788/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1789/// with this lift both closed-set typed enums on the M2 `:supervisor`
1790/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1791/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1792/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1793/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1794/// forward-projection axis on the M2 OTP-shape slot as a unit.
1795///
1796/// Same three-path convergence discipline as the paired owned-input
1797/// impl (this borrowed-input axis, the paired owned-input
1798/// [`From<RestartPolicy> for &'static str`], and
1799/// [`RestartPolicy::as_str`] all route through the same lifted
1800/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1801/// variant rename or per-arm serde-attribute drift reaches every one
1802/// of the six sibling forward-projection paths
1803/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1804/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1805/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1806/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1807/// edit.
1808///
1809/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1810/// parse share the same `PascalCase` vocabulary by construction, so
1811/// the borrowed-input forward axis and the reverse axis compose
1812/// directly — the round-trip witness pin below locks this direct
1813/// composition without the intermediate wire-vocab hop the peer
1814/// [`crate::CaixaKind`] axis pair requires.
1815///
1816/// Pinned load-bearing by
1817/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1818/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1819/// three-arm emit-set via a borrowed input, plus a `const`-context
1820/// materialization witness for the `&'static str` lifetime promise,
1821/// plus a blanket `.into()` shape) and
1822/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1823/// (cross-axis partition pin against the paired owned-input
1824/// [`From<RestartPolicy> for &'static str`] impl, plus a
1825/// `.iter().map(Into::into)` pipe witness over
1826/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1827/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1828/// Self` round-trip without the wire-vocab intermediate the peer
1829/// [`crate::CaixaKind`] axis pair requires).
1830impl From<&RestartPolicy> for &'static str {
1831    fn from(policy: &RestartPolicy) -> &'static str {
1832        policy.as_str()
1833    }
1834}
1835
1836/// Trait-idiomatic *owned-`String`* forward projection on the second
1837/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1838/// owned-heap-string companion to the paired `&'static str`-returning
1839/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1840/// for &'static str`] impls immediately above. Routes byte-for-byte
1841/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1842/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1843/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1844/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1845/// future `serde_json::Value::String(policy.into())` structured-payload
1846/// composer where the `Value::String` arm typing demands an owned
1847/// [`String`] and the sibling [`&'static str`]-returning axis forces
1848/// an explicit `.to_owned()` / `String::from` restatement at every
1849/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1850/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1851/// lookup where the map's key type is owned [`String`] rather than
1852/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1853/// composer on the future M4 admission-webhook rejection body's
1854/// owned-arm, the future wasm-operator's per-child post-exit
1855/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1856/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1857/// — reaches the same three-arm lifted
1858/// [`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 two `&'static str`-returning
1863/// forward-projection impls already return.
1864///
1865/// Extends the trait-idiomatic *owned-`String`* forward-projection
1866/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1867/// the caixa surface — mirror of the first-mover
1868/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1869/// axis on the sibling supervisor-level strategy enum. Rust's standard
1870/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1871/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1872/// every closed-set typed enum that carries the paired `AsRef<str>` /
1873/// `Display` / `From<Self> for &'static str` triple but not the
1874/// owned-[`String`] axis forces every owned-string call site through a
1875/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1876/// detour whose type bounds have no compile-time link to the
1877/// substrate primitive.
1878///
1879/// Deliberately routes through the human-readable
1880/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1881/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1882/// the diagnostic byte-string share the same vocabulary by
1883/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1884/// two axes diverge), so the owned-[`String`] projection lands
1885/// byte-identically on both the wire vocabulary the paired
1886/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1887/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1888/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1889/// axis parses the same `PascalCase` vocabulary — the direct two-way
1890/// `Self → String → Self` round-trip composes without the wire-vocab
1891/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1892/// axis pair requires.
1893///
1894/// Pinned load-bearing by
1895/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1896/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1897/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1898/// witness) and
1899/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1900/// (cross-axis partition pin against the paired owned-input
1901/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1902/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1903/// plus a `.iter().copied().map(String::from)` pipe witness over
1904/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1905/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1906/// borrow that closes the two-way `Self → String → Self` round-trip
1907/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1908/// pair).
1909impl From<RestartPolicy> for String {
1910    fn from(policy: RestartPolicy) -> String {
1911        policy.as_str().to_owned()
1912    }
1913}
1914
1915/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1916/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1917/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1918/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1919/// projection family on this enum, mirror of the first-mover
1920/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1921/// 2×2-completion corner on the sibling supervisor-level strategy
1922/// enum. Routes byte-for-byte through the substrate-primitive
1923/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1924/// [`str::to_owned`]) so every consumer that holds a borrowed
1925/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1926/// `serde_json::Value::String(String::from(&policy))` structured-payload
1927/// composer over a borrowed field, a future `Iterator::map` over
1928/// `&[RestartPolicy]` that projects to owned keys through
1929/// `.iter().map(String::from)`, a future `HashMap::<String,
1930/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1931/// where dereferencing the policy would force an unnecessary `Copy` at
1932/// every step, the future wasm-operator's per-supervisor
1933/// `child_policies.iter().map(String::from).collect()` per-child post-
1934/// exit restart-decision diagnostic emit whose iteration axis is
1935/// borrowed by construction — reaches the same three-arm lifted
1936/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1937/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1938/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1939/// paired [`std::fmt::Display`], [`AsRef<str>`],
1940/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1941/// forward-projection impls
1942/// ([`From<RestartPolicy> for &'static str`],
1943/// [`From<&RestartPolicy> for &'static str`],
1944/// [`From<RestartPolicy> for String`]) already return.
1945///
1946/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1947/// owned-`String` output* forward-projection family opened on
1948/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1949/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1950/// both M2 OTP-shape sibling peers (the paired supervisor-level
1951/// sibling-restart-strategy axis and the per-child restart-decision-
1952/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1953/// full four-corner family by construction. Rust's standard library
1954/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1955/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1956/// closed-set typed enum that carries the paired `AsRef<str>` /
1957/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1958/// &'static str` / `From<Self> for String` quintuple but not the
1959/// borrowed-input owned-[`String`] axis forces every borrowed-input
1960/// owned-string call site through a `policy.as_str().to_owned()` /
1961/// `String::from(*policy)` (with a spurious `Copy`) /
1962/// `policy.to_string()` (through `Display`) detour whose type bounds
1963/// have no compile-time link to the substrate primitive.
1964///
1965/// Deliberately routes through the human-readable
1966/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1967/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1968/// the diagnostic byte-string share the same vocabulary by
1969/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1970/// two axes diverge), so the borrowed-input owned-[`String`]
1971/// projection lands byte-identically on both the wire vocabulary the
1972/// paired [`serde::Serialize`] derive emits and the diagnostic
1973/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1974/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1975/// reverse-projection axis parses the same `PascalCase` vocabulary —
1976/// the direct two-way `&Self → String → Self` round-trip composes
1977/// without the wire-vocab intermediate hop the peer
1978/// [`crate::CaixaKind`] axis pair requires.
1979///
1980/// The remaining thirteen closed-set typed enums on the caixa
1981/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1982/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1983/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1984/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1985/// of this 2×2-completion campaign — each carries the same paired
1986/// quintuple that this borrowed-input owned-[`String`] axis extends
1987/// onto.
1988///
1989/// Pinned load-bearing by
1990/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1991/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1992/// three-arm emit-set through the borrowed-input surface) and
1993/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1994/// (cross-axis partition pin against the paired owned-input owned-
1995/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1996/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1997/// &'static str`] impl, and the sibling [`ToString::to_string`]
1998/// surface routed through [`std::fmt::Display`], plus a direct round-
1999/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2000/// [`String::as_str`] borrow that closes the two-way
2001/// `&Self → String → Self` round-trip on the trait-idiomatic
2002/// borrowed-input owned-[`String`] forward + reverse axis pair).
2003impl From<&RestartPolicy> for String {
2004    fn from(policy: &RestartPolicy) -> String {
2005        policy.as_str().to_owned()
2006    }
2007}
2008
2009/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2010/// output* forward projection on the M2 OTP-shape per-child-restart
2011/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2012/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2013/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2014/// borrowed-input) and first extended off it onto the sibling M2
2015/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2016/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2017/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2018/// surface (`:children :restart`). Routes byte-for-byte through the
2019/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2020/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2021/// that binds a [`RestartPolicy`] through the trait-idiomatic
2022/// [`std::borrow::Cow<'static, str>`] axis — a future
2023/// `axum::response::IntoResponse` composer whose per-policy
2024/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2025/// borrowed return, a future M4 admission-webhook rejection body
2026/// that composes the accepted-policy enumeration through the same
2027/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2028/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2029/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2030/// emitter on a per-child-policy diagnostic column — reaches the same
2031/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2032/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2033/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2034/// paired [`std::fmt::Display`], [`AsRef<str>`],
2035/// [`RestartPolicy::as_str`], and the four
2036/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2037/// forward-projection corners already return.
2038///
2039/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2040/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2041/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2042/// str` lifetime by construction (each `match` arm resolves to a
2043/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2044/// with static lifetime), so the zero-alloc borrowed arm is the
2045/// type-correct projection with no runtime allocation.
2046///
2047/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2048/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2049/// From<T> for Cow<'static, str>`), so the paired sibling
2050/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2051/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2052/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2053/// [`Cow<'static, str>`]-bound call site — every such site is forced
2054/// through a `Cow::Borrowed(policy.as_str())` /
2055/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2056/// no compile-time link back to the substrate primitive until this
2057/// lift.
2058///
2059/// Second peer to extend the substrate-wide trait-idiomatic
2060/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2061/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2062/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2063/// tier of the campaign (both sibling peers, `RestartStrategy` and
2064/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2065/// forward projection) so the remaining eleven peers
2066/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2067/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2068/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2069/// `FerriteRuntime`) are the future targets. Every future arm addition
2070/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2071/// might reach for once the three canonical OTP restart policies stop
2072/// covering the substrate's discovered load-shape) grows the
2073/// Cow<'static, str> axis by construction through one caixa-core edit
2074/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2075/// across every future Cow<'static, str>-bound consumer site.
2076///
2077/// Pinned load-bearing by
2078/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2079/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2080/// against [`RestartPolicy::as_str`] across the three-arm
2081/// [`RestartPolicy::ALL`]) and
2082/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2083/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2084/// for &'static str`], [`From<RestartPolicy> for String`], and
2085/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2086/// `.iter().copied().map(Cow::from)` pipe witness over
2087/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2088/// through the [`Cow<'static, str>`] axis alone and pins the
2089/// zero-alloc discipline on every element).
2090impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2091    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2092        std::borrow::Cow::Borrowed(policy.as_str())
2093    }
2094}
2095
2096/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2097/// output* forward projection on the M2 OTP-shape per-child-restart
2098/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2099/// companion to the paired owned-input
2100/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2101/// immediately above (0612398). Routes byte-for-byte through the same
2102/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2103/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2104/// that holds a `&RestartPolicy` and needs a
2105/// [`std::borrow::Cow<'static, str>`] — a
2106/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2107/// per-arm accept-set materializer (whose iterator over
2108/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2109/// `RestartPolicy`, so the paired owned-input
2110/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2111/// alone forces every call site through an explicit `.copied()` /
2112/// dereference / [`Copy`]-bound restatement rather than the direct
2113/// trait-idiomatic projection), a future generic
2114/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2115/// on a per-child-policy diagnostic column that walks the
2116/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2117/// webhook rejection body that composes the accepted-policy
2118/// enumeration from an iterated
2119/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2120/// per-arm `match p { … }` cascade — reaches the same three-arm
2121/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2122/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2123/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2124/// paired [`std::fmt::Display`], [`AsRef<str>`],
2125/// [`RestartPolicy::as_str`], the four
2126/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2127/// forward-projection corners, and the paired owned-input
2128/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2129/// already return.
2130///
2131/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2132/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2133/// [`RestartPolicy::as_str`] accessor's return carries the
2134/// `&'static str` lifetime by construction (each `match` arm resolves
2135/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2136/// with static lifetime), so the zero-alloc borrowed arm is the
2137/// type-correct projection with no runtime allocation.
2138///
2139/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2140/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2141/// one commit prior (0612398) on the paired owned-input
2142/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2143/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2144/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2145/// which carries both {Self, &Self} × Cow<'static, str> corners since
2146/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2147/// closed it on the top-level [`crate::CaixaKind`] one commit after
2148/// the owning half (99c1735) landed. This lift closes the whole M2
2149/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2150/// forward-projection campaign on both input-shape corners
2151/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2152/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2153/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2154/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2155/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2156/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2157/// standard library does not carry a blanket
2158/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2159/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2160/// closed-set fieldless typed enum peer on the substrate that carries
2161/// the paired owned-input [`Cow<'static, str>`] axis but not the
2162/// borrowed-input axis forces every borrowed-input
2163/// [`Cow<'static, str>`]-parameterized call site through a spurious
2164/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2165/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2166/// bounds have no compile-time link to the substrate primitive.
2167///
2168/// Pinned load-bearing by
2169/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2170/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2171/// against [`RestartPolicy::as_str`] across the three-arm
2172/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2173/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2174/// (cross-axis partition pin against the paired owned-input
2175/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2176/// paired borrowed-input owned-`&'static str`
2177/// [`From<&RestartPolicy> for &'static str`], and the paired
2178/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2179/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2180/// over [`RestartPolicy::ALL`] — whose iterator yields
2181/// `&RestartPolicy` by construction, so the borrowed-input
2182/// [`Cow<'static, str>`] axis is what routes the pipe through the
2183/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2184/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2185/// spurious [`Copy`] deref).
2186impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2187    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2188        std::borrow::Cow::Borrowed(policy.as_str())
2189    }
2190}
2191
2192/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2193/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2194/// closed-set fieldless typed enum — extends the substrate-wide
2195/// `Box<str>` forward-projection campaign tier opened one commit prior
2196/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2197/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2198/// typed enum peer on the caixa surface (`:children :restart`),
2199/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2200/// b4dc55c) closed the
2201/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2202/// corner on this enum. Routes byte-for-byte through the
2203/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2204/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2205/// so every consumer that binds a
2206/// `let key: Box<str> = policy.into();`-shaped call site — a
2207/// per-child metric-key materializer that stashes the policy
2208/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2209/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2210/// hierarchical reconciliation scheduler's per-child restart-decision
2211/// fan-out carries), a future admission-webhook rejection body whose
2212/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2213/// handle — reaches the same three-arm lifted
2214/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2215/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2216/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2217/// sibling
2218/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2219/// forward-projection corner already returns. Rust's standard library
2220/// carries `impl From<&str> for Box<str>` and
2221/// `impl From<String> for Box<str>` but no blanket
2222/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2223/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2224/// this axis is a distinct trait-idiomatic surface that a downstream
2225/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2226/// no other — without a `Box::from(policy.as_str())` open-code whose
2227/// type bounds have no compile-time link back to the substrate
2228/// primitive.
2229///
2230/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2231/// forward-projection family opened on the sibling-restart
2232/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2233/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2234/// projection campaign's owned-input corner on both M2 OTP-shape
2235/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2236/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2237/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2238/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2239/// are the future targets of the campaign.
2240///
2241/// Pinned load-bearing by
2242/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2243/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2244/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2245/// surface, plus a blanket-derived [`Into`] shape witness).
2246impl From<RestartPolicy> for Box<str> {
2247    fn from(policy: RestartPolicy) -> Box<str> {
2248        Box::<str>::from(policy.as_str())
2249    }
2250}
2251
2252/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2253/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2254/// closed-set fieldless typed enum — the borrowed-input companion to
2255/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2256/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2257/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2258/// projection axis on the second (and third-and-final) M2 OTP-shape
2259/// closed-set fieldless typed enum peer on the caixa surface
2260/// (`:children :restart`), routing byte-for-byte through the
2261/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2262/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2263/// Every consumer that holds a `&RestartPolicy` and needs a
2264/// [`Box<str>`] — a
2265/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2266/// per-arm accept-set materializer (whose iterator over
2267/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2268/// `RestartPolicy`, so the paired owned-input
2269/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2270/// call site through an explicit [`Copy`] deref or a
2271/// `.copied()` restatement rather than the direct trait-idiomatic
2272/// projection), a per-child metric-key materializer holding
2273/// `&RestartPolicy` through a `caixa-operator` hierarchical
2274/// reconciliation scheduler's borrow lifetime, a future admission-
2275/// webhook rejection body whose per-arm `Box<str>` field composes
2276/// from a borrowed `&RestartPolicy` handle — reaches the
2277/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2278/// this impl and no other, without a
2279/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2280/// have no compile-time link back to the substrate primitive.
2281///
2282/// Rust's standard library carries `impl From<&str> for Box<str>`
2283/// and `impl From<String> for Box<str>` but no blanket
2284/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2285/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2286/// set fieldless typed enum peer on the substrate that carries the
2287/// paired owned-input `Box<str>` axis but not the borrowed-input
2288/// axis forces every borrowed-input `Box<str>`-parameterized call
2289/// site through a spurious [`Copy`] deref
2290/// (`Box::<str>::from((*policy).as_str())`) or a
2291/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2292/// have no compile-time link back to the substrate primitive.
2293///
2294/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2295/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2296/// — closes the whole `{Self, &Self}` input-shape corner of the
2297/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2298/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2299/// closed the paired [`Cow<'static, str>`] axis one commit after
2300/// its owning half (0612398) landed on this enum. The remaining
2301/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2302/// core / render-side / outside-caixa-core tiers are the future
2303/// targets of the [`Box<str>`] campaign.
2304///
2305/// Pinned load-bearing by
2306/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2307/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2308/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2309/// surface, plus a blanket-derived [`Into`] shape witness, a
2310/// cross-axis partition pin against the paired owned-input
2311/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2312/// input `{&'static str, String, Cow<'static, str>}` return-shape
2313/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2314/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2315/// by construction, so the borrowed-input [`Box<str>`] axis is
2316/// what routes the pipe through the substrate-primitive
2317/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2318/// deref).
2319impl From<&RestartPolicy> for Box<str> {
2320    fn from(policy: &RestartPolicy) -> Box<str> {
2321        Box::<str>::from(policy.as_str())
2322    }
2323}
2324
2325// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2326// supervisor surface — two more typed shadows over Erlang/OTP
2327// primitives the substrate now mechanically tracks (see
2328// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2329// theory/TYPED-ABSORPTION.md for the absorption arc).
2330gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2331gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2332
2333/// One child entry in the supervisor's `:children` list.
2334///
2335/// Every child references another caixa by `:caixa <nome>` + version
2336/// constraint. The supervisor materializes one ComputeUnit per entry.
2337#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2338#[serde(rename_all = "camelCase")]
2339pub struct ChildSpec {
2340    /// The child caixa's `:nome`. Must resolve via the same dependency
2341    /// resolution path as `:deps` (caixa-resolver).
2342    pub caixa: String,
2343
2344    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2345    /// [`crate::dep::Dep::versao`].
2346    pub versao: String,
2347
2348    /// Restart policy — an author-omitted slot degrades onto the
2349    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2350    /// (`permanent`, the Erlang/OTP worker-child default) through the
2351    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2352    /// to.
2353    #[serde(default)]
2354    pub restart: RestartPolicy,
2355}
2356
2357impl ChildSpec {
2358    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2359    /// accessor every consumer that reads the OTP-shape supervised
2360    /// child's identity keys off — returns the author-declared
2361    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2362    /// from the typed slot's own [`String`] storage.
2363    ///
2364    /// The `:children :caixa` slot carries the DNS-1123 label — the
2365    /// child caixa's `:nome` — that every emitted cluster artifact
2366    /// derives its `metadata.name` from verbatim: the rendered
2367    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2368    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2369    /// identity, and the per-child K8s Service `metadata.name` the
2370    /// future wasm-operator (M3) provisions for inter-child supervision-
2371    /// tree wiring. Every downstream consumer that fans on the child's
2372    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2373    /// per-child DNS-1123 gate at
2374    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2375    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2376    /// [`validate_no_self_supervision`] cross-slot equality check
2377    /// against the parent's `:nome`, every `SupervisorError` variant
2378    /// carrying the offending child caixa verbatim for `feira lint`
2379    /// rendering, the future wasm-operator's hierarchical reconciliation
2380    /// scheduler's per-child ComputeUnit-name projection, the future M4
2381    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2382    /// admission webhook).
2383    ///
2384    /// Prior to this lift the `.caixa` byte-string was accessed inline
2385    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2386    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2387    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2388    /// carriers' `child.caixa.clone()`, the dedup key's
2389    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2390    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2391    /// field-accesses that expressed no compile-time link back to the
2392    /// typed slot. A future extension of the `:children :caixa` axis to
2393    /// a richer author surface (a per-cluster alias table the operator
2394    /// pins through a future `:placement`-scoped slot on the supervisor
2395    /// tree, a namespace-qualified rewrite the M4 CR materializer
2396    /// applies per-CR, a per-child overlay from the future `:children
2397    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2398    /// acknowledges) would have had to be threaded through every
2399    /// open-coded copy in lockstep or one consumer would silently
2400    /// disagree with the peers on which caixa a given child resolves to
2401    /// — a child-set lookup that treated the name as `"cart-worker"`
2402    /// while the peer duplicate-detector treated it as
2403    /// `"tenant-a/cart-worker"` would silently split the
2404    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2405    /// self-supervision detector's parent-equality check, a two-consumer
2406    /// split at the validator far from the source `caixa.lisp` with no
2407    /// field naming the identity-drift root cause. Lifting the resolution
2408    /// rule to a typed method on the substrate primitive means every
2409    /// downstream consumer of the Supervisor's per-`:children` identity
2410    /// surface reaches for exactly one typed dispatch — the resolver's
2411    /// accept-set migrates as a unit on any future axis addition.
2412    ///
2413    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2414    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2415    /// mesh-slot surface — same "one typed dispatch on the substrate
2416    /// primitive, thin projections at each consumer" discipline extended
2417    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2418    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2419    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2420    /// accessor discipline for the shared substrate concept "another
2421    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2422    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2423    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2424    /// slot family's typed-accessor discipline now spans both the
2425    /// upgrade axis (`:upgrade-from`) and the supervision axis
2426    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2427    /// shape. Named `nome()` to match the tatara-lisp author-surface
2428    /// term the field's docstring already reaches for ("The child
2429    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2430    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2431    /// discipline the substrate already carries — the accessor's name
2432    /// maps directly onto the canonical caixa-identity vocabulary rather
2433    /// than shadowing the field's storage-side `caixa` label.
2434    #[must_use]
2435    pub const fn nome(&self) -> &str {
2436        self.caixa.as_str()
2437    }
2438
2439    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2440    /// requirement scalar accessor every consumer that reads the OTP-shape
2441    /// supervised child's version pin keys off — returns the author-declared
2442    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2443    /// the typed slot's own [`String`] storage.
2444    ///
2445    /// The `:children :versao` slot carries the Cargo-shaped semver
2446    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2447    /// which release of the supervised child caixa the OTP-shape supervisor
2448    /// tree materializes against — the same requirement grammar the peer
2449    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2450    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2451    /// and the shared [`crate::version::parse_requirement`] parser. Every
2452    /// downstream consumer that fans on the child's version pin keys off
2453    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2454    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2455    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2456    /// for `feira lint` rendering, every future per-cluster version-lock
2457    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2458    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2459    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2460    /// per-child version resolver, the future wasm-operator's per-child
2461    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2462    ///
2463    /// Prior to this lift the `.versao` byte-string was accessed inline at
2464    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2465    /// [`SupervisorSpec::validate`] requirement-gate call
2466    /// `require_valid_versao_requirement(&child.versao, …)` and the
2467    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2468    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2469    /// expressed no compile-time link back to the typed slot. A future
2470    /// extension of the `:children :versao` axis to a richer author surface
2471    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2472    /// flow, a lacre-projected concrete-version rewrite the operator
2473    /// materializes at CR-admission time, a future `:children :versao-lock`
2474    /// per-cluster override slot the wasm-operator's hierarchical
2475    /// reconciliation scheduler authors per-CR) would have had to be
2476    /// threaded through both open-coded copies in lockstep or one consumer
2477    /// would silently disagree with the peer on which release constraint a
2478    /// given child resolves to — the requirement-gate call reading
2479    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2480    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2481    /// the actual gate rejection input, a two-consumer split at the
2482    /// validator far from the source `caixa.lisp` with no field naming the
2483    /// version-pin drift root cause. Lifting the resolution rule to a typed
2484    /// method on the substrate primitive means every downstream
2485    /// requirement-facing consumer of the Supervisor's per-`:children`
2486    /// version-pin surface reaches for exactly one typed dispatch — the
2487    /// resolver's accept-set migrates as a unit on any future axis addition.
2488    ///
2489    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2490    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2491    /// surface — same "one typed dispatch on the substrate primitive, thin
2492    /// projections at each consumer" discipline extended onto the M2
2493    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2494    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2495    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2496    /// one accessor discipline for the shared substrate concept "another
2497    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2498    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2499    /// `:nome` scalar accessor — the pair
2500    /// `(nome(), versao_requirement())` jointly projects the
2501    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2502    /// that fans on per-child identity + version pin keys off, closing the
2503    /// last unlifted per-`:children` `String`-carry axis so every downstream
2504    /// per-`:children` reader now routes through a typed dispatch on the
2505    /// substrate primitive. Named `versao_requirement()` rather than
2506    /// `versao()` because the field's storage-side `.versao` label is
2507    /// already the author-surface term (`:versao`); the accessor's name
2508    /// carries the semantic role — the semver *requirement* string the
2509    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2510    /// so a raw field access and a typed dispatch read differently at every
2511    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2512    /// naming discipline verbatim.
2513    #[must_use]
2514    pub const fn versao_requirement(&self) -> &str {
2515        self.versao.as_str()
2516    }
2517
2518    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2519    /// per-child post-exit restart-decision policy scalar accessor every
2520    /// consumer that dispatches on the supervised child's post-exit
2521    /// reconcile posture keys off — returns the author-declared
2522    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2523    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2524    /// storage.
2525    ///
2526    /// The `:children :restart` slot carries the closed-set OTP-shaped
2527    /// per-child restart-decision policy discriminator
2528    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2529    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2530    /// on abnormal exit, the OTP `transient` clean-completion-aware
2531    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2532    /// `temporary` one-shot default) that every downstream consumer of
2533    /// the Supervisor's per-child post-exit reconcile branch keys off.
2534    /// Every future downstream consumer that fans on the per-child
2535    /// restart-decision keys off this scalar (the future `feira app
2536    /// graph` per-child restart column, the future wasm-operator's
2537    /// per-child post-exit restart-decision branch, the future M4
2538    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2539    /// admission webhook, the `caixa-operator`'s hierarchical
2540    /// reconciliation scheduler's per-child post-exit reconcile branch,
2541    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2542    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2543    /// pin threads through).
2544    ///
2545    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2546    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2547    /// scalar accessor and the M3 mesh-slot
2548    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2549    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2550    /// — same "one typed dispatch on the substrate primitive,
2551    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2552    /// the downstream renderer's per-arm fan-out" discipline extended
2553    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2554    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2555    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2556    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2557    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2558    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2559    /// on the sibling `String`-carry axes. The triple
2560    /// `(nome(), versao_requirement(), restart())` jointly projects the
2561    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2562    /// tree consumer that fans on per-child identity + version pin +
2563    /// restart-decision keys off, closing the last unlifted per-`:children`
2564    /// axis so every downstream per-`:children` reader now routes through
2565    /// a typed dispatch on the substrate primitive. Named `restart()` to
2566    /// match the storage field's name and the author-surface
2567    /// `:children :restart` slot term verbatim; the accessor's identity
2568    /// name maps onto the canonical OTP-shape per-child restart-decision-
2569    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2570    /// carries.
2571    ///
2572    /// Declared `pub const fn` to close the last non-`const`
2573    /// `Copy`-return raw-field-getter posture on the M2
2574    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2575    /// of the sibling M2 per-`:supervisor`
2576    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2577    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2578    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2579    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2580    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2581    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2582    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2583    /// downstream substrate-side `const`-context consumer of the
2584    /// per-`:children` restart-decision-policy scalar (a future
2585    /// module-scope `const _:() = assert!(matches!(child.restart(),
2586    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2587    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2588    /// admission-webhook `const fn` per-child restart-decision floor
2589    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2590    /// composer over the substrate primitive that fans on the per-child
2591    /// restart-decision policy at compile time) now reaches through the
2592    /// same typed dispatch on the substrate primitive at const-eval
2593    /// time as at runtime. A future non-`Copy`-return promotion of the
2594    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2595    /// per-child restart-decision axis once heterogeneous per-cluster
2596    /// restart-policy overlays land, a per-tenant restart-policy-alias
2597    /// table the M4 CR materializer resolves per-CR) that would drop
2598    /// the `const` qualifier fails the fail-before-pass-after pin
2599    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2600    /// build time rather than surfacing as a downstream consumer
2601    /// regression.
2602    #[must_use]
2603    pub const fn restart(&self) -> RestartPolicy {
2604        self.restart
2605    }
2606}
2607
2608/// Supervisor-typed slots that live alongside the standard Caixa
2609/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2610/// the manifest stays a single typed form; this struct exists for
2611/// validation + conversion.
2612#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2613#[serde(rename_all = "camelCase")]
2614pub struct SupervisorSpec {
2615    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2616    #[serde(default)]
2617    pub estrategia: RestartStrategy,
2618
2619    /// Max restarts within [`Self::restart_window`] before the
2620    /// supervisor itself terminates (and its parent supervisor decides
2621    /// what to do). Default 5.
2622    #[serde(default = "default_max_restarts")]
2623    pub max_restarts: u32,
2624
2625    /// Sliding window for `max_restarts`. Authored as a duration
2626    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2627    /// is rejected by [`Self::validate`] — Erlang/OTP's
2628    /// `MaxIntensity / Period` invariant requires a positive window
2629    /// (a zero-period supervisor either trips on the first failure or
2630    /// never trips, depending on operator interpretation, neither of
2631    /// which is the author's intent). Omit the slot to express "no
2632    /// reset"; carry a positive duration to express the sliding window.
2633    #[serde(
2634        default,
2635        skip_serializing_if = "Option::is_none",
2636        with = "duration_codec"
2637    )]
2638    pub restart_window: Option<Duration>,
2639
2640    /// Static children. Empty for `SimpleOneForOne` (children added
2641    /// dynamically); required for the other three strategies.
2642    #[serde(default)]
2643    pub children: Vec<ChildSpec>,
2644}
2645
2646const fn default_max_restarts() -> u32 {
2647    // Route the private serde-`#[serde(default = "…")]` helper through
2648    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2649    // `pub const` rather than the raw `5` literal — one source of truth
2650    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2651    // default across the two production consumers that currently
2652    // dispatch on it (this helper via `#[serde(default = "…")]` on
2653    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2654    // impl at line 962). Pinned by
2655    // `default_max_restarts_helper_routes_through_lifted_default` +
2656    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2657    // in the tests module; peer of the sibling caixa-core
2658    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2659    // that now routes its author-omitted `:max-restarts` arm through
2660    // the same lifted constant.
2661    SUPERVISOR_MAX_RESTARTS_DEFAULT
2662}
2663
2664/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2665/// count default for the `:supervisor :max-restarts` axis — the
2666/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2667/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2668/// so every substrate-side consumer that resolves "what
2669/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2670/// `:max-restarts` slot degrade onto?" reaches for exactly one
2671/// substrate-primitive `u32`.
2672///
2673/// The `:max-restarts` default axis has two production consumers on the
2674/// substrate side today (both prior to this lift folded onto raw `5`
2675/// literals with no compile-time link back to a shared truth): the
2676/// serde-`#[serde(default = "default_max_restarts")]` helper on
2677/// [`SupervisorSpec::max_restarts`] that every author-omitted
2678/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2679/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2680/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2681/// the composed [`SupervisorSpec`] altitude reaches through
2682/// (`feira app graph`, the future wasm-operator's per-supervisor
2683/// restart-intensity counter, the future M4
2684/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2685/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2686/// A pair of open-coded `5`s across two files that expressed no
2687/// compile-time link back to the shared OTP-canonical default — a
2688/// future rebrand of the default (a tightening to Elixir's
2689/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2690/// the operator pins through a future
2691/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2692/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2693/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2694/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2695/// per-child-cohort roadmap lands) would have had to be threaded
2696/// through both open-coded copies in lockstep or the wire-format
2697/// author-omitted arm and the view-construction author-omitted arm
2698/// would silently disagree on which restart-budget an omitted
2699/// `:max-restarts` resolves to (an author writing `:supervisor
2700/// (:max-restarts ())` would round-trip through serde with the new
2701/// default while `supervisor_view` silently continued to compose the
2702/// stale `5`, or vice versa), a two-consumer split at the composition
2703/// boundary far from the source `caixa.lisp` with no field naming the
2704/// default-drift root cause. Lifting the resolution rule to a typed
2705/// `pub const` on the substrate primitive means every downstream
2706/// consumer of the per-Supervisor default-restart-budget-count surface
2707/// reaches for exactly one substrate-primitive `u32` — the resolver's
2708/// accepted value migrates as a unit on any future axis change.
2709///
2710/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2711/// worker-supervisor default (the closest canonical OTP-shape
2712/// production reference the substrate carries, matching the sibling
2713/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2714/// this constant with on the paired sliding-window axis). Two orders of
2715/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2716/// (the upper bracket on the same axis, sibling of this lower default;
2717/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2718/// axis and now share one accessor discipline on the substrate) and
2719/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2720/// restart floor — the "one restart, then escalate" default is
2721/// deliberately loose enough to absorb a short burst of transient
2722/// child failures without escalating past the supervisor's parent
2723/// while remaining tight enough to trip the `MaxIntensity / Period`
2724/// ratio's escalation on a genuinely-stuck child within the sibling
2725/// `60s` sliding window.
2726///
2727/// Lifted as a typed `pub const` so the bound has exactly one source
2728/// of truth — the serde-side wire-format author-omitted arm at
2729/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2730/// struct-literal default field, and the caixa-core
2731/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2732/// arm all read from one place. Same shape every other typed default
2733/// in this crate carries (the sibling
2734/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2735/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2736/// sibling `:restart-window` axis, and the peer
2737/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2738/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2739/// axes).
2740pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2741
2742/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2743/// validated [`SupervisorSpec::max_restarts`] past
2744/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2745///
2746/// The typed field is `u32` (the zero-floor arm
2747/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2748/// so a programmatic struct literal
2749/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2750/// author-surface form (`:max-restarts 4294967295` or any
2751/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2752/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2753/// runtime substrate consuming the value (Erlang/OTP's
2754/// `MaxIntensity / Period` ratio, the future wasm-operator's
2755/// per-supervisor restart-intensity counter, the M4
2756/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2757/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2758/// escalation threshold is structurally so high that no realistic
2759/// restarts-per-`:restart-window` traffic shape can reach it, the
2760/// supervisor never escalates to its parent, and a bad child can loop
2761/// inside the window indefinitely with the parent supervisor structurally
2762/// never receiving the "this subtree has exceeded its restart budget"
2763/// signal the typed slot is meant to express — the canonical
2764/// "supervisor intensity declared, no escalation" footgun, exactly the
2765/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2766/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2767/// "trip the next-higher protection layer after N events in a rolling
2768/// window" counters with identical degenerate-at-the-high-end shape).
2769///
2770/// The `1000` ceiling matches the sibling
2771/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2772/// peer — same "events-per-window trip threshold" semantics, same `u32`
2773/// type, same no-op-at-the-high-end failure mode) so the M4
2774/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2775/// and the future wasm-operator's per-supervisor restart-intensity
2776/// counter reach for either field knowing the value is in `1..=1000`
2777/// without re-validating at the reconciler layer. The cap sits two
2778/// orders of magnitude above every documented Erlang/OTP production
2779/// playbook recommendation (Learn You Some Erlang's
2780/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2781/// `max_restarts: 3` default, OTP's `supervisor` callback module
2782/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2783/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2784/// default) and below the clearly-pathological "effectively no
2785/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2786/// author can plausibly want at hyperscale (a long-running supervisor
2787/// over a very-flaky pool tolerating thousands of transient restarts
2788/// before escalating), but a hard wall above which the typed policy is
2789/// structurally a no-op carried verbatim on every emitted child-restart
2790/// reconciliation contract.
2791///
2792/// Lifted as a typed `pub const` so the bound has exactly one source of
2793/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2794/// materializer's admission webhook and the wasm-operator-side
2795/// per-supervisor restart-intensity reconciler read from one place. Same
2796/// shape every other typed upper bound in this crate carries
2797/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2798/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2799/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2800/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2801/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2802/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2803pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2804
2805/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2806/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2807/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2808/// (inclusive on both ends, integer-millisecond magnitudes by the
2809/// canonical-form gate immediately preceding).
2810///
2811/// The typed field is `Option<Duration>` (the zero-floor arm
2812/// [`SupervisorError::RestartWindowZero`] already rejects
2813/// `Some(Duration::ZERO)`, and the canonical-form arm
2814/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2815/// sub-millisecond residue), so a programmatic struct literal
2816/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2817/// .. }` — 24h) and the equivalent author-surface form
2818/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2819/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2820/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2821/// A `:restart-window` value far above the documented Erlang/OTP
2822/// `MaxIntensity / Period` production-playbook band (Learn You Some
2823/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2824/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2825/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2826/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2827/// degenerates the supervisor's restart-intensity counter into a
2828/// lifetime counter: the rolling failure-counting window is structurally
2829/// so long that transient restarts are never forgotten, so the
2830/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2831/// supervisor when the child has exceeded its restart budget *within
2832/// the recent window*" to "trip the parent when the child has exceeded
2833/// its restart budget *over its lifetime*" — every transient restart
2834/// counts against the budget forever, the supervisor's reset semantic
2835/// never reaches the child, and the typed `:restart-window` slot
2836/// becomes a no-op rolling window carried on every emitted hierarchical
2837/// reconciliation contract. The canonical
2838/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2839/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2840/// `:politicas :circuit-breaker :window` axis with identical shape (both
2841/// are "rolling failure-counting window with a per-`Period` reset" Duration
2842/// axes whose lifetime-counter degenerate at the high end is the same
2843/// "the reset semantic never fires" CSE invariant violation).
2844///
2845/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2846/// the shared duration codec emits (`"<n>h"` for any integer-hour
2847/// magnitude) — every value in the canonical authoring form's
2848/// `<integer><unit>` grammar at or below this cap renders to a clean
2849/// canonical string — and matches the three sibling typed-`Duration`
2850/// caps already lifted to this surface
2851/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2852/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2853/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2854/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2855/// per-supervisor `:supervisor :restart-window` — now share a single
2856/// uniform top edge at the codec's largest emitted unit so the next
2857/// typed-slot wiring (the future wasm-operator's per-supervisor
2858/// `MaxIntensity / Period` reconciler, the M4
2859/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2860/// webhook, the `caixa-operator`'s hierarchical reconciliation
2861/// scheduler) reaches for any of the four knowing the value is in
2862/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2863/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2864/// Riak Core / RabbitMQ production-playbook recommendation band
2865/// (`5s..=300s`) and below the clearly-pathological "rolling window
2866/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2867/// a value the author can plausibly want for a very-low-traffic
2868/// long-tail failure-restart window over a hyperscale-flaky child pool,
2869/// but a hard wall above which the rolling-window contract is
2870/// structurally a lifetime-counter contract.
2871///
2872/// Lifted as a typed `pub const` so the bound has exactly one source
2873/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2874/// materializer's admission webhook, the wasm-operator-side
2875/// per-supervisor `MaxIntensity / Period` reconciler, and the
2876/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2877/// from one place. Same shape every other typed upper bound in this
2878/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2879/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2880/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2881/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2882/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2883/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2884/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2885/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2886/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2887pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2888
2889/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2890/// default for the `:supervisor :restart-window` axis — the canonical
2891/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2892/// worker-supervisor default, extracted as a typed `pub const` so every
2893/// substrate-side consumer that resolves "what
2894/// [`SupervisorSpec::restart_window`] value does an author-omitted
2895/// `:restart-window` slot degrade onto?" reaches for exactly one
2896/// substrate-primitive [`Duration`].
2897///
2898/// The `:restart-window` default axis has one production consumer on the
2899/// substrate side today: the [`Default for SupervisorSpec`] impl's
2900/// struct-literal `restart_window` field, which prior to this lift folded
2901/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2902/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2903/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2904/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2905/// *not* fall back to this default on the sibling `:restart-window` axis
2906/// — an author-omitted `:supervisor :restart-window` composes to
2907/// `restart_window: None` (the shared codec's soft-swallow shape),
2908/// keeping author-declared intent ("no reset — never escalate on rolling
2909/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2910/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2911/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2912/// default was split across two files with no compile-time link between
2913/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2914/// `MaxIntensity` half at the substrate primitive while the `Period`
2915/// half rode as an open-coded literal at the composition site, so a
2916/// future coherent rebrand of the paired canonical (a tightening to
2917/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2918/// per-cluster overlay the operator pins through a future
2919/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2920/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2921/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2922/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2923/// roadmap lands) would have had to migrate the `MaxIntensity` half
2924/// through the lifted constant and the `Period` half through a raw
2925/// literal in lockstep or the two halves of the same OTP-canonical
2926/// default would silently drift out of pairing. Lifting the resolution
2927/// rule to a typed `pub const` on the substrate primitive means the
2928/// paired OTP-canonical default migrates as one unit on any future
2929/// axis change.
2930///
2931/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2932/// worker-supervisor default (the closest canonical OTP-shape
2933/// production reference the substrate carries, matching the paired
2934/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2935/// constant is the `Period` denominator of on the same
2936/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2937/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2938/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2939/// this lower default; both are typed [`Duration`] const bounds on the
2940/// `:supervisor :restart-window` axis and now share one accessor
2941/// discipline on the substrate) and above the OTP-`supervisor`
2942/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2943/// rolling window" default is deliberately loose enough to absorb a
2944/// short burst of transient child failures without escalating past the
2945/// supervisor's parent while remaining tight enough for the paired
2946/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2947/// stuck child within a human-scale observation window.
2948///
2949/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2950/// exactly one source of truth on each half — the sibling
2951/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2952/// `Period` `60s` half now share the same substrate-primitive lift
2953/// discipline. Same shape every other typed default in this crate
2954/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2955/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2956/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2957/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2958/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2959/// caixa-flux / caixa-helm rendering axes).
2960pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2961
2962/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2963/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2964/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2965/// worker-supervisor default, extracted as a typed `pub const` so every
2966/// substrate-side consumer that resolves "what
2967/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2968/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2969/// primitive [`RestartStrategy`].
2970///
2971/// The `:estrategia` default axis has three production consumers on the
2972/// substrate side today: the [`Default for RestartStrategy`] impl's
2973/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2974/// `estrategia` field, and the
2975/// [`crate::manifest::Caixa::supervisor_view`] fold's
2976/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2977/// collapse arm — three entry points onto the same OTP-canonical
2978/// `one_for_one` value that prior to this lift folded onto a raw
2979/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2980/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2981/// with no compile-time link back to the paired
2982/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2983/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2984/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2985/// triple was split across three altitudes with no compile-time link
2986/// between the halves: the `MaxIntensity` half rode through the lifted
2987/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2988/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2989/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2990/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2991/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2992/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2993/// intensity/period; an OTP `rest_for_one` widening once the substrate
2994/// discovers startup-order-coupled child cohorts as the more common
2995/// worker-supervisor default; a per-cluster overlay the operator pins
2996/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2997/// §III.2 supervision-canary roadmap acknowledges) would have had to
2998/// migrate the `MaxIntensity` + `Period` halves through the lifted
2999/// constants and the `one_for_one` half through an open-coded arm in
3000/// lockstep or the three halves of the same OTP-canonical default would
3001/// silently drift out of pairing. Lifting the resolution rule to a typed
3002/// `pub const` on the substrate primitive means the paired OTP-canonical
3003/// worker-supervisor default migrates as one unit on any future axis
3004/// change.
3005///
3006/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3007/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3008/// closest canonical OTP-shape production reference the substrate
3009/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3010/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3011/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3012/// failed child, leaving siblings untouched — is the default for tree-of-
3013/// independent-workers use cases the substrate's [`RestartStrategy`]
3014/// discriminator's own docstring already carries as the default arm; it
3015/// composes with the `{5, 60}` restart-intensity ratio to name the same
3016/// substrate-canonical "canonical worker-supervisor" shape the paired
3017/// halves close on their respective axes.
3018///
3019/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3020/// exactly one source of truth on each of its three halves — the sibling
3021/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3022/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3023/// this `one_for_one` strategy half now share the same substrate-
3024/// primitive lift discipline. Same shape every other typed default in
3025/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3026/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3027/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3028/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3029/// upper caps on the paired sibling axes, and the peer
3030/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3031/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3032pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3033
3034/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3035/// default for the `:children :restart` axis — the OTP `permanent`
3036/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3037/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3038/// `pub const` so every substrate-side consumer that resolves "what
3039/// [`ChildSpec::restart`] variant does an author-omitted `:children
3040/// :restart` slot degrade onto?" reaches for exactly one substrate-
3041/// primitive [`RestartPolicy`].
3042///
3043/// Completes the OTP-shape supervisor-tree default set at the substrate
3044/// primitive. The per-`:supervisor` axis already carries all three of its
3045/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3046/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3047/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3048/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3049/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3050/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3051/// the M2 `:supervisor` slot family. The split mattered because the two
3052/// axes resolve *together* on every author-omitted supervisor: a
3053/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3054/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3055/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3056/// `permanent` through an open-coded enum arm, so a future coherent
3057/// rebrand of the OTP-shape default set (an Elixir-shaped
3058/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3059/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3060/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3061/// once the substrate discovers clean-completion-aware children as the
3062/// more common child shape) would have had to migrate three halves
3063/// through typed constants and the fourth through a raw enum arm in
3064/// lockstep or the supervisor-level and child-level defaults would
3065/// silently drift apart.
3066///
3067/// The `:children :restart` default axis has two production consumers on
3068/// the substrate side today: the [`Default for RestartPolicy`] impl's
3069/// return arm, and the serde-side `#[serde(default)]` on
3070/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3071/// :restart` slot through that same impl. Both now key off this one
3072/// substrate primitive, so the future wasm-operator's per-child post-exit
3073/// restart-decision branch, the future M4
3074/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3075/// admission webhook, and the `caixa-operator`'s hierarchical
3076/// reconciliation scheduler's per-child fan-out all reach for one typed
3077/// identifier when they resolve an omitted per-child restart posture.
3078///
3079/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3080/// worker-child restart type — always restart the child regardless of how
3081/// it died, the canonical posture for long-running services that must
3082/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3083/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3084/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3085/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3086/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3087/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3088/// one-shot / clean-completion-aware postures an author declares
3089/// explicitly, never a posture an omitted slot should silently assume.
3090pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3091
3092/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3093/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3094/// `pub const fn` constructor rather than a struct-literal cascade over
3095/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3096/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3097/// lifted consts — one source of truth for the Erlang/OTP-canonical
3098/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3099/// paths every downstream consumer already reaches through (the
3100/// hand-authored-until-now [`Default::default`] the
3101/// `..SupervisorSpec::default()` struct-update-syntax on every
3102/// one-axis-under-test fixture in this crate's test module rests on,
3103/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3104/// every `const`-context consumer reaches through).
3105///
3106/// Extends the [`Default`]-through-const-ctor fold discipline the
3107/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3108/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3109/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3110/// and [`crate::BehaviorSpec`]
3111/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3112/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3113/// typed-slot spec family — extended here onto the M2 supervisor-slot
3114/// [`SupervisorSpec`] whose canonical baseline is not "everything
3115/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3116/// supervisor triple. The `empty()` peer's naming did not fit
3117/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3118/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3119/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3120/// the sibling `Option`-only slots fold to), so this peer is named
3121/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3122/// existing per-arm pin tests
3123/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3124/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3125/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3126/// already reach for. Pinned load-bearing by
3127/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3128/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3129/// [`PartialEq`], sharpening the sibling
3130/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3131/// pins from a per-field lift into a whole-struct one-source-of-truth
3132/// pin — the derived-until-now [`Default::default`] and the
3133/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3134/// construction, not by coincidence).
3135impl Default for SupervisorSpec {
3136    #[inline]
3137    fn default() -> Self {
3138        Self::otp_canonical()
3139    }
3140}
3141
3142impl SupervisorSpec {
3143    /// `const`-context peer of the [`Default for SupervisorSpec`]
3144    /// impl (which routes through this constructor) — returns the
3145    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3146    /// baseline this crate reaches for in every fixture-builder
3147    /// `..SupervisorSpec::default()` struct-update expression and
3148    /// every downstream `SupervisorSpec::default()` seed.
3149    ///
3150    /// Each field routes through the same substrate-canonical
3151    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3152    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3153    /// per-arm pin tests
3154    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3155    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3156    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3157    /// already assert, so a future coherent rebrand of the OTP-canonical
3158    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3159    /// cluster overlay via a future `:restart-window-overrides` slot, a
3160    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3161    /// absorption roadmap acknowledges) migrates through three typed
3162    /// constants in lockstep, and the paired [`Default`] impl inherits
3163    /// every future extension by construction.
3164    ///
3165    /// `pub const fn` rather than the derived-style `Default::default`
3166    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3167    /// [`Default::default`] is not `const` on stable Rust, and
3168    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3169    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3170    /// discipline lets `const`-context callers construct the OTP-
3171    /// canonical baseline at compile time without runtime dispatch on
3172    /// the derived [`Default::default`], the same posture the sibling
3173    /// [`crate::LimitsSpec::empty`] (9739971) /
3174    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3175    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3176    /// spec `pub const fn` constructors carry on the sibling
3177    /// "everything `None`" baseline axis.
3178    ///
3179    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3180    /// of the derived-style [`Default`]" family — sibling of the
3181    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3182    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3183    /// baseline" trio, extended here onto the M2 supervisor-slot
3184    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3185    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3186    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3187    /// than `empty()` to name the actual invariant the return value
3188    /// pins — the same phrasing already used in the per-arm pin tests
3189    /// on this file. Pinned load-bearing by
3190    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3191    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3192    #[must_use]
3193    pub const fn otp_canonical() -> Self {
3194        Self {
3195            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3196            max_restarts: default_max_restarts(),
3197            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3198            children: Vec::new(),
3199        }
3200    }
3201
3202    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3203    /// sibling-restart-strategy scalar accessor every consumer that
3204    /// dispatches on the supervisor's per-sibling restart-decision shape
3205    /// keys off — returns the author-declared `:supervisor :estrategia`
3206    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3207    /// the typed slot's own [`RestartStrategy`] storage.
3208    ///
3209    /// The `:supervisor :estrategia` slot carries the closed-set
3210    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3211    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3212    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3213    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3214    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3215    /// every child started after it, the Erlang/OTP `rest_for_one`
3216    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3217    /// dynamic children of the same shape, the Erlang/OTP
3218    /// `simple_one_for_one` per-session default) that every downstream
3219    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3220    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3221    /// paired coherently with the sibling `:children` axis
3222    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3223    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3224    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3225    /// downstream consumer that reads the strategy keys off this scalar
3226    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3227    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3228    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3229    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3230    /// strategy print line, the future wasm-operator's per-supervisor
3231    /// sibling-restart-strategy branch, the future M4
3232    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3233    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3234    /// reconciliation scheduler's per-strategy fan-out).
3235    ///
3236    /// Prior to this lift the `.estrategia` field was accessed inline at
3237    /// two production sites in `caixa-core/src/supervisor.rs` — the
3238    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3239    /// `match self.estrategia { … }` partition dispatch, and the
3240    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3241    /// carrier at `estrategia: self.estrategia` — two open-coded
3242    /// field-accesses that expressed no compile-time link back to the
3243    /// typed slot. A future extension of the `:supervisor :estrategia`
3244    /// axis to a richer author surface (a per-cluster strategy override
3245    /// the operator pins through a future `:supervisor :estrategia-overrides`
3246    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3247    /// acknowledges, a per-tenant strategy-alias table the M4 CR
3248    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3249    /// derivation the future adaptive-supervision engine computes from
3250    /// child-failure-history topology, a per-child-cohort strategy split
3251    /// the future `RestForCohort` extension acknowledged by the
3252    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3253    /// would have had to be threaded through every open-coded copy in
3254    /// lockstep — one consumer reading the raw variant while a peer read
3255    /// the operator-resolved variant would silently split the
3256    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3257    /// the actual partition-dispatch input the empty-children refusal
3258    /// arm reached under, a two-consumer split at the validator far from
3259    /// the source `caixa.lisp` with no field naming the strategy-drift
3260    /// root cause. Lifting the resolution rule to a typed method on the
3261    /// substrate primitive means every downstream consumer of the
3262    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3263    /// reaches for exactly one typed dispatch — the resolver's accept-set
3264    /// migrates as a unit on any future axis addition.
3265    ///
3266    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3267    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3268    /// per-`:placement` distribution-strategy axis — same "one typed
3269    /// dispatch on the substrate primitive, thin projections at each
3270    /// consumer" discipline extended onto the M2 supervisor-slot
3271    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3272    /// scalar axis. The two typed axes (`Placement::estrategia` on the
3273    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3274    /// Supervisor side) now share one accessor discipline for the shared
3275    /// substrate concept "a `Copy`-projected closed-set enum-arm
3276    /// discriminator that partitions the downstream renderer's per-arm
3277    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3278    /// `SupervisorSpec` type — companion to the sibling per-`:children`
3279    /// [`crate::ChildSpec::nome`] (57c61d0) /
3280    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3281    /// scalar accessors on the sibling per-`:children` `String`-carry
3282    /// axes. Named `estrategia()` to match the storage field's name and
3283    /// the peer [`crate::Placement::estrategia`] method-name discipline
3284    /// verbatim; the accessor's identity name maps onto the canonical
3285    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3286    /// docstring already carries.
3287    ///
3288    /// Declared `pub const fn` to close the M2 supervisor-slot
3289    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3290    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3291    /// (converted in this commit) `Copy`-composite-enum accessor, peer
3292    /// of the sibling M2 per-`:supervisor`
3293    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3294    /// already lifted, and mirror of the peer M3 mesh-slot
3295    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3296    /// `Copy`-return `pub const fn` scalar accessor whose method-name
3297    /// discipline this accessor was authored to match. Every downstream
3298    /// substrate-side `const`-context consumer of the per-`:supervisor`
3299    /// sibling-restart-strategy scalar (a future module-scope `const
3300    /// _:() = assert!(matches!(sup.estrategia(),
3301    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3302    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3303    /// admission-webhook `const fn` per-supervisor strategy-arm floor
3304    /// over a typed [`SupervisorSpec`], any future `const fn`
3305    /// supervisor-tree composer over the substrate primitive that fans
3306    /// on the sibling-restart-strategy at compile time) now reaches
3307    /// through the same typed dispatch on the substrate primitive at
3308    /// const-eval time as at runtime. A future non-`Copy`-return
3309    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3310    /// migration once the substrate grows per-cluster strategy overlays
3311    /// the [`SupervisorSpec`] docstring already anticipates, a
3312    /// per-tenant strategy-alias table the M4 CR materializer resolves
3313    /// per-CR) that would drop the `const` qualifier fails the
3314    /// fail-before-pass-after pin
3315    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3316    /// caixa-core build time rather than surfacing as a downstream
3317    /// consumer regression.
3318    #[must_use]
3319    pub const fn estrategia(&self) -> RestartStrategy {
3320        self.estrategia
3321    }
3322
3323    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3324    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3325    /// reads the supervisor's per-`:restart-window` restart-budget count
3326    /// keys off — returns the author-declared `:supervisor :max-restarts`
3327    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3328    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3329    /// borrow of `&self` past the call). Non-optional (the `u32` field
3330    /// carries the restart-budget count as a required axis with a
3331    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3332    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3333    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3334    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3335    ///
3336    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3337    /// `MaxIntensity` restart-budget count that pairs with the sibling
3338    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3339    /// restart-intensity ratio the supervisor trips its own escalation on
3340    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3341    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3342    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3343    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3344    /// upper-cap bracket at
3345    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3346    /// wasm-operator's per-supervisor restart-intensity counter's
3347    /// budget-vs-count comparator, the future M4
3348    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3349    /// webhook, the `caixa-operator`'s hierarchical reconciliation
3350    /// scheduler's per-supervisor escalation-decision branch, every
3351    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3352    /// offending count verbatim for `feira lint` rendering).
3353    ///
3354    /// Prior to this lift the `.max_restarts` field was accessed inline at
3355    /// one production site in `caixa-core/src/supervisor.rs` — the
3356    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3357    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3358    /// that expressed no compile-time link back to the typed slot. A
3359    /// future extension of the `:max-restarts` axis to a richer author
3360    /// surface (a per-cluster restart-budget override the operator pins
3361    /// through a future `:supervisor :max-restarts-overrides` slot the
3362    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3363    /// a per-tenant restart-budget-alias table the M4 CR materializer
3364    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3365    /// the future adaptive-supervision engine computes from child-failure-
3366    /// history topology, a promotion of the plain `u32` count to a richer
3367    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3368    /// budget-partition slot comes into scope) would have had to be
3369    /// threaded through every open-coded copy in lockstep or the validate
3370    /// gate and the future M4 emit path would silently disagree on which
3371    /// restart-budget count a given supervisor resolves to — an author's
3372    /// `:max-restarts 5` would satisfy validate while the emit path
3373    /// silently read a drifted other value (a `:max-restarts 10000`
3374    /// no-op supervisor at the emit boundary would carry the author's
3375    /// declared `5` verbatim in `feira lint` output while the future
3376    /// wasm-operator's restart-intensity counter operated under the
3377    /// drifted count), a two-consumer split at the validator far from the
3378    /// source `caixa.lisp` with no field naming the restart-budget-drift
3379    /// root cause. Lifting the resolution rule to a typed method on the
3380    /// substrate primitive means every downstream consumer of the
3381    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3382    /// for exactly one typed dispatch — the resolver's accept-set migrates
3383    /// as a unit on any future axis addition.
3384    ///
3385    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3386    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3387    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3388    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3389    /// the substrate primitive, thin projections at each consumer"
3390    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3391    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3392    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3393    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3394    /// one accessor discipline for the shared substrate concept "a
3395    /// `Copy`-projected required `u32` count that trips the next-higher
3396    /// protection layer after N events in a rolling window" — both are
3397    /// counters with identical degenerate-at-the-high-end shape and share
3398    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3399    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3400    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3401    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3402    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3403    /// the storage field's name verbatim and the peer
3404    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3405    /// accessor's identity maps onto the canonical OTP-shape supervision
3406    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3407    /// already carries.
3408    #[must_use]
3409    pub const fn max_restarts(&self) -> u32 {
3410        self.max_restarts
3411    }
3412
3413    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3414    /// `Period` sliding-window scalar accessor every consumer of the
3415    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3416    /// keys off — returns the author-declared `:supervisor :restart-window`
3417    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3418    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3419    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3420    /// value; no borrow of `&self` past the call). `None` when the slot is
3421    /// absent (the canonical "never reset — every restart across the
3422    /// supervisor's lifetime counts against the sibling `:max-restarts`
3423    /// budget" sentinel the field's own docstring names and the peer
3424    /// `validate_accepts_none_restart_window` pin locks in on the
3425    /// [`SupervisorSpec::validate`] entry-side).
3426    ///
3427    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3428    /// `Period` sliding-observation-interval that pairs with the sibling
3429    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3430    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3431    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3432    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3433    /// default). The typed slot's `Option<Duration>` accept-set —
3434    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3435    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3436    /// `Period > 0`; a zero period either trips on the first failure or
3437    /// never trips depending on operator interpretation, neither of which
3438    /// is the author's intent — omit the slot to express "no reset";
3439    /// carry a positive duration to express the sliding window),
3440    /// integer-millisecond canonical form enforced through
3441    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3442    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3443    /// future wasm-operator's per-supervisor restart-intensity counter
3444    /// quantizes at milliseconds), upper-bounded by
3445    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3446    /// supervisor rolling window any operationally-reachable supervisor
3447    /// can honor without spanning multiple scheduler epochs the
3448    /// hierarchical-reconciliation scheduler treats as independent) —
3449    /// maps onto the future wasm-operator (M3) per-supervisor
3450    /// restart-intensity counter's rolling-observation-interval, the
3451    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3452    /// per-`spec.restartWindow` admission webhook, and the sibling
3453    /// `duration_codec`-serialized wire scalar every downstream consumer
3454    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3455    /// keys off.
3456    ///
3457    /// Prior to this lift the `.restart_window` field was accessed inline
3458    /// at one production site in `caixa-core/src/supervisor.rs` — the
3459    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3460    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3461    /// open-coded field-access that expressed no compile-time link back to
3462    /// the typed slot. A future extension of the `:restart-window` axis to
3463    /// a richer author surface (a per-cluster restart-window override the
3464    /// operator pins through a future `:supervisor :restart-window-overrides`
3465    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3466    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3467    /// materializer resolves per-CR, a per-supervisor dynamic
3468    /// restart-window derivation the future adaptive-supervision engine
3469    /// computes from child-failure-history topology, a promotion of the
3470    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3471    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3472    /// partition slot comes into scope) would have had to be threaded
3473    /// through every open-coded copy in lockstep or the validate gate and
3474    /// the future M4 emit path would silently disagree on which
3475    /// restart-window a given supervisor resolves to — an author's
3476    /// `:restart-window "60s"` would satisfy validate while the emit path
3477    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3478    /// authored slot at the emit boundary would carry the author's
3479    /// declared window verbatim in `feira lint` output while the future
3480    /// wasm-operator's restart-intensity counter operated under a
3481    /// drifted window, or vice versa: an author's `:restart-window ()`
3482    /// would carry the "never reset" sentinel through validate while the
3483    /// emit path silently substituted a default sliding window), a
3484    /// two-consumer split at the validator far from the source
3485    /// `caixa.lisp` with no field naming the restart-window-drift root
3486    /// cause. Lifting the resolution rule to a typed method on the
3487    /// substrate primitive means every downstream consumer of the
3488    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3489    /// surface reaches for exactly one typed dispatch — the resolver's
3490    /// accept-set migrates as a unit on any future axis addition.
3491    ///
3492    /// Third `Copy`-return accessor on the M2 supervisor-slot
3493    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3494    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3495    /// payload rather than a `Copy`-scalar, and the per-`:children`
3496    /// [`crate::ChildSpec::nome`] (57c61d0) /
3497    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3498    /// scalar accessors already close the per-element `String`-carry
3499    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3500    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3501    /// per-outermost-call wall-clock-deadline axis and the peer M3
3502    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3503    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3504    /// three share the shared substrate concept "a `Copy`-projected
3505    /// optional `Duration` that carries a positive integer-millisecond
3506    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3507    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3508    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3509    /// bracket-helper the three axes each route through. Named
3510    /// `restart_window()` to match the storage field's name verbatim and
3511    /// the peer [`crate::LimitsSpec::wall_clock`] /
3512    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3513    /// accessor's identity maps onto the canonical OTP-shape supervision
3514    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3515    /// already carries.
3516    #[must_use]
3517    pub const fn restart_window(&self) -> Option<Duration> {
3518        self.restart_window
3519    }
3520
3521    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3522    /// static-child-list slice accessor every consumer that walks the
3523    /// supervisor's declared child set keys off — returns the author-
3524    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3525    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3526    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3527    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3528    /// through). Non-optional: an empty slice is the load-bearing
3529    /// "author declared `:children ()`" sentinel every consumer of the
3530    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3531    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3532    /// three strategies require a non-empty slice — the paired
3533    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3534    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3535    /// partition on both arms).
3536    ///
3537    /// The `:supervisor :children` slot carries the OTP-shaped static
3538    /// child list the supervisor materializes one ComputeUnit per
3539    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3540    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3541    /// through the tatara-lisp `:children` author surface onto a typed
3542    /// `Vec<ChildSpec>` whose per-element `(nome(),
3543    /// versao_requirement(), restart)` triple the per-child
3544    /// [`SupervisorSpec::validate`] loop already gates through the
3545    /// lifted [`ChildSpec::nome`] (57c61d0) /
3546    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3547    /// Every downstream consumer that fans on the static child list
3548    /// keys off this slice (the [`SupervisorSpec::validate`]
3549    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3550    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3551    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3552    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3553    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3554    /// materialization loop, the future M4
3555    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3556    /// admission-webhook fan-out, the future `feira app graph`
3557    /// per-supervisor tree-print traversal).
3558    ///
3559    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3560    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3561    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3562    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3563    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3564    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3565    /// validate loop's `for child in &self.children` traversal head —
3566    /// three open-coded field-accesses that expressed no compile-time
3567    /// link back to the typed slot. A future extension of the
3568    /// `:supervisor :children` axis to a richer author surface (a
3569    /// per-cluster child-set overlay the operator pins through a future
3570    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3571    /// supervision-canary roadmap acknowledges, a per-tenant
3572    /// child-set-alias table the M4 CR materializer resolves per-CR,
3573    /// a per-supervisor dynamic-child derivation the future adaptive-
3574    /// supervision engine computes from child-failure-history topology,
3575    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3576    /// `{static, dynamic}` partition once Erlang/OTP's
3577    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3578    /// would have had to be threaded through all three open-coded copies
3579    /// in lockstep or one consumer would silently disagree with the
3580    /// peers on which child-set a given supervisor resolves to — the
3581    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3582    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3583    /// would silently split the partition-dispatch's two-arm coherence
3584    /// (a supervisor that satisfies neither arm's precondition, or that
3585    /// satisfies both, at the cost of the paired
3586    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3587    /// silently drifting from the per-child validate loop's actual
3588    /// traversal input), a three-consumer split at the validator far
3589    /// from the source `caixa.lisp` with no field naming the
3590    /// child-set-drift root cause. Lifting the resolution rule to a
3591    /// typed method on the substrate primitive means every downstream
3592    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3593    /// surface reaches for exactly one typed dispatch — the resolver's
3594    /// accept-set migrates as a unit on any future axis addition.
3595    ///
3596    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3597    /// — the seed for the same "one typed dispatch on the substrate
3598    /// primitive, thin projections at each consumer" discipline the
3599    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3600    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3601    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3602    /// onto the first `Vec`-carry axis on the substrate. The four peer
3603    /// `Vec`-carry axes still unlifted at the time of this seed —
3604    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3605    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3606    /// (`Vec<Membro>` per-Aplicacao member list),
3607    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3608    /// per-Aplicacao WIT-typed edge list),
3609    /// [`crate::UpgradeFromEntry::instructions`]
3610    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3611    /// — inherit this accessor's discipline as future compounding runs
3612    /// migrate their consumers onto the shared slice-return shape.
3613    /// Fourth (and final) accessor on the M2 supervisor-slot
3614    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3615    /// [`SupervisorSpec::estrategia`] (eafb619) /
3616    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3617    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3618    /// the last unlifted per-`:supervisor` field axis (the
3619    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3620    /// per-`:supervisor` reader now routes through a typed dispatch on
3621    /// the substrate primitive. Named `children()` to match the storage
3622    /// field's name verbatim and the tatara-lisp author-surface term
3623    /// (`:children`) the field's own docstring already carries; the
3624    /// accessor's identity maps onto the canonical OTP-shape
3625    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3626    /// docstring already reaches for ("Static children ..."). Returns
3627    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3628    /// consumer of the child list treats it as a read-only sequence —
3629    /// the slice-view is the narrowest borrow that supports every
3630    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3631    /// index, `.len()`) without leaking the backing `Vec`'s
3632    /// grow/push/reserve surface that no consumer of the typed view
3633    /// reaches for (the storage-side `Vec` remains reachable through
3634    /// the `pub children` field for the mutation-carrying
3635    /// `Caixa::supervisor_view` fold-in path in
3636    /// `manifest.rs:supervisor_view`).
3637    #[must_use]
3638    pub const fn children(&self) -> &[ChildSpec] {
3639        self.children.as_slice()
3640    }
3641
3642    /// Validate the supervisor's typed shape — strategy ↔ children
3643    /// invariants, max_restarts > 0, restart_window > 0 when set,
3644    /// per-child non-empty + duplicate-free names.
3645    ///
3646    /// Mirrors the value-shape discipline applied to every other
3647    /// typed slot:
3648    ///
3649    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3650    ///     same "0 means the opposite of what you think" footgun
3651    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3652    ///     timeout as `infinite`), `:politicas :circuit-breaker
3653    ///     :window`, and `:limits :wall-clock`. The
3654    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3655    ///     `supervisor` requires `Period > 0`; a zero period either
3656    ///     trips on the first failure or never trips depending on
3657    ///     operator interpretation, neither of which is the
3658    ///     author's intent. Omit `:restart-window` to express "no
3659    ///     reset"; carry a positive duration to express the window.
3660    ///   - duplicate `:children` `:caixa` names are the same
3661    ///     graph-node-set / multiset distinction closed for
3662    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3663    ///     and `:entrada :paths` (eb3456d). Two children with the
3664    ///     same `:caixa` materialize as two ComputeUnits with the
3665    ///     same name in the cluster's HelmRelease values, one
3666    ///     silently overwriting the other. Erlang/OTP's
3667    ///     `child_spec.id` is required-unique per supervisor;
3668    ///     pleme-io enforces the same set-not-multiset shape on
3669    ///     `:caixa` (the load-bearing identity in our renderer).
3670    pub fn validate(&self) -> Result<(), SupervisorError> {
3671        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3672        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3673        // error carrier's `estrategia:` field through the lifted
3674        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3675        // `self.estrategia` field access — the two production consumers
3676        // of the per-`:supervisor` sibling-restart-strategy scalar now
3677        // key off exactly one typed dispatch on the substrate primitive,
3678        // so any future rebrand on the axis (a per-cluster strategy
3679        // override the operator pins through a future `:supervisor
3680        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3681        // the M4 CR materializer resolves per-CR) migrates as a single
3682        // caixa-core edit rather than a coordinated rewrite of the two
3683        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3684        // (921fe1b) four-consumer migration on the per-`:placement`
3685        // distribution-strategy axis.
3686        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3687        // dispatch's paired `.is_empty()` cross-slot refusal probes
3688        // (the `SimpleOneForOne`-arm
3689        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3690        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3691        // refusal) through the lifted [`SupervisorSpec::children`]
3692        // slice-return accessor rather than the raw `self.children`
3693        // field access — the two paired production consumers of the
3694        // per-`:supervisor` static-child-list scalar-shape now key off
3695        // exactly one typed dispatch on the substrate primitive, so any
3696        // future rebrand on the axis (a per-cluster child-set overlay
3697        // the operator pins through a future `:supervisor
3698        // :children-overrides` slot, a per-tenant child-set-alias table
3699        // the M4 CR materializer resolves per-CR) migrates as a single
3700        // caixa-core edit rather than a coordinated rewrite of the
3701        // paired arms — first slice-return migration on any typed slot,
3702        // seed for the peer per-`:placement :clusters`,
3703        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3704        // :instructions` `Vec`-carry axes.
3705        match self.estrategia() {
3706            RestartStrategy::SimpleOneForOne => {
3707                // SimpleOneForOne: children added at runtime. Static
3708                // list must be empty (one shape declared elsewhere).
3709                if !self.children().is_empty() {
3710                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3711                }
3712            }
3713            _ => {
3714                if self.children().is_empty() {
3715                    return Err(SupervisorError::no_children(self.estrategia()));
3716                }
3717            }
3718        }
3719        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3720        // axis. See [`crate::render::require_positive_bounded_u32`] for
3721        // the ordering discipline (zero-floor arm strictly precedes cap
3722        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3723        // diagnostic with its counter-axis remediation directly named,
3724        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3725        // cap-arm miss). Until this bracket landed the top edge ran all
3726        // the way to `u32::MAX` and a struct-literal
3727        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3728        // equivalent author-surface `:max-restarts 100000` /
3729        // `:max-restarts 4294967295` typo landing in the slot) silently
3730        // passed validate. The runtime substrate consuming the value
3731        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3732        // wasm-operator's per-supervisor restart-intensity counter, the
3733        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3734        // admission webhook) then turned a typed `:max-restarts`
3735        // policy into a no-op supervisor: the escalation threshold is
3736        // structurally so high that no realistic
3737        // restarts-per-`:restart-window` traffic shape can reach it,
3738        // the supervisor never escalates to its parent, and a bad
3739        // child can loop inside the window indefinitely with the
3740        // parent supervisor structurally never receiving the "this
3741        // subtree has exceeded its restart budget" signal the typed
3742        // slot is meant to express. The bracket set is
3743        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3744        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3745        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3746        // both are "trip the next-higher protection layer after N
3747        // events in a rolling window" counters with identical
3748        // degenerate-at-the-high-end shape and now share one canonical
3749        // bracket helper. The bracket precedes the sibling
3750        // `:restart-window` zero-floor / canonical-millisecond arms so
3751        // an over-cap `max_restarts` paired with a structurally invalid
3752        // window surfaces the bracket diagnostic first, mirroring the
3753        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3754        // ordering on the peer `:politicas :circuit-breaker` slot.
3755        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3756        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3757        // accessor rather than the raw `self.max_restarts` field access —
3758        // the one production consumer of the per-`:supervisor`
3759        // restart-budget-count scalar now keys off exactly one typed
3760        // dispatch on the substrate primitive, so any future rebrand on
3761        // the axis (a per-cluster restart-budget override the operator
3762        // pins through a future `:supervisor :max-restarts-overrides`
3763        // slot, a per-tenant restart-budget-alias table the M4 CR
3764        // materializer resolves per-CR) migrates as a single caixa-core
3765        // edit rather than a coordinated rewrite — sibling of the peer M3
3766        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3767        // the per-`:politicas :circuit-breaker :max-failures` axis.
3768        crate::render::require_positive_bounded_u32(
3769            self.max_restarts(),
3770            SUPERVISOR_MAX_RESTARTS_MAX,
3771            || SupervisorError::ZeroMaxRestarts,
3772            SupervisorError::max_restarts_exceeds_cap,
3773        )?;
3774        // Route the [`SupervisorSpec::validate`] `:restart-window`
3775        // zero-floor + integer-millisecond canonical-form + upper-cap
3776        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3777        // accessor rather than the raw `self.restart_window` field access —
3778        // the one production consumer of the per-`:supervisor`
3779        // restart-intensity-denominator scalar now keys off exactly one
3780        // typed dispatch on the substrate primitive, so any future rebrand
3781        // on the axis (a per-cluster restart-window override the operator
3782        // pins through a future `:supervisor :restart-window-overrides`
3783        // slot, a per-tenant restart-window-alias table the M4 CR
3784        // materializer resolves per-CR) migrates as a single caixa-core
3785        // edit rather than a coordinated rewrite — sibling of the peer M2
3786        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3787        // on the per-`:limits :wall-clock` axis and the peer M3
3788        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3789        // per-`:politicas :timeout` axis.
3790        if let Some(w) = self.restart_window() {
3791            // Zero-floor + integer-millisecond canonical-form +
3792            // upper-cap bracket on the typed `:restart-window` axis.
3793            // See
3794            // [`crate::render::require_positive_canonical_bounded_duration`]
3795            // for the full three-arm ordering discipline (zero-floor
3796            // strictly precedes canonical-form so `Duration::ZERO`
3797            // surfaces the self-locating `RestartWindowZero`
3798            // diagnostic; canonical-form strictly precedes the cap arm
3799            // so a sub-millisecond above-cap value surfaces the more
3800            // fundamental round-trip-shape diagnostic first) and the
3801            // three peer typed-`Duration` sites that share this
3802            // canonical bracket ([`crate::MeshPolicy::timeout`],
3803            // [`crate::CircuitBreaker::window`],
3804            // [`crate::LimitsSpec::wall_clock`]). Every validated
3805            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3806            // (1ms..=1h), integer-millisecond granularity.
3807            crate::render::require_positive_canonical_bounded_duration(
3808                w,
3809                SUPERVISOR_RESTART_WINDOW_MAX,
3810                || SupervisorError::RestartWindowZero,
3811                SupervisorError::restart_window_not_canonical,
3812                SupervisorError::restart_window_exceeds_cap,
3813            )?;
3814        }
3815        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3816        // detection fan-out loop through the lifted named per-slot gate
3817        // [`SupervisorSpec::validate_children`] rather than an inline
3818        // three-per-child cascade — every future consumer that wants to
3819        // re-check only the `:children` slot's per-entry axes (the M4
3820        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3821        // admission webhook re-validating one added/renamed child, the
3822        // future wasm-operator's per-child dynamic-add re-validator on
3823        // the `SimpleOneForOne` runtime-add path once dynamic-children
3824        // graduate to a typed slot, a future partial re-validator on a
3825        // per-`:children`-entry patch) reaches every per-entry axis
3826        // through one dispatch rather than re-inlining the three-arm
3827        // cascade in lockstep with `validate` or paying the peer
3828        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3829        // reach one entry check. Sibling of the peer M3 mesh-slot
3830        // per-slot gate family (`validate_membros` — the exact peer on
3831        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3832        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3833        // `validate_placement`; `validate_politicas` routing through
3834        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3835        // per-slot gate discipline now spans both the M3 mesh-slot
3836        // family and the M2 `:children` per-child-cascade axis on one
3837        // shape: one named per-slot gate per typed per-entry loop.
3838        self.validate_children()?;
3839        Ok(())
3840    }
3841
3842    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3843    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3844    /// gate, and duplicate-`:caixa` dedup arm into one call every
3845    /// consumer that wants to re-validate one `:children` entry (or the
3846    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3847    /// admits reaches through.
3848    ///
3849    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3850    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3851    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3852    /// duplicate-`:caixa` dedup), lifted to one named substrate
3853    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3854    /// materializer's admission webhook re-checking one added or renamed
3855    /// child, the future wasm-operator's per-child dynamic-add
3856    /// re-validator on the `SimpleOneForOne` runtime-add path once
3857    /// dynamic-children graduate to a typed slot, a future partial
3858    /// re-validator on a per-`:children`-entry patch — each reaches the
3859    /// three per-entry axes through this one dispatch rather than
3860    /// re-inlining the three-arm cascade in lockstep with `validate`
3861    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3862    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3863    /// reach one entry check.
3864    ///
3865    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3866    /// through [`SupervisorSpec::children`] rather than borrowing one
3867    /// threaded down from `validate`, the same posture the peer M3
3868    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3869    /// [`crate::AplicacaoSpec::validate_contratos`],
3870    /// [`crate::AplicacaoSpec::validate_entrada`],
3871    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3872    /// consumer that reaches this gate directly (without first calling
3873    /// `validate`) still runs the full per-child cascade — pinned by
3874    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3875    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3876    /// + `validate_children_is_self_contained_on_children_slot`.
3877    ///
3878    /// The three per-entry arms run in the same canonical order the
3879    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3880    /// the diagnostic every author-declared per-`:children` entry surfaces
3881    /// through `validate` is byte-equal to the diagnostic this gate
3882    /// surfaces when called directly — the equivalence-pin pair
3883    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3884    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3885    /// asserts the two altitudes discriminate the same set on every
3886    /// per-entry-covered input.
3887    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3888        let mut seen = std::collections::HashSet::new();
3889        for child in self.children() {
3890            // Every emitted cluster artifact's `metadata.name` for a
3891            // supervised child derives from this `:children :caixa` value
3892            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3893            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3894            // label value on every child's pod identity, and the per-
3895            // child K8s [`Service`][svc] `metadata.name` the future
3896            // wasm-operator (M3) provisions for inter-child supervision
3897            // tree wiring. Each apiserver-side schema on each landing
3898            // site enforces the DNS-1123 label rule on admission; a
3899            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3900            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3901            // UUID-shaped mistaken-identity slug) silently passes the
3902            // prior empty-/duplicate-only gate and the failure surfaces
3903            // at `kubectl apply` time as a `metadata.name: Invalid value`
3904            // rejection, far from the source caixa.lisp, with no field
3905            // naming the offending `:children` entry. Lifting the gate
3906            // to caixa-build time mirrors the `:membros :caixa` value-
3907            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3908            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3909            // identifier axis — the supervisor tree's child names —
3910            // through the lifted
3911            // [`crate::render::require_valid_dns_1123_label`] gate the
3912            // seven peer name axes (`:membros :caixa`, `:placement
3913            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3914            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3915            // route through, so drift between the eight axes' accepted
3916            // DNS-1123-label sets is structurally impossible.
3917            //
3918            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3919            crate::render::require_valid_dns_1123_label(
3920                child.nome(),
3921                || SupervisorError::EmptyChildName,
3922                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3923            )?;
3924            // The author surface for `:children :versao` is the same
3925            // Cargo-shaped semver requirement string `:deps :versao` and
3926            // `:membros :versao` carry — and the lacre pipeline resolves
3927            // all three axes through the same
3928            // [`crate::version::parse_requirement`] entry-point. The
3929            // shared [`crate::render::require_valid_versao_requirement`]
3930            // helper brackets the empty-first + parse cascade both peer
3931            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3932            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3933            // :versao`) route through, so drift between the three axes'
3934            // accepted requirement sets is structurally impossible and
3935            // the parse-side no-op the empty-first arm closes (semver's
3936            // empty parse yields an implicit `*`) lives in exactly one
3937            // predicate. Every `ChildSpec::versao` past validate is
3938            // round-trippable through [`crate::parse_requirement`]
3939            // without re-checking at the resolver layer, and the three
3940            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3941            // are now structurally equivalent by construction.
3942            crate::render::require_valid_versao_requirement(
3943                child.versao_requirement(),
3944                || SupervisorError::empty_child_version(child.nome()),
3945                |reason| {
3946                    SupervisorError::child_versao_invalid(
3947                        child.nome(),
3948                        child.versao_requirement(),
3949                        reason,
3950                    )
3951                },
3952            )?;
3953            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3954                SupervisorError::duplicate_child_caixa(child.nome())
3955            })?;
3956        }
3957        Ok(())
3958    }
3959}
3960
3961/// Cross-slot coherence gate on the supervision tree: no
3962/// `:children :caixa` entry may name the supervisor's own `:nome`.
3963///
3964/// A supervisor that lists itself as a child is a degenerate self-parent
3965/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3966/// specs reference *distinct* child processes; a supervisor is never its
3967/// own child), and the wasm-operator's hierarchical reconciliation would
3968/// otherwise be handed a node that is its own parent: a one-node cycle it
3969/// either rejects far from the source `caixa.lisp` or recurses on. Because
3970/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3971/// lacre closure root), a child whose `:caixa` equals the supervisor's
3972/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3973///
3974/// Lives outside [`SupervisorSpec::validate`] because the typed view
3975/// carries the children but not the parent `:nome`; mirrors the
3976/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3977/// (which likewise reads one slot against another at the
3978/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3979/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3980/// node to itself is structurally not a tree/mesh edge" discipline, here
3981/// on the supervision-tree axis.
3982pub fn validate_no_self_supervision(
3983    children: &[ChildSpec],
3984    parent_nome: &str,
3985) -> Result<(), SupervisorError> {
3986    for child in children {
3987        if child.nome() == parent_nome {
3988            return Err(SupervisorError::child_supervises_self(parent_nome));
3989        }
3990    }
3991    Ok(())
3992}
3993
3994#[derive(Debug, Error, PartialEq, Eq)]
3995pub enum SupervisorError {
3996    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3997    NoChildren { estrategia: RestartStrategy },
3998    #[error(
3999        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4000    )]
4001    SimpleOneForOneWithStaticChildren,
4002    #[error(":max-restarts must be > 0")]
4003    ZeroMaxRestarts,
4004    #[error(
4005        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4006         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4007         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4008         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4009         can reach it, so the supervisor never escalates to its parent and a bad child can \
4010         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4011         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4012         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4013         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4014         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4015         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4016         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4017         band) or restructure the supervision tree (split the flaky child into its own \
4018         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4019    )]
4020    MaxRestartsExceedsCap { max_restarts: u32 },
4021    #[error(
4022        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4023         requires Period > 0; a zero window either trips on the first failure or \
4024         never trips depending on operator interpretation. Omit :restart-window to \
4025         express `never reset`; carry a positive duration to express the window."
4026    )]
4027    RestartWindowZero,
4028    #[error(
4029        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4030         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4031         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4032         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4033         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4034    )]
4035    RestartWindowNotCanonical { window: Duration },
4036    #[error(
4037        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4038         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4039         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4040         failure-counting window is structurally so long that transient restarts are never \
4041         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4042         when the child has exceeded its restart budget within the recent window` to `trip the \
4043         parent when the child has exceeded its restart budget over its lifetime`, and the \
4044         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4045         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4046         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4047         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4048         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4049         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4050         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4051         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4052         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4053         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4054         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4055         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4056         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4057         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4058         hiding it behind a rolling-window declaration the cap arm rejects)"
4059    )]
4060    RestartWindowExceedsCap { window: Duration },
4061    #[error("child entry has empty :caixa name")]
4062    EmptyChildName,
4063    #[error(
4064        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4065         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4066         name / label value the child name lands in — the per-child \
4067         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4068         label value, and the future wasm-operator per-child Service `metadata.name` \
4069         — each apiserver-side schema rejects names that don't match; use a \
4070         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4071    )]
4072    ChildCaixaInvalid { caixa: String, reason: String },
4073    #[error("child {caixa:?} has empty :versao constraint")]
4074    EmptyChildVersion { caixa: String },
4075    #[error(
4076        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4077         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4078         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4079         `:membros :versao` carry; the lacre pipeline resolves all three \
4080         through the same parser)"
4081    )]
4082    ChildVersaoInvalid {
4083        caixa: String,
4084        versao: String,
4085        reason: String,
4086    },
4087    #[error(
4088        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4089         child_spec.id per supervisor; duplicate children materialize as duplicate \
4090         ComputeUnits in the rendered chart, one silently overwriting the other)"
4091    )]
4092    DuplicateChildCaixa { caixa: String },
4093    #[error(
4094        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4095         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4096         OTP child specs reference distinct child processes). Since every :nome is a \
4097         globally-unique substrate identity, a child naming the supervisor's own :nome \
4098         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4099         self-referential :children entry or rename it to the actual child caixa."
4100    )]
4101    ChildSupervisesSelf { caixa: String },
4102}
4103
4104// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4105// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4106// and [`validate_no_self_supervision`] onto one substrate primitive per
4107// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4108// `LayoutError`-envelope constructor families the peer
4109// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4110// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4111// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4112// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4113// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4114// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4115// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4116// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4117// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4118// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4119// variants on `{ de, para }`) already at that discipline on the peer
4120// `AplicacaoError` envelopes.
4121//
4122// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4123// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4124// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4125// self-supervision arm) opened the identical
4126// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4127// the exact "same block re-inlined at every consumer" shape the PRIME
4128// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4129// `AplicacaoError` families each closed on their sibling envelopes. The
4130// three variants share one `{ caixa: String }` shape, so the fold routes
4131// each wire-up site through one dispatch per typed variant.
4132//
4133// The macro below generates one static constructor per variant of shape
4134// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4135// collapses onto one dispatch:
4136// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4137// struct-literal on the same `&str` fixture. The uniform one-field
4138// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4139// macro — rather than at every wire-up site. Every constructor is
4140// `#[must_use]` so a caller who mistakenly discards the constructed error
4141// trips a compile warning at the wire-up site.
4142//
4143// Every future consumer that wants to construct one of these three
4144// variants outside `SupervisorSpec::validate_children` /
4145// `validate_no_self_supervision` — a deferred
4146// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4147// webhook re-checking one added/renamed child, a future
4148// `feira validate --supervisor` per-caixa admission verb, a per-child
4149// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4150// once dynamic-children graduate to a typed slot, a per-Supervisor
4151// overlay resolver rejecting a duplicate/self-supervising child against
4152// a cluster-local snapshot — now reaches each variant through one call
4153// rather than re-inlining the three-line struct-literal in lockstep
4154// with the three in-crate wire-up sites.
4155macro_rules! supervisor_caixa_only_ctors {
4156    ($($ctor:ident => $variant:ident),* $(,)?) => {
4157        impl SupervisorError {
4158            $(
4159                #[doc = concat!(
4160                    "Construct a [`SupervisorError::",
4161                    stringify!($variant),
4162                    "`] naming the offending `:children :caixa` (or ",
4163                    "supervisor `:nome`, on the self-supervision arm). ",
4164                    "Folds the uniform `Self::",
4165                    stringify!($variant),
4166                    " { caixa: caixa.to_string() }` one-field ",
4167                    "struct-literal onto one substrate primitive so ",
4168                    "every [`SupervisorSpec::validate_children`] / ",
4169                    "[`validate_no_self_supervision`] wire-up on this ",
4170                    "variant reads through one dispatch rather than the ",
4171                    "pre-lift open-coded struct-literal block."
4172                )]
4173                #[must_use]
4174                pub fn $ctor(caixa: &str) -> Self {
4175                    Self::$variant { caixa: caixa.to_string() }
4176                }
4177            )*
4178        }
4179    };
4180}
4181
4182supervisor_caixa_only_ctors! {
4183    empty_child_version => EmptyChildVersion,
4184    duplicate_child_caixa => DuplicateChildCaixa,
4185    child_supervises_self => ChildSupervisesSelf,
4186}
4187
4188// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4189// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4190// one substrate primitive per typed variant — the M2 supervisor-side siblings
4191// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4192// already lifted through the sibling
4193// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4194// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4195// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4196// String }` two-slot shape the peer seven-variant
4197// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4198// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4199// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4200// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4201// variant carries the `{ caixa: String, versao: String, reason: String }`
4202// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4203// carries on the same `:versao` value-shape.
4204//
4205// Each of the two wire-up sites opened the same closure-shaped
4206// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4207// [versao: child.versao_requirement().to_string(),] reason }` block inside
4208// the paired [`crate::render::require_valid_dns_1123_label`] and
4209// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4210// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4211// as a bug, on the same altitude the peer `AplicacaoError` /
4212// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4213// families already closed on their sibling envelopes.
4214//
4215// The two `#[must_use]` inherent constructors below fold each wire-up onto
4216// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4217// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4218// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4219// The uniform per-field `.to_string()` / `.into()` construction is spelled
4220// once — inside each ctor body — rather than at every wire-up site. The
4221// `reason: impl Into<String>` bound accepts both `&str` literals and
4222// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4223// diagnostic shape at the lift, matching the peer
4224// [`aplicacao_field_reason_ctors!`] and
4225// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4226// sibling envelopes.
4227//
4228// Every future consumer that wants to construct one of these two variants
4229// outside `SupervisorSpec::validate_children` — a deferred
4230// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4231// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4232// `feira validate --supervisor` per-caixa admission verb, a per-child
4233// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4234// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4235// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4236// cluster-local snapshot — now reaches each variant through one call rather
4237// than re-inlining the per-shape struct-literal block in lockstep with the
4238// two in-crate wire-up sites.
4239impl SupervisorError {
4240    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4241    /// offending `:children :caixa` value under the given `reason`. Folds
4242    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4243    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4244    /// primitive so every wire-up on this variant reads through one
4245    /// dispatch, matching the peer
4246    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4247    /// sibling `AplicacaoError { caixa: String, reason: String }`
4248    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4249    /// outputs through the `impl Into<String>` bound.
4250    #[must_use]
4251    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4252        Self::ChildCaixaInvalid {
4253            caixa: caixa.to_string(),
4254            reason: reason.into(),
4255        }
4256    }
4257
4258    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4259    /// offending `:children :caixa` and its `:versao` requirement under
4260    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4261    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4262    /// reason.into() }` three-slot struct-literal onto one substrate
4263    /// primitive so every wire-up on this variant reads through one
4264    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4265    /// { caixa, versao, reason }` three-slot axis on the peer
4266    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4267    /// and `format!(…)` outputs through the `impl Into<String>` bound.
4268    #[must_use]
4269    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4270        Self::ChildVersaoInvalid {
4271            caixa: caixa.to_string(),
4272            versao: versao.to_string(),
4273            reason: reason.into(),
4274        }
4275    }
4276}
4277
4278// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4279// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4280// three bracket-arms — one struct-literal at the `:children`-empty
4281// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4282// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4283// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4284// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4285// [`crate::render::require_positive_canonical_bounded_duration`]
4286// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4287// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4288// primitive per typed variant, matching the sibling
4289// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4290// variants on the same `{ <field>: Duration | u32 }` shape) at that
4291// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4292// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4293// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4294// wire-up site through one dispatch per typed variant without a runtime-
4295// work delta.
4296//
4297// Each of the four wire-up sites opened the identical
4298// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4299// exact "same block re-inlined at every consumer" shape the PRIME
4300// DIRECTIVE names as a bug, on the same altitude the peer
4301// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4302// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4303// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4304// the fold routes each wire-up site through one dispatch per typed
4305// variant.
4306//
4307// The macro below generates one static constructor per variant of shape
4308// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4309// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4310// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4311// fixture — as a direct call at the [`SupervisorSpec::validate`]
4312// `:children`-empty refusal, or as a bare function pointer in the
4313// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4314// [`crate::render::require_positive_bounded_u32`] /
4315// [`crate::render::require_positive_canonical_bounded_duration`] gate
4316// carries — rather than the pre-lift open-coded one-line closure over
4317// the same one-field struct-literal. `const fn` preserves the `Copy`-
4318// pass-through's zero-runtime-work property verbatim. Every constructor
4319// is `#[must_use]` so a caller who mistakenly discards the constructed
4320// error trips a compile warning at the wire-up site.
4321//
4322// Every future consumer that wants to construct one of these four
4323// variants outside `SupervisorSpec::validate` — a deferred
4324// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4325// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4326// `:restart-window` slot against the cap + canonical-form cascade, a
4327// future `feira validate --supervisor` per-caixa admission verb re-
4328// running the shape gates on demand, a per-Supervisor overlay resolver
4329// rejecting an author-supplied slot against a cluster-local snapshot —
4330// now reaches each variant through one call rather than re-inlining the
4331// per-shape struct-literal block in lockstep with the four in-crate
4332// wire-up sites.
4333macro_rules! supervisor_scalar_ctors {
4334    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4335        impl SupervisorError {
4336            $(
4337                #[doc = concat!(
4338                    "Construct a [`SupervisorError::",
4339                    stringify!($variant),
4340                    "`] naming the offending per-`:supervisor` `",
4341                    stringify!($field),
4342                    "` scalar. Folds the uniform `Self::",
4343                    stringify!($variant),
4344                    " { ",
4345                    stringify!($field),
4346                    " }` one-field `Copy`-pass-through struct-literal onto ",
4347                    "one substrate primitive so every per-axis wire-up on ",
4348                    "this variant reads through one dispatch — as a direct ",
4349                    "call (`SupervisorError::",
4350                    stringify!($ctor),
4351                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4352                    "the same `Copy`-`",
4353                    stringify!($ty),
4354                    "` fixture) or as a bare function pointer in the ",
4355                    "`impl FnOnce(",
4356                    stringify!($ty),
4357                    ") -> SupervisorError` bracket-closure slot every ",
4358                    "`crate::render::require_positive_bounded_*` / ",
4359                    "`crate::render::require_positive_canonical_bounded_*` ",
4360                    "gate carries — rather than the pre-lift open-coded ",
4361                    "one-line closure over the same one-field struct-",
4362                    "literal. `const fn` preserves the `Copy`-pass-through's ",
4363                    "zero-runtime-work property verbatim."
4364                )]
4365                #[must_use]
4366                pub const fn $ctor($field: $ty) -> Self {
4367                    Self::$variant { $field }
4368                }
4369            )*
4370        }
4371    };
4372}
4373
4374supervisor_scalar_ctors! {
4375    no_children => NoChildren { estrategia: RestartStrategy },
4376    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4377    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4378    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4379}
4380
4381/// Shared duration string codec for the typed slots that take a
4382/// duration (`restart_window`, `MeshPolicy::timeout`,
4383/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4384/// reuse it without duplicating the parser.
4385pub mod duration_codec {
4386    use super::Duration;
4387    use serde::{Deserializer, Serializer};
4388
4389    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4390        // Route through the canonical [`crate::render::serialize_option_via_str`]
4391        // — the substrate-side single-owner primitive for the forward
4392        // arm of the typed-magnitude codec family. See its docstring
4393        // for the full sibling roster.
4394        crate::render::serialize_option_via_str(v, s, render)
4395    }
4396
4397    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4398        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4399        // — the substrate-side single-owner primitive for the reverse
4400        // arm of the typed-magnitude codec family. See its docstring
4401        // for the full sibling roster.
4402        crate::render::deserialize_option_via_str(d, parse)
4403    }
4404
4405    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4406        // Paired whitespace-rejection arm — same canonical-form
4407        // render-determinism discipline as the peer
4408        // `limits::parse_byte_size` / `limits::parse_duration` /
4409        // `limits::parse_millicores` /
4410        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4411        // byte-scan closes the WhatWG-conformant whitespace bytes
4412        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4413        // `char::is_whitespace` scan closes the strictly-complementary
4414        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4415        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4416        // codepoints) that `str::trim` at parse entry silently strips.
4417        // Either drift class would round-trip through `render` to a
4418        // *different* canonical form on next emit — breaking the
4419        // THEORY.md Part V render-determinism contract on three typed-
4420        // duration slots at once (`:supervisor :restart-window`,
4421        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4422        // via the shared codec.
4423        //
4424        // Routed through the lifted [`crate::render::reject_whitespace`]
4425        // primitive — the substrate-side single-owner paired-arm gate
4426        // every typed-magnitude codec in caixa-core shares.
4427        crate::render::reject_whitespace::<String, _, _>(
4428            s,
4429            |b| {
4430                format!(
4431                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4432                 authoring form for the typed duration slots routed through this shared codec \
4433                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4434                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4435                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4436                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4437                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4438                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4439                 Part V render-determinism contract every typed slot carries. Strip every \
4440                 whitespace byte (write `\"30s\"` verbatim)"
4441                )
4442            },
4443            |ch| {
4444                format!(
4445                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4446                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4447                 duration slots routed through this shared codec (`:supervisor \
4448                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4449                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4450                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4451                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4452                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4453                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4454                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4455                 strips it at parse entry, and the value round-trips through `render` to \
4456                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4457                 the THEORY.md Part V render-determinism contract every typed slot \
4458                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4459                 verbatim with only ASCII bytes)",
4460                    cp = ch as u32
4461                )
4462            },
4463        )?;
4464        let s = s.trim();
4465        // Routed through the lifted
4466        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4467        // the single-owner split every ASCII-alphabetic-unit typed-
4468        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4469        // `limits::parse_duration` / this shared duration codec) shares.
4470        // See its docstring for the full sibling roster on the same
4471        // primitive altitude.
4472        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4473        let num_trim = num_part.trim();
4474        // The canonical authoring form for every typed slot routed
4475        // through this shared codec — `:supervisor :restart-window`,
4476        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4477        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4478        // non-negative integer with no decimal point and no leading
4479        // sign, so the parser's accepted set must match for
4480        // serialize/deserialize to round-trip without canonical-form
4481        // drift. Until this gate landed the parser accepted any
4482        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4483        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4484        // tripped the value to a *different* canonical string on the
4485        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4486        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4487        // — breaking the THEORY.md Part V render-determinism contract
4488        // on three typed slots at once. Same canonical-form discipline
4489        // `crate::limits::parse_duration` (818dd38, the immediate
4490        // predecessor on the peer `:limits :wall-clock` codec) applies;
4491        // this gate lifts the discipline onto the shared codec that
4492        // backs the remaining three typed-duration slots in caixa-core.
4493        //
4494        // Strict canonical form: every byte of the magnitude is an
4495        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4496        // inputs the gate distinguishes "non-canonical-but-numeric"
4497        // (parses as f64 or i64 — surfaced with a self-locating
4498        // diagnostic naming the canonical authoring form, the
4499        // round-trip drift each rejected shape would produce on first
4500        // serialize, and the canonical-form remediation) from
4501        // "garbage" (parses as neither — surfaced with the existing
4502        // narrower "bad duration magnitude" wording so its diagnostic
4503        // shape remains stable for the parser-shape footgun case).
4504        // The pre-existing `num < 0.0` arm is now unreachable — the
4505        // digit-only gate strictly precedes magnitude parsing, and a
4506        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4507        // non-canonical-but-numeric branch with the `-30` named
4508        // verbatim in the diagnostic rather than the prior
4509        // value-laundered "negative duration in \"-30s\"" wording.
4510        //
4511        // Routed through the lifted
4512        // [`crate::render::is_digit_only_magnitude`] predicate — the
4513        // same source of truth the four peer typed-magnitude codec
4514        // sites share.
4515        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4516        if !digit_only {
4517            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4518            if numeric {
4519                return Err(format!(
4520                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4521                     canonical authoring form for the typed duration slots routed through \
4522                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4523                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4524                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4525                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4526                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4527                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4528                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4529                     THEORY.md Part V render-determinism contract every typed slot carries. \
4530                     Pick an integer magnitude in the unit that divides cleanly (write \
4531                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4532                ));
4533            }
4534            return Err(format!("bad duration magnitude in {s:?}"));
4535        }
4536        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4537        // zero arm (4f46830) on the same canonical-form render-
4538        // determinism axis. The digit-only gate accepts `"030s"`,
4539        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4540        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4541        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4542        // *different* canonical string on the next emit, breaking the
4543        // THEORY.md Part V render-determinism contract the same way
4544        // `"+30s"` did before the leading-`+` arm landed. The single-
4545        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4546        // losslessly through `render` (`render(Duration::ZERO)` emits
4547        // `"0s"`) — the downstream semantic-zero gates (e.g.
4548        // `SupervisorError::ZeroRestartWindow` on
4549        // `:supervisor :restart-window`,
4550        // `AplicacaoError::PolicyTimeoutZero` /
4551        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4552        // duration slots) refuse zero-magnitude authoring at the typed-
4553        // validate layer above, so the single-byte `"0"` stays in the
4554        // accepted set at this codec layer and the diagnostic
4555        // partitioning between canonical-form drift (this arm) and
4556        // semantic-zero (the downstream gates) remains stable.
4557        // Peer with the future leading-zero arms on the two remaining
4558        // typed-magnitude codecs the trajectory acknowledges:
4559        // `limits::parse_duration` backing `:limits :wall-clock`,
4560        // `limits::parse_byte_size` backing `:limits :memory` — each
4561        // carries the same canonical-form-drift class today; this
4562        // gate lands the discipline on the shared duration codec
4563        // first because the `rate_limit_codec` predecessor on the
4564        // same canonical-form-drift axis is the closest peer on the
4565        // trajectory.
4566        //
4567        // Routed through the lifted
4568        // [`crate::render::is_leading_zero_padded_magnitude`]
4569        // predicate — the same source of truth the four peer
4570        // typed-magnitude codec sites share.
4571        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4572            return Err(format!(
4573                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4574                 canonical authoring form for the typed duration slots routed through \
4575                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4576                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4577                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4578                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4579                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4580                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4581                 serialize — breaking the THEORY.md Part V render-determinism contract \
4582                 every typed slot carries. Strip the leading zeros (write \
4583                 `\"30s\"` instead of `\"030s\"`)"
4584            ));
4585        }
4586        // The digit-only gate guarantees every byte is `[0-9]`, and
4587        // the leading-zero arm above guarantees the magnitude is
4588        // either the single byte `"0"` or starts with `[1-9]`, so
4589        // the only way `u64::from_str` can fail here is overflow (the
4590        // magnitude exceeds `u64::MAX`). Surface that with an
4591        // overflow-shaped wording so the diagnostic names the offending
4592        // magnitude verbatim rather than collapsing onto the
4593        // non-canonical arm. The codec now operates on `u64` end-to-end
4594        // — every accepted magnitude is integer-exact; no f64 mantissa
4595        // drift between author-supplied magnitude and the consumer's
4596        // `Duration` value. Same shape `crate::limits::parse_duration`
4597        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4598        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4599            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4600        })?;
4601        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4602        // unit-arm dispatch through the canonical
4603        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4604        // primitive — the substrate-side single-owner unit-dispatch
4605        // table every typed-duration codec in caixa-core routes
4606        // through (peer: `crate::limits::parse_duration` backing
4607        // `:limits :wall-clock`). Every unit conversion is integer-
4608        // exact for an integer magnitude; overflow surfaces via the
4609        // typed `DurationUnitError::Overflow { multiplier }`
4610        // discriminant so this arm reconstructs the pre-lift
4611        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4612        // wording verbatim from `num` / `unit_trim` / the returned
4613        // `multiplier`, and the unknown-unit arm reconstructs the
4614        // pre-lift `"unknown duration unit \"<other>\""` wording from
4615        // the caller-scoped `unit_trim`. Load-bearing pinned by
4616        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4617        let unit_trim = unit.trim();
4618        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4619            |e| match e {
4620                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4621                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4622                ),
4623                crate::render::DurationUnitError::UnknownUnit => {
4624                    format!("unknown duration unit {unit_trim:?}")
4625                }
4626            },
4627        )?;
4628        Ok(dur)
4629    }
4630
4631    /// Render a [`Duration`] in the canonical pleme-io duration string
4632    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4633    /// caixa typed-duration slot serializes to and the same form K8s
4634    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4635    /// EnvoyConfig per-route timeouts both expect (an integer
4636    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4637    /// `+`). Lifted to `pub` so caixa-side renderers
4638    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4639    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4640    /// emitter, the future caixa-otel collector pipeline emitter) can
4641    /// consume the same canonical formatter without re-inlining the
4642    /// magnitude/unit decision tree (and inheriting the same drift
4643    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4644    /// downstream apply-time parsing in non-obvious ways).
4645    pub fn render(d: Duration) -> String {
4646        let total_ms = d.as_millis();
4647        if total_ms == 0 {
4648            return "0s".into();
4649        }
4650        if total_ms.is_multiple_of(3600 * 1000) {
4651            return format!("{}h", total_ms / (3600 * 1000));
4652        }
4653        if total_ms.is_multiple_of(60 * 1000) {
4654            return format!("{}m", total_ms / (60 * 1000));
4655        }
4656        if total_ms.is_multiple_of(1000) {
4657            return format!("{}s", total_ms / 1000);
4658        }
4659        format!("{total_ms}ms")
4660    }
4661
4662    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4663    ///
4664    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4665    /// largest divisor unit, so any sub-millisecond residue
4666    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4667    /// §V.2.7 render-determinism contract:
4668    ///
4669    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4670    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4671    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4672    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4673    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4674    ///     on every typed-`Duration` slot then rejects on re-validate.
4675    ///
4676    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4677    /// the codec's round-trippable accepted set lives in exactly one place —
4678    /// every typed-`Duration` slot that routes through this shared codec
4679    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4680    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4681    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4682    /// every typed-`Duration` slot whose own codec shares the same
4683    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4684    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4685    /// pair) calls this predicate from its `validate()` to bracket the
4686    /// accepted set against the codec's accepted set, structurally. Drift
4687    /// between the codec's granularity and any typed slot's accepted set is
4688    /// then a single-source-of-truth edit at this predicate rather than a
4689    /// silent round-trip break the next consumer discovers at apply time.
4690    ///
4691    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4692    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4693    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4694    /// family — same "typed-slot's valid set matches its codec's accepted
4695    /// set, structurally" discipline carried at the codec layer.
4696    #[must_use]
4697    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4698        d.subsec_nanos().is_multiple_of(1_000_000)
4699    }
4700}
4701
4702/// Required-Duration variant for fields that aren't Option<Duration>.
4703pub mod duration_codec_required {
4704    use super::Duration;
4705    use serde::{Deserialize, Deserializer, Serializer};
4706
4707    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4708        s.serialize_str(&super::duration_codec::render(*v))
4709    }
4710
4711    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4712        let s = String::deserialize(d)?;
4713        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4714    }
4715}
4716
4717#[cfg(test)]
4718mod tests {
4719    use super::*;
4720
4721    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4722        ChildSpec {
4723            caixa: name.into(),
4724            versao: ver.into(),
4725            restart,
4726        }
4727    }
4728
4729    #[test]
4730    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4731        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4732        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4733        // posture. Each accessor projects the per-`:children :caixa`
4734        // / per-`:children :versao` [`String`] storage through the
4735        // `pub const fn` [`String::as_str`] (const-stable since Rust
4736        // 1.87, well within the workspace MSRV) — any future
4737        // accidental downgrade to non-`const` fails the corresponding
4738        // `<name>_via_const_fn` wrapper at caixa-core build time with
4739        // E0015 (`cannot call non-const method`), strictly stronger
4740        // than a runtime `assert!`. Sibling of the peer
4741        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4742        // family pins on the sibling `const`-eval-surface passes
4743        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4744        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4745        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4746        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4747        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4748        // [`crate::aplicacao::Entrada::destination`] at the M3
4749        // ingress axis,
4750        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4751        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4752        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4753        // axis, and the per-`:contratos`
4754        // [`crate::aplicacao::WitContract::source`] /
4755        // [`crate::aplicacao::WitContract::destination`] /
4756        // [`crate::aplicacao::WitContract::world_ref`] trio the
4757        // sibling pin at 279823b already anchors).
4758        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4759            c.nome()
4760        }
4761        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4762            c.versao_requirement()
4763        }
4764        for (caixa, versao) in [
4765            ("worker-a", "^0.1"),
4766            ("worker-b", "~0.2.3"),
4767            ("collector", "*"),
4768        ] {
4769            let c = child(caixa, versao, RestartPolicy::Permanent);
4770            assert_eq!(nome_via_const_fn(&c), c.nome());
4771            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4772            assert_eq!(c.nome(), caixa);
4773            assert_eq!(c.versao_requirement(), versao);
4774        }
4775    }
4776
4777    #[test]
4778    fn supervisor_children_slice_return_accessor_is_const_fn() {
4779        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4780        // `const`-eval-surface posture. The accessor destructures the
4781        // per-`:children` `Vec<ChildSpec>` storage through the
4782        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4783        // 1.66, well within the workspace MSRV) — any future
4784        // accidental downgrade to non-`const` fails
4785        // `children_via_const_fn` at caixa-core build time with E0015
4786        // (`cannot call non-const method`), strictly stronger than a
4787        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4788        // `Vec → &[T]` slice-return accessor family pin
4789        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4790        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4791        // per-`:membros` / per-`:contratos` slice-return axes, and of
4792        // the peer M2 upgrade-appup axis pin
4793        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4794        // on the per-`:upgrade-from :instructions` slice-return axis.
4795        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4796            s.children()
4797        }
4798        // Sweep both the empty-children (leaf-supervisor with no
4799        // static children — the `SimpleOneForOne` dynamic-child
4800        // arm's canonical shape) and the populated-children
4801        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4802        // arm's canonical shape) axes so the accessor carries a
4803        // const-dispatch pin on both arms.
4804        let s_empty = SupervisorSpec {
4805            estrategia: RestartStrategy::SimpleOneForOne,
4806            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4807            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4808            children: vec![],
4809        };
4810        assert!(children_via_const_fn(&s_empty).is_empty());
4811        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4812        let s_full = SupervisorSpec {
4813            estrategia: RestartStrategy::OneForOne,
4814            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4815            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4816            children: vec![
4817                child("worker-a", "^0.1", RestartPolicy::Permanent),
4818                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4819                child("collector", "*", RestartPolicy::Temporary),
4820            ],
4821        };
4822        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4823        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4824    }
4825
4826    #[test]
4827    fn default_has_one_for_one_and_5_restarts_in_60s() {
4828        let s = SupervisorSpec::default();
4829        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4830        assert_eq!(s.max_restarts, 5);
4831        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4832        assert!(s.children.is_empty());
4833    }
4834
4835    #[test]
4836    fn validate_one_for_one_requires_children() {
4837        let mut s = SupervisorSpec::default();
4838        s.children = vec![];
4839        assert!(matches!(
4840            s.validate().unwrap_err(),
4841            SupervisorError::NoChildren { .. }
4842        ));
4843        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4844        s.validate().unwrap();
4845    }
4846
4847    #[test]
4848    fn validate_simple_one_for_one_forbids_static_children() {
4849        let mut s = SupervisorSpec {
4850            estrategia: RestartStrategy::SimpleOneForOne,
4851            ..SupervisorSpec::default()
4852        };
4853        s.children
4854            .push(child("w", "^0.1", RestartPolicy::Permanent));
4855        assert_eq!(
4856            s.validate().unwrap_err(),
4857            SupervisorError::SimpleOneForOneWithStaticChildren
4858        );
4859        s.children.clear();
4860        s.validate().unwrap();
4861    }
4862
4863    #[test]
4864    fn validate_rejects_zero_max_restarts() {
4865        let s = SupervisorSpec {
4866            max_restarts: 0,
4867            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4868            ..SupervisorSpec::default()
4869        };
4870        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4871    }
4872
4873    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4874    //
4875    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4876    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4877    // `:supervisor :max-restarts` axis — both fields are "trip the
4878    // next-higher protection layer after N events in a rolling window"
4879    // counters with identical degenerate-at-the-high-end shape, so the
4880    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4881    // exactly as it lies in `1..=1000` on the breaker side.
4882
4883    #[test]
4884    fn validate_rejects_max_restarts_above_cap() {
4885        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4886        // 1` is structurally one past the cap and silently passed
4887        // validate on every pre-gate codebase because the typed slot's
4888        // only check was the zero-floor arm. The no-op-supervisor vector
4889        // only surfaced at the runtime substrate (Erlang/OTP
4890        // MaxIntensity/Period ratio, the future wasm-operator's
4891        // per-supervisor restart-intensity counter) far from the source
4892        // caixa.lisp with no field naming the offending supervisor.
4893        let s = SupervisorSpec {
4894            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4895            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4896            ..SupervisorSpec::default()
4897        };
4898        assert_eq!(
4899            s.validate().unwrap_err(),
4900            SupervisorError::MaxRestartsExceedsCap {
4901                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4902            }
4903        );
4904    }
4905
4906    #[test]
4907    fn validate_rejects_max_restarts_far_above_cap() {
4908        // The `u32::MAX` worst case — the four-billion-restart
4909        // threshold a typo (`:max-restarts 4294967295`) or a
4910        // struct-literal copy-paste lands in the slot. Pin the cap
4911        // arm's coverage explicitly across the full `u32` overflow so
4912        // a future relaxation that drops the upper bound surfaces
4913        // here. Same shape every other typed-cap arm on this surface
4914        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4915        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4916        let s = SupervisorSpec {
4917            max_restarts: u32::MAX,
4918            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4919            ..SupervisorSpec::default()
4920        };
4921        assert_eq!(
4922            s.validate().unwrap_err(),
4923            SupervisorError::MaxRestartsExceedsCap {
4924                max_restarts: u32::MAX,
4925            }
4926        );
4927    }
4928
4929    #[test]
4930    fn validate_accepts_max_restarts_at_cap() {
4931        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4932        // must validate. The cap is inclusive on the top edge,
4933        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4934        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4935        // discipline on the sibling capped axes. Pin the boundary
4936        // explicitly so a future off-by-one tightening
4937        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4938        // here as a test failure rather than a silent contract
4939        // narrowing.
4940        let s = SupervisorSpec {
4941            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4942            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4943            ..SupervisorSpec::default()
4944        };
4945        s.validate()
4946            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4947    }
4948
4949    #[test]
4950    fn validate_accepts_max_restarts_typical_values() {
4951        // The documented production-playbook band positive-control
4952        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4953        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4954        // through the hyperscale band (200, 500, 1000) the cap
4955        // accepts. Pin the inclusive validated set explicitly so a
4956        // future tightening of the ceiling surfaces here.
4957        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4958            let s = SupervisorSpec {
4959                max_restarts: n,
4960                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4961                ..SupervisorSpec::default()
4962            };
4963            s.validate()
4964                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4965        }
4966    }
4967
4968    #[test]
4969    fn zero_max_restarts_takes_precedence_over_cap() {
4970        // The cross-arm ordering pin: `0` is structurally outside
4971        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4972        // (cap), but the zero-floor diagnostic is the more
4973        // self-locating one (it directly names the counter-axis
4974        // remediation), so the validate gate must fire on zero first.
4975        // Same shape every other zero-then-shape ordering on this
4976        // surface uses (PolicyRetriesZero then
4977        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4978        // PolicyBreakerMaxFailuresExceedsCap).
4979        let s = SupervisorSpec {
4980            max_restarts: 0,
4981            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4982            ..SupervisorSpec::default()
4983        };
4984        assert_eq!(
4985            s.validate().unwrap_err(),
4986            SupervisorError::ZeroMaxRestarts,
4987            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4988        );
4989    }
4990
4991    #[test]
4992    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4993        // The cross-arm ordering pin between the cap and the sibling
4994        // `:restart-window` gates (zero-window, canonical-window). A
4995        // supervisor carrying both an over-cap `max_restarts` AND a
4996        // structurally invalid window (zero, sub-ms) must surface the
4997        // cap diagnostic first — the cap arm is wired immediately
4998        // after the zero-restart arm and strictly before the window
4999        // arms, so the offending value the diagnostic names matches
5000        // the order the author would discover the gates by reading
5001        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5002        // order so a future refactor that reorders the arms surfaces
5003        // here as a test failure rather than a silent diagnostic
5004        // regression. Peer of
5005        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5006        // on the sibling `:politicas :circuit-breaker` slot.
5007        let s = SupervisorSpec {
5008            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5009            restart_window: Some(Duration::ZERO),
5010            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5011            ..SupervisorSpec::default()
5012        };
5013        assert_eq!(
5014            s.validate().unwrap_err(),
5015            SupervisorError::MaxRestartsExceedsCap {
5016                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5017            },
5018            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5019        );
5020    }
5021
5022    #[test]
5023    fn max_restarts_cap_diagnostic_carries_offending_value() {
5024        // The diagnostic-shape pin: the offending `u32` is carried
5025        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5026        // variant so the surfaced error message names the value the
5027        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5028        // supervisor-policy ceiling …"`), not just the cap. Same
5029        // self-locating diagnostic shape every other typed-cap arm on
5030        // this surface carries
5031        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5032        // the offending failure count verbatim,
5033        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5034        // retries count verbatim).
5035        let s = SupervisorSpec {
5036            max_restarts: 50_000,
5037            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5038            ..SupervisorSpec::default()
5039        };
5040        let err = s.validate().unwrap_err();
5041        assert!(
5042            matches!(
5043                err,
5044                SupervisorError::MaxRestartsExceedsCap {
5045                    max_restarts: 50_000
5046                }
5047            ),
5048            "got {err:?}"
5049        );
5050        let msg = err.to_string();
5051        assert!(
5052            msg.contains("50000"),
5053            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5054        );
5055    }
5056
5057    #[test]
5058    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5059        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5060        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5061        // half of Learn You Some Erlang's worker-supervisor default,
5062        // sibling of the `60s` `Period` half that the paired
5063        // [`Default for SupervisorSpec`] impl already pins on the
5064        // sibling `restart_window` axis. Pinning the literal here
5065        // surfaces a future rebrand (a tightening to Elixir's `3`,
5066        // a widening to a per-cluster overlay the operator pins
5067        // through a future `:max-restarts-overrides` slot) as a
5068        // deliberate test edit, not a silent contract migration.
5069        // Peer of the sibling
5070        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5071        // upper-bracket pin on the same axis.
5072        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5073    }
5074
5075    #[test]
5076    fn default_max_restarts_helper_routes_through_lifted_default() {
5077        // Composition pin: the private `default_max_restarts()`
5078        // serde-`#[serde(default = "…")]` helper on
5079        // [`SupervisorSpec::max_restarts`] must route through the
5080        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5081        // typed `pub const` rather than a raw `5` literal. Prior to
5082        // the lift the helper carried an inline `5` with no compile-
5083        // time link back to the shared default, so the wire-format
5084        // author-omitted arm and the caixa-core
5085        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5086        // arm could silently split on any future default rebrand.
5087        // Byte-parity against the lifted constant closes the split.
5088        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5089    }
5090
5091    #[test]
5092    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5093        // Composition pin: the [`Default for SupervisorSpec`] impl's
5094        // struct-literal `max_restarts` field must route through the
5095        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5096        // typed `pub const` (via the private helper this test's
5097        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5098        // already pins onto the constant). Structurally: every
5099        // `SupervisorSpec::default()` call must yield a
5100        // `max_restarts` field byte-equal to the lifted constant
5101        // (the two paired defaults — the serde-side wire-format arm
5102        // and the struct-literal default arm — cannot silently split
5103        // on any future default rebrand). Peer of the sibling
5104        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5105        // — this pin closes the byte-parity arm on the two paired
5106        // altitude entry points onto the shared substrate constant.
5107        assert_eq!(
5108            SupervisorSpec::default().max_restarts(),
5109            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5110        );
5111    }
5112
5113    #[test]
5114    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5115        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5116        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5117        // Learn You Some Erlang's worker-supervisor default, paired
5118        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5119        // `MaxIntensity` half this constant is the sliding-window
5120        // denominator of on the same `MaxIntensity / Period`
5121        // restart-intensity ratio. Pinning the literal here surfaces a
5122        // future coherent rebrand of the paired default (Elixir's
5123        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5124        // the operator pins through a future
5125        // `:restart-window-overrides` slot) as a deliberate test edit,
5126        // not a silent contract migration. Peer of the sibling
5127        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5128        // paired-half pin on the same OTP-canonical default and the
5129        // [`supervisor_restart_window_cap_pins_canonical_value`]
5130        // upper-bracket pin on the same axis.
5131        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5132    }
5133
5134    #[test]
5135    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5136        // Composition pin: the [`Default for SupervisorSpec`] impl's
5137        // struct-literal `restart_window` field must route through the
5138        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5139        // typed `pub const` rather than a raw
5140        // `Duration::from_secs(60)` literal. Prior to this lift the
5141        // paired `{intensity, 5, 60}` OTP-canonical default was split
5142        // across two altitudes with no compile-time link between the
5143        // halves — the `MaxIntensity` half rode through the lifted
5144        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5145        // `Period` half rode as an open-coded literal at the
5146        // composition site, so a future coherent rebrand of the paired
5147        // canonical would have had to migrate one half through the
5148        // constant and the other through a raw literal in lockstep.
5149        // Byte-parity against the lifted constant on the `Period` half
5150        // closes the split — the paired OTP-canonical default now
5151        // migrates as one unit on any future axis change. Peer of the
5152        // sibling
5153        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5154        // byte-parity pin on the paired `MaxIntensity` half.
5155        assert_eq!(
5156            SupervisorSpec::default().restart_window(),
5157            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5158        );
5159    }
5160
5161    #[test]
5162    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5163        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5164        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5165        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5166        // canonical default, paired with the sibling
5167        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5168        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5169        // this constant is the strategy discriminator of on the same
5170        // OTP-canonical worker-supervisor default. Pinning the arm here
5171        // surfaces a future coherent rebrand of the paired triple (Elixir's
5172        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5173        // intensity/period axes leaving this strategy arm untouched, an OTP
5174        // `rest_for_one` widening once the substrate discovers startup-
5175        // order-coupled child cohorts as the more common worker-supervisor
5176        // shape, a per-cluster overlay the operator pins through a future
5177        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5178        // supervision-canary roadmap acknowledges) as a deliberate test
5179        // edit, not a silent contract migration. Peer of the sibling
5180        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5181        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5182        // paired-half pins on the same OTP-canonical default.
5183        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5184    }
5185
5186    #[test]
5187    fn restart_strategy_default_routes_through_lifted_default() {
5188        // Composition pin: the [`Default for RestartStrategy`] impl's
5189        // return arm must route through the substrate-canonical
5190        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5191        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5192        // an inline `Self::OneForOne` with no compile-time link back to
5193        // the shared OTP-canonical `one_for_one` strategy the paired
5194        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5195        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5196        // `.unwrap_or_default()` (now
5197        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5198        // so a future rebrand of the OTP-canonical strategy default (an
5199        // OTP `rest_for_one` widening once the substrate discovers
5200        // startup-order-coupled child cohorts as the more common worker-
5201        // supervisor shape, a per-cluster overlay the operator pins
5202        // through a future `:estrategia-overrides` slot) would have had to
5203        // be threaded through the `Default` impl and the two peer routes
5204        // in lockstep or the three consumers would silently split. Byte-
5205        // parity against the lifted constant closes the split. Peer of
5206        // the sibling
5207        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5208        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5209        // composition pins on the paired `MaxIntensity` + `Period` halves.
5210        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5211    }
5212
5213    #[test]
5214    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5215        // Composition pin: the [`Default for SupervisorSpec`] impl's
5216        // struct-literal `estrategia` field must route through the
5217        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5218        // `pub const` (either directly, or via the
5219        // [`RestartStrategy::default`] impl that the sibling
5220        // `restart_strategy_default_routes_through_lifted_default` pin
5221        // already routes onto the constant). Structurally: every
5222        // `SupervisorSpec::default()` call must yield an `estrategia`
5223        // field byte-equal to the lifted constant (the three paired
5224        // defaults — the [`Default for RestartStrategy`] impl arm, the
5225        // struct-literal default arm here, and the
5226        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5227        // silently split on any future default rebrand). Peer of the
5228        // sibling
5229        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5230        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5231        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5232        // of the same `SupervisorSpec::default()` composed altitude.
5233        assert_eq!(
5234            SupervisorSpec::default().estrategia(),
5235            SUPERVISOR_ESTRATEGIA_DEFAULT,
5236        );
5237    }
5238
5239    #[test]
5240    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5241        // Composition pin: the [`Default for SupervisorSpec`] impl must
5242        // route through the substrate-canonical
5243        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5244        // rather than a re-hand-authored struct-literal cascade. Sharpens
5245        // the sibling per-arm
5246        // `supervisor_spec_default_*_routes_through_lifted_default` pins
5247        // from a per-field lift into a whole-struct one-source-of-truth
5248        // pin — the derived-until-now [`Default::default`] and the
5249        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5250        // construction, not by coincidence.
5251        //
5252        // A future extension of the OTP-canonical baseline (a fifth
5253        // `restart_intensity` field the Erlang/OTP `#supervisor` record
5254        // grows, a per-child-cohort split of the `restart_window` /
5255        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5256        // CR materializer's admission-time overlay pass) reaches both
5257        // paths through exactly one edit on
5258        // [`SupervisorSpec::otp_canonical`] — the derived path could
5259        // silently disagree with the constructor's shape on any new
5260        // field whose [`Default::default`] resolves to a different arm
5261        // than the OTP-canonical baseline the constructor names, while
5262        // this delegated impl reaches the constructor directly and
5263        // picks up every future extension by construction.
5264        //
5265        // Fourth peer on the M2 / M3 typed-slot-spec
5266        // [`Default`]-through-const-ctor fold family — sibling of the
5267        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5268        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5269        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5270        // (91641a4), and [`crate::BehaviorSpec`]
5271        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5272        // per-`Option`-only-typed-slot folds — extended here onto the
5273        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5274        // is not "everything `None`" but the Erlang/OTP-canonical
5275        // `{one_for_one, 5, 60}` worker-supervisor triple.
5276        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5277    }
5278
5279    #[test]
5280    fn supervisor_spec_otp_canonical_byte_equals_default() {
5281        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5282        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5283        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5284        // pin already asserts against the [`Default::default`] path.
5285        // Sharpens the pair-invariant into a per-constructor pin so a
5286        // future extension of [`SupervisorSpec`] with a fifth field
5287        // whose OTP-canonical shape is non-`Default::default`-equivalent
5288        // trips at caixa-core test time rather than at a downstream
5289        // consumer that composed [`SupervisorSpec::otp_canonical`] with
5290        // [`SupervisorSpec::validate`] as its "canonical baseline
5291        // seed".
5292        let canonical = SupervisorSpec::otp_canonical();
5293        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5294        assert_eq!(canonical.max_restarts, 5);
5295        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5296        assert!(canonical.children.is_empty());
5297    }
5298
5299    #[test]
5300    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5301        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5302        // remain callable from a `const`-bound position so downstream
5303        // `const`-context callers wanting a canonical OTP-baseline seed
5304        // can construct one at compile time without runtime dispatch on
5305        // the derived [`Default::default`]. Peer of the sibling
5306        // `pub const fn` [`crate::LimitsSpec::empty`] /
5307        // [`crate::aplicacao::MeshPolicy::empty`] /
5308        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5309        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5310        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5311        // (a non-`const` field-default helper, a non-`const`-stable
5312        // container type promotion), this evaluation fails at
5313        // build time on this file rather than at a downstream
5314        // `const`-context call site.
5315        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5316        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5317        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5318        assert_eq!(
5319            CANONICAL.restart_window,
5320            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5321        );
5322        assert!(CANONICAL.children.is_empty());
5323    }
5324
5325    #[test]
5326    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5327        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5328        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5329        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5330        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5331        // half of the same OTP-shape supervisor-tree default set whose
5332        // per-`:supervisor` halves the sibling
5333        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5334        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5335        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5336        // arm here surfaces a future rebrand of the per-child default (an
5337        // OTP-`transient` widening once the substrate discovers clean-
5338        // completion-aware children as the more common child shape, a
5339        // per-cluster overlay the operator pins through a future
5340        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5341        // supervision-canary roadmap acknowledges) as a deliberate test
5342        // edit, not a silent contract migration. Peer of the sibling
5343        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5344        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5345        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5346        // value pins on the per-`:supervisor` halves.
5347        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5348    }
5349
5350    #[test]
5351    fn restart_policy_default_routes_through_lifted_default() {
5352        // Composition pin: the [`Default for RestartPolicy`] impl's return
5353        // arm must route through the substrate-canonical
5354        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5355        // than a raw `Self::Permanent` arm. Prior to the lift the impl
5356        // carried an inline `Self::Permanent` with no compile-time link
5357        // back to the OTP-shape supervisor-tree default set whose three
5358        // per-`:supervisor` halves already rode through lifted constants
5359        // — so a future coherent rebrand of the set would have had to
5360        // migrate three halves through typed constants and this fourth
5361        // through a raw enum arm in lockstep or the supervisor-level and
5362        // child-level defaults would silently drift apart. Byte-parity
5363        // against the lifted constant closes the split. Peer of the
5364        // sibling
5365        // [`restart_strategy_default_routes_through_lifted_default`]
5366        // composition pin on the per-`:supervisor` `:estrategia` axis.
5367        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5368    }
5369
5370    #[test]
5371    fn child_spec_serde_default_restart_routes_through_lifted_default() {
5372        // Composition pin: the serde-side `#[serde(default)]` on
5373        // [`ChildSpec::restart`] — the wire-format author-omitted
5374        // `:children :restart` arm — must resolve onto the substrate-
5375        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5376        // (via the [`Default for RestartPolicy`] impl the sibling
5377        // `restart_policy_default_routes_through_lifted_default` pin
5378        // already routes onto the constant). Structurally: a `ChildSpec`
5379        // deserialized from a payload that omits the `restart` key must
5380        // yield a `restart` field byte-equal to the lifted constant, so
5381        // the wire-format author-omitted arm and the
5382        // [`RestartPolicy::default`] impl arm cannot silently split on any
5383        // future default rebrand. Peer of the sibling
5384        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5385        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5386        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5387        // byte-parity pins on the per-`:supervisor` halves of the same
5388        // author-omitted-slot resolution surface.
5389        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5390            .expect("ChildSpec must deserialize with the restart key omitted");
5391        assert_eq!(
5392            omitted.restart(),
5393            SUPERVISOR_CHILD_RESTART_DEFAULT,
5394            "an author-omitted :children :restart slot must degrade onto \
5395             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5396             {:?}, expected {:?})",
5397            omitted.restart(),
5398            SUPERVISOR_CHILD_RESTART_DEFAULT,
5399        );
5400    }
5401
5402    #[test]
5403    fn supervisor_max_restarts_cap_pins_canonical_value() {
5404        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5405        // 1000 — the same ceiling the peer
5406        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5407        // `:politicas :circuit-breaker :max-failures` axis (both are
5408        // "trip the next-higher protection layer after N events in a
5409        // rolling window" counters with identical
5410        // degenerate-at-the-high-end shape; uniform top edge so the
5411        // M4 CR materializers and the wasm-operator reconciler reach
5412        // for either field knowing the value is in `1..=1000`). Two
5413        // orders of magnitude above every documented Erlang/OTP /
5414        // Elixir / Riak Core / RabbitMQ production-playbook
5415        // recommendation band and below the clearly-pathological
5416        // "effectively no escalation" floor (10_000, 100_000,
5417        // u32::MAX). Pinning the literal value here surfaces a future
5418        // drift (a relaxation to 10_000, a tightening to 100) as a
5419        // deliberate test edit, not a silent contract narrowing.
5420        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5421    }
5422
5423    #[test]
5424    fn validate_rejects_empty_child_name() {
5425        let s = SupervisorSpec {
5426            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5427            ..SupervisorSpec::default()
5428        };
5429        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5430    }
5431
5432    #[test]
5433    fn validate_rejects_empty_child_version() {
5434        let s = SupervisorSpec {
5435            children: vec![child("w", "", RestartPolicy::Permanent)],
5436            ..SupervisorSpec::default()
5437        };
5438        assert!(matches!(
5439            s.validate().unwrap_err(),
5440            SupervisorError::EmptyChildVersion { .. }
5441        ));
5442    }
5443
5444    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5445
5446    #[test]
5447    fn validate_rejects_invalid_child_versao_requirement() {
5448        // The fail-before-pass-after pin: a non-empty but malformed
5449        // semver requirement (`"^bad-version"`) silently passed
5450        // `validate()` on every pre-gate codebase because the prior
5451        // shape only refused the empty string. The parse failure
5452        // surfaced far downstream at lacre-resolve time with a
5453        // `semver::Error` that didn't name which `:children` entry
5454        // carried the typo. The new gate moves the check to caixa-build
5455        // time at the source caixa.lisp — the third `:versao` typed
5456        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5457        // structural parity.
5458        let s = SupervisorSpec {
5459            children: vec![
5460                child("worker", "^0.1", RestartPolicy::Permanent),
5461                child("cache", "^bad-version", RestartPolicy::Transient),
5462            ],
5463            ..SupervisorSpec::default()
5464        };
5465        let err = s.validate().unwrap_err();
5466        assert!(
5467            matches!(
5468                err,
5469                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5470                    if caixa == "cache" && versao == "^bad-version"
5471            ),
5472            "got {err:?}"
5473        );
5474    }
5475
5476    #[test]
5477    fn validate_rejects_child_versao_with_double_caret_typo() {
5478        // `"^^0.1"` is the canonical doubled-caret typo — looks
5479        // Cargo-shaped on first glance but fails the parser because
5480        // semver doesn't accept stacked operators. Pin this
5481        // adjacent-shape footgun explicitly so a future relaxation that
5482        // accepts "looks-canonical-but-isn't" forms surfaces here.
5483        let s = SupervisorSpec {
5484            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5485            ..SupervisorSpec::default()
5486        };
5487        let err = s.validate().unwrap_err();
5488        assert!(
5489            matches!(
5490                err,
5491                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5492                    if caixa == "worker" && versao == "^^0.1"
5493            ),
5494            "got {err:?}"
5495        );
5496    }
5497
5498    #[test]
5499    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5500        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5501        // semver requirement slot" typo — an author copies the
5502        // publish-side git-tag string verbatim into `:versao`, but
5503        // Cargo's semver parser rejects the leading `v`. Same
5504        // adjacent-shape footgun pinned for `:membros :versao`
5505        // (9888b13).
5506        let s = SupervisorSpec {
5507            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5508            ..SupervisorSpec::default()
5509        };
5510        let err = s.validate().unwrap_err();
5511        assert!(
5512            matches!(
5513                err,
5514                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5515                    if caixa == "worker" && versao == "v0.1"
5516            ),
5517            "got {err:?}"
5518        );
5519    }
5520
5521    #[test]
5522    fn validate_accepts_canonical_child_versao_forms() {
5523        // The Cargo-shaped requirement forms `:deps :versao` and
5524        // `:membros :versao` already accept via
5525        // `crate::parse_requirement` must pass the children gate
5526        // without re-validating at the resolver layer. Pin every leg so
5527        // a future tightening of the canonical set surfaces here as a
5528        // test failure.
5529        for form in [
5530            "^0.1",      // caret — minor-range pin (the most common shape)
5531            "~0.1.2",    // tilde — patch-range pin
5532            "0.1.0",     // exact — single-version pin
5533            "*",         // wildcard — any version (semver::VersionReq::STAR)
5534            ">=0.1, <2", // multi-range — comma-separated comparators
5535        ] {
5536            let s = SupervisorSpec {
5537                children: vec![child("worker", form, RestartPolicy::Permanent)],
5538                ..SupervisorSpec::default()
5539            };
5540            s.validate()
5541                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5542        }
5543    }
5544
5545    #[test]
5546    fn child_versao_empty_takes_precedence_over_invalid() {
5547        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5548        // doesn't try to parse) fires before the new
5549        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5550        // `:versao` keeps its narrower error message —
5551        // `parse_requirement` would also reject `""`, but the
5552        // empty-string arm is the more self-locating diagnostic for the
5553        // author. Same ordering discipline as
5554        // `membro_versao_empty_takes_precedence_over_invalid` in
5555        // aplicacao.rs.
5556        let s = SupervisorSpec {
5557            children: vec![child("worker", "", RestartPolicy::Permanent)],
5558            ..SupervisorSpec::default()
5559        };
5560        let err = s.validate().unwrap_err();
5561        assert!(
5562            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5563            "got {err:?}"
5564        );
5565    }
5566
5567    #[test]
5568    fn child_versao_invalid_fires_before_duplicate_check() {
5569        // Order pin: a malformed requirement on a non-duplicate entry
5570        // surfaces *its own* diagnostic (which names the offending
5571        // `:versao` string), even when a later entry would otherwise
5572        // collapse onto an earlier name. The per-entry shape gate runs
5573        // inline before the duplicate-key insert — parallel to
5574        // `membro_versao_invalid_fires_before_duplicate_check` in
5575        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5576        let s = SupervisorSpec {
5577            children: vec![
5578                child("worker", "^bad", RestartPolicy::Permanent),
5579                child("cache", "^0.1", RestartPolicy::Transient),
5580                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5581            ],
5582            ..SupervisorSpec::default()
5583        };
5584        let err = s.validate().unwrap_err();
5585        assert!(
5586            matches!(
5587                err,
5588                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5589            ),
5590            "got {err:?}"
5591        );
5592    }
5593
5594    #[test]
5595    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5596        // The diagnostic-shape pin: the error names the offending
5597        // `:versao` value verbatim so the author can grep their
5598        // caixa.lisp without re-running the build, and carries a
5599        // non-empty `reason` from `semver::VersionReq::parse` so the
5600        // parser's own wording flows through to the diagnostic.
5601        let s = SupervisorSpec {
5602            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5603            ..SupervisorSpec::default()
5604        };
5605        let err = s.validate().unwrap_err();
5606        let SupervisorError::ChildVersaoInvalid {
5607            caixa,
5608            versao,
5609            reason,
5610        } = err
5611        else {
5612            panic!("expected ChildVersaoInvalid, got other variant");
5613        };
5614        assert_eq!(caixa, "worker");
5615        assert_eq!(versao, "not-a-req");
5616        assert!(
5617            !reason.is_empty(),
5618            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5619        );
5620    }
5621
5622    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5623
5624    #[test]
5625    fn validate_rejects_child_caixa_with_uppercase() {
5626        // The canonical "I copied the Servico's display name verbatim"
5627        // typo — child caixa names are lowercase per K8s DNS-1123 label
5628        // rule. The diagnostic names the offending name and suggests the
5629        // lower-cased fix in one edit, mirroring the
5630        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5631        let s = SupervisorSpec {
5632            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5633            ..SupervisorSpec::default()
5634        };
5635        let err = s.validate().unwrap_err();
5636        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5637            panic!("expected ChildCaixaInvalid, got other variant");
5638        };
5639        assert_eq!(caixa, "Worker");
5640        assert!(
5641            reason.contains("uppercase"),
5642            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5643        );
5644        assert!(
5645            reason.contains("\"worker\""),
5646            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5647        );
5648    }
5649
5650    #[test]
5651    fn validate_rejects_child_caixa_with_underscore() {
5652        // The canonical "I'm thinking of a Python module / Postgres
5653        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5654        // label schema. K8s rejects `metadata.name: my_worker` at
5655        // admission time with an opaque `field is invalid` (no source-
5656        // citing diagnostic). The gate moves it to caixa-build time.
5657        let s = SupervisorSpec {
5658            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5659            ..SupervisorSpec::default()
5660        };
5661        let err = s.validate().unwrap_err();
5662        assert!(
5663            matches!(
5664                err,
5665                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5666                    if caixa == "my_worker" && reason.contains('_')
5667            ),
5668            "got {err:?}"
5669        );
5670    }
5671
5672    #[test]
5673    fn validate_rejects_child_caixa_with_dot() {
5674        // A `:children :caixa` entry is a single DNS-1123 label, not a
5675        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5676        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5677        // (3f9d7a0) on the peer name axis.
5678        let s = SupervisorSpec {
5679            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5680            ..SupervisorSpec::default()
5681        };
5682        let err = s.validate().unwrap_err();
5683        assert!(
5684            matches!(
5685                err,
5686                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5687                    if caixa == "team.worker" && reason.contains('.')
5688            ),
5689            "got {err:?}"
5690        );
5691    }
5692
5693    #[test]
5694    fn validate_rejects_child_caixa_with_leading_hyphen() {
5695        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5696        // with an alphanumeric. The K8s apiserver rejects `-worker`
5697        // outright; the renderer would emit a `metadata.name: "-worker"`
5698        // that fails admission far from the source caixa.lisp.
5699        let s = SupervisorSpec {
5700            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5701            ..SupervisorSpec::default()
5702        };
5703        let err = s.validate().unwrap_err();
5704        assert!(
5705            matches!(
5706                err,
5707                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5708                    if caixa == "-worker" && reason.contains("start and end")
5709            ),
5710            "got {err:?}"
5711        );
5712    }
5713
5714    #[test]
5715    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5716        // The symmetric arm of the boundary rule. Pin separately so
5717        // both ends of the label are covered against a future relaxation
5718        // that only checks one boundary.
5719        let s = SupervisorSpec {
5720            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5721            ..SupervisorSpec::default()
5722        };
5723        let err = s.validate().unwrap_err();
5724        assert!(
5725            matches!(
5726                err,
5727                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5728                    if caixa == "worker-"
5729            ),
5730            "got {err:?}"
5731        );
5732    }
5733
5734    #[test]
5735    fn validate_rejects_child_caixa_with_unicode() {
5736        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5737        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5738        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5739        // by the first byte that fails the `[a-z0-9-]` predicate.
5740        let s = SupervisorSpec {
5741            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5742            ..SupervisorSpec::default()
5743        };
5744        let err = s.validate().unwrap_err();
5745        assert!(
5746            matches!(
5747                err,
5748                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5749                    if caixa == "café"
5750            ),
5751            "got {err:?}"
5752        );
5753    }
5754
5755    #[test]
5756    fn validate_rejects_child_caixa_with_whitespace() {
5757        // Whitespace is the canonical "I pasted from a sketch / doc"
5758        // footgun. The apiserver rejects every `metadata.name` value
5759        // carrying whitespace; pin the gate fires at the right boundary.
5760        let s = SupervisorSpec {
5761            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5762            ..SupervisorSpec::default()
5763        };
5764        let err = s.validate().unwrap_err();
5765        assert!(
5766            matches!(
5767                err,
5768                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5769                    if caixa == "my worker"
5770            ),
5771            "got {err:?}"
5772        );
5773    }
5774
5775    #[test]
5776    fn validate_rejects_child_caixa_too_long() {
5777        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5778        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5779        // axis over the limit at admission time. The diagnostic names
5780        // both the cap and the actual length so the author can shorten
5781        // in one edit, mirroring `rejects_membro_caixa_too_long`
5782        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5783        let too_long = "a".repeat(64);
5784        let s = SupervisorSpec {
5785            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5786            ..SupervisorSpec::default()
5787        };
5788        let err = s.validate().unwrap_err();
5789        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5790            panic!("expected ChildCaixaInvalid, got other variant");
5791        };
5792        assert_eq!(caixa, too_long);
5793        assert!(
5794            reason.contains("63"),
5795            "diagnostic must name the 63-byte cap (got: {reason:?})"
5796        );
5797        assert!(
5798            reason.contains("64"),
5799            "diagnostic must name the actual length (got: {reason:?})"
5800        );
5801    }
5802
5803    #[test]
5804    fn child_caixa_max_length_validates() {
5805        // The 63-byte boundary control pin — exactly-at-the-cap is
5806        // accepted, mirroring `membro_caixa_max_length_validates`
5807        // (3f9d7a0) and `placement_cluster_max_length_validates`
5808        // (6cbb900). Pinned separately so a future off-by-one tightening
5809        // surfaces here.
5810        let max_label = "a".repeat(63);
5811        let s = SupervisorSpec {
5812            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5813            ..SupervisorSpec::default()
5814        };
5815        s.validate().unwrap();
5816    }
5817
5818    #[test]
5819    fn validate_accepts_canonical_child_caixa_forms() {
5820        // The realistic shapes a supervised child's `:caixa` carries —
5821        // single-word `worker`, version-suffixed `cache-v2`, single-char
5822        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5823        // `payment-retry`, all-digit `0`. Pin every leg so a future
5824        // tightening (e.g. requiring a leading lowercase letter) surfaces
5825        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5826        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5827        // (6cbb900).
5828        for form in [
5829            "worker",
5830            "cache-v2",
5831            "a",
5832            "db",
5833            "2-pool",
5834            "payment-retry",
5835            "0",
5836        ] {
5837            let s = SupervisorSpec {
5838                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5839                ..SupervisorSpec::default()
5840            };
5841            s.validate()
5842                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5843        }
5844    }
5845
5846    #[test]
5847    fn child_caixa_empty_takes_precedence_over_invalid() {
5848        // Order pin: the existing `EmptyChildName` diagnostic (which
5849        // doesn't try to parse the DNS-1123 shape) fires before the new
5850        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5851        // its narrower error message — `is_dns_1123_label` would reject
5852        // the empty string too (boundary check on the first byte), but
5853        // the empty-string arm is the more self-locating diagnostic for
5854        // the author. Same ordering discipline as
5855        // `membro_caixa_empty_takes_precedence_over_invalid` in
5856        // aplicacao.rs.
5857        let s = SupervisorSpec {
5858            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5859            ..SupervisorSpec::default()
5860        };
5861        let err = s.validate().unwrap_err();
5862        assert_eq!(err, SupervisorError::EmptyChildName);
5863    }
5864
5865    #[test]
5866    fn child_caixa_invalid_fires_before_versao_check() {
5867        // Order pin: the per-axis shape gate runs inline before the
5868        // per-entry versao check, so a malformed `:caixa` on an entry
5869        // whose `:versao` would also fail surfaces the more self-
5870        // locating name-axis diagnostic first. Parallel to
5871        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5872        // and `placement_cluster_invalid_fires_before_duplicate_check`
5873        // (6cbb900).
5874        let s = SupervisorSpec {
5875            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5876            ..SupervisorSpec::default()
5877        };
5878        let err = s.validate().unwrap_err();
5879        assert!(
5880            matches!(
5881                err,
5882                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5883            ),
5884            "got {err:?}"
5885        );
5886    }
5887
5888    #[test]
5889    fn child_caixa_invalid_fires_before_duplicate_check() {
5890        // Order pin: a malformed name on a non-duplicate entry surfaces
5891        // its own diagnostic, even when a later entry would otherwise
5892        // collapse onto an earlier name. The per-entry shape gate runs
5893        // inline before the duplicate-key HashSet insert, mirroring
5894        // `placement_cluster_invalid_fires_before_duplicate_check`
5895        // (6cbb900).
5896        let s = SupervisorSpec {
5897            children: vec![
5898                child("Worker", "^0.1", RestartPolicy::Permanent),
5899                child("cache", "^0.1", RestartPolicy::Transient),
5900                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5901            ],
5902            ..SupervisorSpec::default()
5903        };
5904        let err = s.validate().unwrap_err();
5905        assert!(
5906            matches!(
5907                err,
5908                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5909            ),
5910            "got {err:?}"
5911        );
5912    }
5913
5914    #[test]
5915    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5916        // The diagnostic-shape pin: the error names the offending
5917        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5918        // the author can grep their caixa.lisp without re-running the
5919        // build. Mirrors the diagnostic-shape sweep on every prior
5920        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5921        let s = SupervisorSpec {
5922            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5923            ..SupervisorSpec::default()
5924        };
5925        let err = s.validate().unwrap_err();
5926        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5927            panic!("expected ChildCaixaInvalid, got other variant");
5928        };
5929        assert_eq!(caixa, "My_Worker");
5930        assert!(
5931            !reason.is_empty(),
5932            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5933        );
5934    }
5935
5936    // ── value-shape: zero restart_window + duplicate child names ──────────
5937
5938    #[test]
5939    fn validate_accepts_none_restart_window() {
5940        // Omitted `:restart-window` is the "never reset" sentinel —
5941        // valid by design. Mirrors :limits axes where None = unbounded.
5942        let s = SupervisorSpec {
5943            restart_window: None,
5944            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5945            ..SupervisorSpec::default()
5946        };
5947        s.validate().unwrap();
5948    }
5949
5950    #[test]
5951    fn validate_rejects_zero_restart_window() {
5952        // Same "0 means the opposite of what you think" footgun closed
5953        // for :politicas :timeout (Envoy treats 0s as infinite) and
5954        // :limits :wall-clock (wasmtime traps before the call starts).
5955        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5956        let s = SupervisorSpec {
5957            restart_window: Some(Duration::ZERO),
5958            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5959            ..SupervisorSpec::default()
5960        };
5961        assert_eq!(
5962            s.validate().unwrap_err(),
5963            SupervisorError::RestartWindowZero
5964        );
5965    }
5966
5967    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5968    //
5969    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5970    // the integer-millisecond canonical-form gate — peer with
5971    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5972    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5973    // path is already gated at the shared codec layer (see
5974    // `restart_window_serde_rejects_fractional_seconds`); this arm
5975    // closes the programmatic-struct-literal path the codec gate can't
5976    // see.
5977
5978    #[test]
5979    fn validate_rejects_sub_millisecond_restart_window() {
5980        // The fail-before-pass-after pin: a programmatic
5981        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5982        // `validate` on every pre-gate codebase, then truncated to
5983        // `as_millis() == 1` on first serialize — the shared codec
5984        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5985        // 1_000_000 ns, the typed `restart_window` no longer matches
5986        // its rendered form.
5987        let s = SupervisorSpec {
5988            restart_window: Some(Duration::from_micros(1500)),
5989            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5990            ..SupervisorSpec::default()
5991        };
5992        match s.validate().unwrap_err() {
5993            SupervisorError::RestartWindowNotCanonical { window } => {
5994                assert_eq!(window, Duration::from_micros(1500));
5995            }
5996            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5997        }
5998    }
5999
6000    #[test]
6001    fn validate_rejects_one_nanosecond_restart_window() {
6002        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6003        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6004        // so the shared codec emits the literal `"0s"` — the next
6005        // serde round-trip would parse back to `Duration::ZERO`, which
6006        // the `RestartWindowZero` arm then rejects on re-validate. The
6007        // canonical-form gate at this layer surfaces a self-locating
6008        // diagnostic naming the offending Duration verbatim rather
6009        // than a downstream `RestartWindowZero` whose remediation
6010        // points at omitting the slot.
6011        let s = SupervisorSpec {
6012            restart_window: Some(Duration::from_nanos(1)),
6013            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6014            ..SupervisorSpec::default()
6015        };
6016        match s.validate().unwrap_err() {
6017            SupervisorError::RestartWindowNotCanonical { window } => {
6018                assert_eq!(window, Duration::from_nanos(1));
6019            }
6020            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6021        }
6022    }
6023
6024    #[test]
6025    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6026        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6027        // 1_000_001 ns is structurally past the integer-ms granularity
6028        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6029        // trip would truncate to `1ms` and the consumer would observe
6030        // a 1-ns drift on every emit. Same boundary the peer
6031        // `validate_rejects_nanosecond_past_canonical_boundary` test
6032        // in limits.rs pins for the `:limits :wall-clock` axis.
6033        let w = Duration::from_nanos(1_000_001);
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        );
6043    }
6044
6045    #[test]
6046    fn validate_accepts_integer_millisecond_restart_window_values() {
6047        // The positive-control sweep: every `Duration` the shared
6048        // codec can round-trip losslessly — the canonical
6049        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6050        // pair emits and accepts — passes `validate` without
6051        // surfacing the new canonical-form arm. Mirrors
6052        // `validate_accepts_integer_millisecond_wall_clock_values` on
6053        // the sibling `:limits :wall-clock` axis.
6054        for w in [
6055            Duration::from_millis(1),
6056            Duration::from_millis(500),
6057            Duration::from_millis(1500),
6058            Duration::from_secs(1),
6059            Duration::from_secs(30),
6060            Duration::from_secs(60),
6061            Duration::from_secs(120),
6062            Duration::from_secs(3600),
6063        ] {
6064            let s = SupervisorSpec {
6065                restart_window: Some(w),
6066                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6067                ..SupervisorSpec::default()
6068            };
6069            s.validate()
6070                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6071        }
6072    }
6073
6074    #[test]
6075    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6076        // Cross-arm ordering pin: `Duration::ZERO` has
6077        // `subsec_nanos() == 0` and would otherwise pass the
6078        // canonical-form arm — the zero-floor arm must fire first so
6079        // the more self-locating `RestartWindowZero` diagnostic (with
6080        // its omit-axis remediation directly named) leads. Same
6081        // posture every peer zero-then-shape gate uses
6082        // (`WallClockZero` → `WallClockNotCanonical`,
6083        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6084        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6085        let s = SupervisorSpec {
6086            restart_window: Some(Duration::ZERO),
6087            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6088            ..SupervisorSpec::default()
6089        };
6090        assert_eq!(
6091            s.validate().unwrap_err(),
6092            SupervisorError::RestartWindowZero
6093        );
6094    }
6095
6096    #[test]
6097    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6098        // Diagnostic-shape pin: the canonical-form arm names the
6099        // offending `Duration` verbatim so the author's grep lands on
6100        // the field's value, not a generic "duration not canonical"
6101        // message. Same shape every other typed-canonical-form arm
6102        // on this surface carries (`WallClockNotCanonical` carries
6103        // the offending `Duration` verbatim,
6104        // `PolicyTimeoutNotCanonical` carries the offending
6105        // `Duration` verbatim).
6106        let w = Duration::from_micros(500);
6107        let s = SupervisorSpec {
6108            restart_window: Some(w),
6109            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6110            ..SupervisorSpec::default()
6111        };
6112        let err = s.validate().unwrap_err();
6113        let msg = err.to_string();
6114        assert!(
6115            msg.contains("500"),
6116            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6117        );
6118        assert!(
6119            msg.contains("sub-millisecond"),
6120            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6121        );
6122    }
6123
6124    #[test]
6125    fn restart_window_validated_value_round_trips_through_codec() {
6126        // The structural property the canonical-ms gate enforces:
6127        // every `SupervisorSpec::restart_window` past
6128        // `SupervisorSpec::validate` round-trips losslessly through
6129        // the shared duration codec (serialize → string →
6130        // deserialize → equal value). Pin this end-to-end so a future
6131        // change to either side (the validate gate's accepted
6132        // granularity, the codec's parse/render unit set) that breaks
6133        // the alignment surfaces here. Peer of
6134        // `wall_clock_validated_value_round_trips_through_codec` on
6135        // the sibling `:limits :wall-clock` axis.
6136        for w in [
6137            Duration::from_millis(1),
6138            Duration::from_millis(1500),
6139            Duration::from_secs(30),
6140            Duration::from_secs(3600),
6141        ] {
6142            let s = SupervisorSpec {
6143                restart_window: Some(w),
6144                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6145                ..SupervisorSpec::default()
6146            };
6147            s.validate().unwrap();
6148            let json = serde_json::to_string(&s).unwrap();
6149            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6150            assert_eq!(back.restart_window, Some(w));
6151        }
6152    }
6153
6154    // ── value-shape: upper cap on :restart-window ─────────────────────────
6155    //
6156    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6157    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6158    // `:politicas :timeout` (2e8ee7e), and `:politicas
6159    // :circuit-breaker :window` (379a814). Brackets the typed
6160    // `:restart-window` axis structurally: every validated value lies
6161    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6162    // granularity, closing the
6163    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6164    // zero-floor-and-canonical-form-only checks left open.
6165
6166    #[test]
6167    fn validate_rejects_restart_window_above_cap() {
6168        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6169        // structurally one canonical-tick past the
6170        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6171        // integer-millisecond magnitude the canonical-form arm above
6172        // accepts cleanly, that the shared duration codec round-trips
6173        // losslessly as `"3601s"`, and that silently passed validate on
6174        // every pre-gate codebase because the typed slot's only checks
6175        // were the zero-floor and canonical-form arms. The runtime
6176        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6177        // Period reconciler, the future wasm-operator's per-supervisor
6178        // restart-intensity counter) reaches for a `Duration` so long
6179        // no realistic restart-recovery pattern resets the counter,
6180        // far from the source caixa.lisp.
6181        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6182        let s = SupervisorSpec {
6183            restart_window: Some(w),
6184            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6185            ..SupervisorSpec::default()
6186        };
6187        assert_eq!(
6188            s.validate().unwrap_err(),
6189            SupervisorError::RestartWindowExceedsCap { window: w }
6190        );
6191    }
6192
6193    #[test]
6194    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6195        // Boundary case: exactly 1ms past the cap (the granularity the
6196        // canonical-form gate enforces). Catches a future "strictly
6197        // less than" half-measure and pins the diagnostic to name the
6198        // offending `Duration` verbatim. Peer of
6199        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6200        // `rejects_policy_timeout_one_millisecond_above_cap` /
6201        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6202        // on the sibling typed-`Duration` axes' top edges.
6203        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6204        let s = SupervisorSpec {
6205            restart_window: Some(w),
6206            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6207            ..SupervisorSpec::default()
6208        };
6209        assert_eq!(
6210            s.validate().unwrap_err(),
6211            SupervisorError::RestartWindowExceedsCap { window: w }
6212        );
6213    }
6214
6215    #[test]
6216    fn validate_rejects_restart_window_far_above_cap() {
6217        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6218        // `(:restart-window "7d")`, or any "I want a lifetime counter
6219        // but wrote a `<integer>h` magnitude anyway" typo — values the
6220        // canonical-form arm accepts as integer-millisecond magnitudes,
6221        // the codec round-trips losslessly through serde, but the
6222        // operator's `MaxIntensity / Period` reconciler cannot honor
6223        // as a meaningful rolling window. Until this gate landed
6224        // validate accepted them. Pin the common above-cap values (24h,
6225        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6226        // surfaces here.
6227        for w in [
6228            Duration::from_secs(86_400),    // 24h
6229            Duration::from_secs(604_800),   // 7d
6230            Duration::from_secs(1_000_000), // ~11.5 days
6231        ] {
6232            let s = SupervisorSpec {
6233                restart_window: Some(w),
6234                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6235                ..SupervisorSpec::default()
6236            };
6237            assert_eq!(
6238                s.validate().unwrap_err(),
6239                SupervisorError::RestartWindowExceedsCap { window: w }
6240            );
6241        }
6242    }
6243
6244    #[test]
6245    fn validate_accepts_restart_window_at_cap() {
6246        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6247        // (1h) — must validate. The cap is inclusive on the top edge,
6248        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6249        // [`crate::POLICY_TIMEOUT_MAX`] /
6250        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6251        // capped axes. Pin the boundary explicitly so a future
6252        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6253        // instead of `>`) surfaces here as a test failure rather than a
6254        // silent contract narrowing.
6255        let s = SupervisorSpec {
6256            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6257            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6258            ..SupervisorSpec::default()
6259        };
6260        s.validate()
6261            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6262    }
6263
6264    #[test]
6265    fn validate_accepts_restart_window_typical_values() {
6266        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6267        // per-supervisor production-playbook band positive-control
6268        // sweep — every value Learn You Some Erlang's `{intensity, 5,
6269        // 60}` worker-supervisor `Period = 60s` default, Elixir's
6270        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6271        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6272        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6273        // default recommend (5s..=300s) must pass, plus a sweep
6274        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6275        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6276        // on the sibling `:limits :wall-clock` axis.
6277        for w in [
6278            Duration::from_millis(1),
6279            Duration::from_millis(500),
6280            Duration::from_secs(1),
6281            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
6282            Duration::from_secs(10), // Riak Core lower
6283            Duration::from_secs(30),
6284            Duration::from_secs(60),  // Learn You Some Erlang default
6285            Duration::from_secs(120), // OTP supervisor MaxT typical
6286            Duration::from_secs(300), // Riak Core upper
6287            Duration::from_secs(900), // 15m
6288            Duration::from_secs(1800),
6289            Duration::from_secs(3600), // exactly 1h, the cap
6290        ] {
6291            let s = SupervisorSpec {
6292                restart_window: Some(w),
6293                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6294                ..SupervisorSpec::default()
6295            };
6296            s.validate()
6297                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6298        }
6299    }
6300
6301    #[test]
6302    fn restart_window_zero_takes_precedence_over_cap() {
6303        // The cross-arm ordering pin: `Duration::ZERO` is structurally
6304        // outside both `>= 1ms` (zero-floor) and `<=
6305        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6306        // diagnostic is the more self-locating one (it directly names
6307        // the omit-axis remediation), so the validate gate must fire
6308        // on zero first. Same shape every other zero-then-cap ordering
6309        // on this surface uses (`WallClockZero` then
6310        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6311        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6312        // `PolicyBreakerWindowExceedsCap`).
6313        let s = SupervisorSpec {
6314            restart_window: Some(Duration::ZERO),
6315            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6316            ..SupervisorSpec::default()
6317        };
6318        assert_eq!(
6319            s.validate().unwrap_err(),
6320            SupervisorError::RestartWindowZero,
6321            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6322        );
6323    }
6324
6325    #[test]
6326    fn restart_window_canonical_takes_precedence_over_cap() {
6327        // The cross-arm ordering pin: a `Duration` that is *both*
6328        // sub-millisecond (non-canonical-form) and structurally above
6329        // the cap surfaces the canonical-form diagnostic first,
6330        // because the round-trip-shape break is the more fundamental
6331        // issue (the value can't even round-trip through the codec,
6332        // so the cap diagnostic naming `1ms..=1h` would be misleading
6333        // — there's no integer-ms form of the offending value). Pin
6334        // the order so a future refactor that reorders the arms
6335        // surfaces here as a test failure rather than a silent
6336        // diagnostic regression. Peer of
6337        // `wall_clock_canonical_takes_precedence_over_cap` /
6338        // `policy_timeout_canonical_takes_precedence_over_cap`.
6339        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6340        let s = SupervisorSpec {
6341            restart_window: Some(w),
6342            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6343            ..SupervisorSpec::default()
6344        };
6345        assert_eq!(
6346            s.validate().unwrap_err(),
6347            SupervisorError::RestartWindowNotCanonical { window: w },
6348            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6349        );
6350    }
6351
6352    #[test]
6353    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6354        // The cross-arm ordering pin between the `:max-restarts` cap
6355        // and the sibling `:restart-window` cap. A supervisor carrying
6356        // both an over-cap `max_restarts` AND an over-cap window must
6357        // surface the `MaxRestartsExceedsCap` diagnostic first — the
6358        // cap arm is wired immediately after the zero-restart arm and
6359        // strictly before every window-axis arm (zero / canonical /
6360        // cap), so the offending value the diagnostic names matches
6361        // the order the author would discover the gates by reading
6362        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6363        // order so a future refactor that reorders the arms surfaces
6364        // here as a test failure rather than a silent diagnostic
6365        // regression. Peer of
6366        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6367        // on the sibling zero / canonical window arms.
6368        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6369        let s = SupervisorSpec {
6370            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6371            restart_window: Some(w),
6372            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6373            ..SupervisorSpec::default()
6374        };
6375        assert_eq!(
6376            s.validate().unwrap_err(),
6377            SupervisorError::MaxRestartsExceedsCap {
6378                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6379            },
6380            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6381        );
6382    }
6383
6384    #[test]
6385    fn restart_window_cap_diagnostic_carries_offending_value() {
6386        // The diagnostic-shape pin: the offending `Duration` is
6387        // carried verbatim into the
6388        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6389        // surfaced error message names the value the author wrote,
6390        // not just the cap. Same self-locating diagnostic shape every
6391        // other typed-cap arm on this surface carries
6392        // (`WallClockExceedsCap` carries the offending `Duration`
6393        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6394        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6395        // the offending `Duration` verbatim).
6396        let w = Duration::from_secs(7200); // 2h
6397        let s = SupervisorSpec {
6398            restart_window: Some(w),
6399            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6400            ..SupervisorSpec::default()
6401        };
6402        let err = s.validate().unwrap_err();
6403        assert!(
6404            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6405            "got {err:?}"
6406        );
6407        let msg = err.to_string();
6408        assert!(
6409            msg.contains("7200"),
6410            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6411        );
6412    }
6413
6414    #[test]
6415    fn supervisor_restart_window_cap_pins_canonical_value() {
6416        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6417        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6418        // shared duration codec emits as a clean canonical string
6419        // (`"<n>h"`). Pinning the literal value here surfaces a future
6420        // drift (a relaxation to 24h, a tightening to 5m) as a
6421        // deliberate test edit, not a silent contract narrowing.
6422        //
6423        // The four typed-`Duration` caps on the validation surface
6424        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6425        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6426        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6427        // single uniform top edge at the codec's largest emitted unit
6428        // — a structural-property invariant the equality assertions
6429        // here enshrine, so a future drift on any of the four
6430        // surfaces as a deliberate test edit. Same shape every other
6431        // typed-cap value pin uses
6432        // (`wall_clock_cap_pins_canonical_value`,
6433        // `policy_timeout_cap_pins_canonical_value`,
6434        // `circuit_breaker_window_cap_pins_canonical_value`).
6435        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6436        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6437        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6438        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6439        assert_eq!(
6440            SUPERVISOR_RESTART_WINDOW_MAX,
6441            crate::POLICY_BREAKER_WINDOW_MAX
6442        );
6443    }
6444
6445    #[test]
6446    fn restart_window_cap_value_round_trips_through_codec() {
6447        // The codec round-trip property the cap arm preserves: the
6448        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6449        // through the shared duration codec — every value at the cap
6450        // serializes to the canonical `"1h"` form and parses back
6451        // identically. Pin the round-trip so a future change to the
6452        // codec's unit set or to the cap's magnitude that breaks the
6453        // round-trip property surfaces here. Peer of
6454        // `wall_clock_cap_value_round_trips_through_codec` on the
6455        // sibling `:limits :wall-clock` axis.
6456        let s = SupervisorSpec {
6457            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6458            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6459            ..SupervisorSpec::default()
6460        };
6461        s.validate().unwrap();
6462        let json = serde_json::to_string(&s).unwrap();
6463        assert!(
6464            json.contains("\"1h\""),
6465            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6466        );
6467        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6468        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6469    }
6470
6471    #[test]
6472    fn validate_rejects_duplicate_child_caixa() {
6473        // Two children with the same :caixa render to two ComputeUnits
6474        // with the same name in the cluster's HelmRelease values —
6475        // one silently overwrites the other. Erlang/OTP's child_spec.id
6476        // is required-unique per supervisor; same set-not-multiset
6477        // discipline applied here as for :membros / :placement
6478        // :clusters / :entrada :paths.
6479        let s = SupervisorSpec {
6480            children: vec![
6481                child("worker", "^0.1", RestartPolicy::Permanent),
6482                child("cache", "^0.1", RestartPolicy::Transient),
6483                child("worker", "^0.2", RestartPolicy::Permanent),
6484            ],
6485            ..SupervisorSpec::default()
6486        };
6487        let err = s.validate().unwrap_err();
6488        assert!(
6489            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6490            "got {err:?}"
6491        );
6492    }
6493
6494    #[test]
6495    fn validate_duplicate_child_diagnostic_names_first_collision() {
6496        // Iteration walks the :children list in declaration order —
6497        // the diagnostic names the first repeat, deterministically,
6498        // even when multiple names duplicate.
6499        let s = SupervisorSpec {
6500            children: vec![
6501                child("a", "^0.1", RestartPolicy::Permanent),
6502                child("b", "^0.1", RestartPolicy::Permanent),
6503                child("a", "^0.1", RestartPolicy::Permanent),
6504                child("b", "^0.1", RestartPolicy::Permanent),
6505            ],
6506            ..SupervisorSpec::default()
6507        };
6508        let err = s.validate().unwrap_err();
6509        assert!(
6510            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6511            "got {err:?}"
6512        );
6513    }
6514
6515    // ── self-supervision cross-slot gate ──────────────────────────
6516
6517    #[test]
6518    fn validate_no_self_supervision_rejects_self_referential_child() {
6519        // A supervisor whose `:children` lists its own `:nome` is a
6520        // one-node reconciliation cycle — rejected, naming the parent.
6521        let children = vec![
6522            child("worker", "^0.1", RestartPolicy::Permanent),
6523            child("orquestra", "^0.1", RestartPolicy::Permanent),
6524        ];
6525        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6526        assert!(
6527            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6528            "got {err:?}"
6529        );
6530    }
6531
6532    #[test]
6533    fn validate_no_self_supervision_accepts_distinct_children() {
6534        // Positive control: distinct child names (including a child that
6535        // is itself a supervisor — nested trees are valid OTP) pass.
6536        let children = vec![
6537            child("worker", "^0.1", RestartPolicy::Permanent),
6538            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6539        ];
6540        validate_no_self_supervision(&children, "orquestra").unwrap();
6541    }
6542
6543    #[test]
6544    fn validate_no_self_supervision_empty_children_is_ok() {
6545        // SimpleOneForOne / no-static-children supervisors have nothing
6546        // to self-reference — the gate is vacuously satisfied.
6547        validate_no_self_supervision(&[], "orquestra").unwrap();
6548    }
6549
6550    #[test]
6551    fn validate_simple_one_for_one_skips_uniqueness_check() {
6552        // SimpleOneForOne supervisors carry no static children — the
6553        // duplicate-child loop never runs. A zero-window declaration
6554        // on a SimpleOneForOne supervisor still trips the window check
6555        // (window applies to dynamic children too).
6556        let s = SupervisorSpec {
6557            estrategia: RestartStrategy::SimpleOneForOne,
6558            restart_window: None,
6559            children: vec![],
6560            ..SupervisorSpec::default()
6561        };
6562        s.validate().unwrap();
6563        let s_zero = SupervisorSpec {
6564            estrategia: RestartStrategy::SimpleOneForOne,
6565            restart_window: Some(Duration::ZERO),
6566            children: vec![],
6567            ..SupervisorSpec::default()
6568        };
6569        assert_eq!(
6570            s_zero.validate().unwrap_err(),
6571            SupervisorError::RestartWindowZero
6572        );
6573    }
6574
6575    #[test]
6576    fn validate_zero_window_runs_after_max_restarts_check() {
6577        // Pin the order: max_restarts == 0 fires before
6578        // restart_window == 0s, so an author with both wrong sees the
6579        // counter-axis diagnostic first (matches the order in the
6580        // struct and in the doc comment).
6581        let s = SupervisorSpec {
6582            max_restarts: 0,
6583            restart_window: Some(Duration::ZERO),
6584            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6585            ..SupervisorSpec::default()
6586        };
6587        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6588    }
6589
6590    #[test]
6591    fn round_trip_all_strategies() {
6592        for &strat in RestartStrategy::ALL {
6593            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6594            // shape partition through the [`gen_platform::IsVariant`]
6595            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6596            // predicate rather than the raw
6597            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6598            // open-coded pattern-match — same closed-set-typed-enum
6599            // arm-discriminator dispatch discipline the sibling
6600            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6601            // (915a934) extended onto its two paired positive / negated
6602            // `matches!` filter sites, and the sibling
6603            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6604            // predicate convergence (766ec63) extended onto the M3 mesh-
6605            // slot per-`:placement` distribution-strategy `matches!`
6606            // discriminator axis. See the sibling
6607            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6608            // fixture and the peer `manifest::tests::
6609            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6610            // fixture — all three sites (the last unlifted
6611            // `matches!`-based arm-discriminator axis on the OTP-shape
6612            // supervisor sibling-restart-strategy closed-set typed enum,
6613            // acknowledged in 915a934's Prior-commits footnote as the
6614            // outstanding follow-up) now consult one typed dispatch on
6615            // the substrate primitive.
6616            let s = SupervisorSpec {
6617                estrategia: strat,
6618                children: if strat.is_simple_one_for_one() {
6619                    vec![]
6620                } else {
6621                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6622                },
6623                ..SupervisorSpec::default()
6624            };
6625            let json = serde_json::to_string(&s).unwrap();
6626            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6627            assert_eq!(s, back);
6628        }
6629    }
6630
6631    #[test]
6632    fn round_trip_all_restart_policies() {
6633        for policy in [
6634            RestartPolicy::Permanent,
6635            RestartPolicy::Temporary,
6636            RestartPolicy::Transient,
6637        ] {
6638            let c = child("w", "^0.1", policy);
6639            let json = serde_json::to_string(&c).unwrap();
6640            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6641            assert_eq!(c, back);
6642        }
6643    }
6644
6645    #[test]
6646    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6647        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6648        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6649        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6650        // is the only variant that satisfies `.is_simple_one_for_one()`;
6651        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6652        // / `RestForOne`) returns `false`. This pin makes the partition
6653        // invariant load-bearing at caixa-core test time so a future
6654        // derive regression (a hole that returns `false` for
6655        // `SimpleOneForOne` too, or a byte-collision that flips a second
6656        // variant to `true`) trips here rather than laundering the arm
6657        // at the three test-fixture builder sites (a hole flips the
6658        // `SimpleOneForOne` fixture to carry a non-empty children list
6659        // and the subsequent `SupervisorSpec::validate` would refuse the
6660        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6661        // a collision flips a peer strategy's fixture to carry an empty
6662        // children list and the subsequent `validate` would refuse with
6663        // [`SupervisorError::NoChildren`] — either way, the pin fires
6664        // here, at the derive site, rather than at the fixture-refusal
6665        // site far away). Peer of the sibling
6666        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6667        // (915a934) pin on the M2 OTP-appup axis and the sibling
6668        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6669        // pin on the M0 `:kind` axis.
6670        let cases: &[(RestartStrategy, bool)] = &[
6671            (RestartStrategy::OneForOne, false),
6672            (RestartStrategy::OneForAll, false),
6673            (RestartStrategy::RestForOne, false),
6674            (RestartStrategy::SimpleOneForOne, true),
6675        ];
6676        for (variant, expected) in cases {
6677            assert_eq!(
6678                variant.is_simple_one_for_one(),
6679                *expected,
6680                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6681                 return {expected} (partition invariant on the \
6682                 IsVariant-derived arm-discriminator predicate — every \
6683                 test-fixture site that partitions the `:children` slot \
6684                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6685                 off this typed dispatch, so a derive regression must \
6686                 surface here rather than at the fixture-refusal site)"
6687            );
6688        }
6689    }
6690
6691    #[test]
6692    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6693        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6694        // fixture-shape partition against the pre-lift
6695        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6696        // pattern-match every test-fixture builder site previously
6697        // coupled to inline. Asserts the two projections agree byte-for-
6698        // byte on every arm of the enum, so a future derive regression
6699        // that flipped either predicate's arm-set would surface here at
6700        // caixa-core test time rather than at the three fixture-builder
6701        // sites (`supervisor::tests::round_trip_all_strategies`,
6702        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6703        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6704        // far from the derive site. Same peer-shape byte-identity pin
6705        // every sibling `IsVariant`-derive-routed convergence carries on
6706        // the substrate's closed-set typed-enum surface (peer of
6707        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6708        // on the M2 OTP-appup axis).
6709        for &strat in RestartStrategy::ALL {
6710            let via_predicate = strat.is_simple_one_for_one();
6711            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6712            assert_eq!(
6713                via_predicate, via_matches,
6714                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6715                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6716                 the pre-lift open-coded pattern and the \
6717                 IsVariant-derived predicate are the same axis, \
6718                 one typed dispatch"
6719            );
6720        }
6721    }
6722
6723    #[test]
6724    fn duration_codec_round_trip_canonical_units() {
6725        // Note the canonical-form rule: durations serialize to the
6726        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6727        // "60s" — but the round-trip preserves the underlying Duration.
6728        let cases = [
6729            ("30s", Duration::from_secs(30)),
6730            ("5m", Duration::from_secs(300)),
6731            ("1h", Duration::from_secs(3600)),
6732            ("500ms", Duration::from_millis(500)),
6733        ];
6734        for (lit, dur) in cases {
6735            let s = SupervisorSpec {
6736                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6737                restart_window: Some(dur),
6738                ..SupervisorSpec::default()
6739            };
6740            let json = serde_json::to_string(&s).unwrap();
6741            assert!(
6742                json.contains(&format!("\"{lit}\"")),
6743                "expected \"{lit}\" in {json}"
6744            );
6745            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6746            assert_eq!(back.restart_window, Some(dur));
6747        }
6748    }
6749
6750    #[test]
6751    fn duration_canonicalizes_to_largest_unit() {
6752        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6753        // typed Duration still equals 60s on the way back.
6754        let s = SupervisorSpec {
6755            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6756            restart_window: Some(Duration::from_secs(60)),
6757            ..SupervisorSpec::default()
6758        };
6759        let json = serde_json::to_string(&s).unwrap();
6760        assert!(json.contains("\"1m\""), "{json}");
6761        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6762        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6763    }
6764
6765    #[test]
6766    fn three_child_one_for_one_validates() {
6767        let s = SupervisorSpec {
6768            estrategia: RestartStrategy::OneForOne,
6769            max_restarts: 5,
6770            restart_window: Some(Duration::from_secs(60)),
6771            children: vec![
6772                child("worker", "^0.1", RestartPolicy::Permanent),
6773                child("cache", "^0.1", RestartPolicy::Transient),
6774                child("scratch", "^0.1", RestartPolicy::Temporary),
6775            ],
6776        };
6777        s.validate().unwrap();
6778    }
6779
6780    #[test]
6781    fn json_uses_pascal_case_for_strategy_and_policy() {
6782        // Variant names are PascalCase by default in serde, matching
6783        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6784        let c = child("w", "^0.1", RestartPolicy::Permanent);
6785        let json = serde_json::to_string(&c).unwrap();
6786        assert!(json.contains("\"Permanent\""));
6787        assert!(!json.contains("\"permanent\""));
6788
6789        let s = SupervisorSpec {
6790            estrategia: RestartStrategy::OneForOne,
6791            children: vec![c],
6792            ..SupervisorSpec::default()
6793        };
6794        let json = serde_json::to_string(&s).unwrap();
6795        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6796    }
6797
6798    // ── shared duration codec: integer-magnitude canonical-form gate ──
6799    //
6800    // The gate lifts the discipline `crate::limits::parse_duration`
6801    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6802    // the shared codec backing the remaining three typed-duration
6803    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6804    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6805    // emits is a non-negative integer with no decimal point and no
6806    // leading sign, so the codec's accepted set must match for
6807    // serialize/deserialize to round-trip without canonical-form
6808    // drift.
6809
6810    #[test]
6811    fn parse_accepts_integer_canonical_units() {
6812        // Pin the happy-path: every canonical author shape `render`
6813        // ever emits parses to the same `Duration` value, so the
6814        // codec's accepted set is at least a superset of its emitted
6815        // set on the canonical-unit axis.
6816        for (lit, dur) in [
6817            ("30s", Duration::from_secs(30)),
6818            ("500ms", Duration::from_millis(500)),
6819            ("2m", Duration::from_secs(120)),
6820            ("1h", Duration::from_secs(3600)),
6821            ("0s", Duration::ZERO),
6822        ] {
6823            assert_eq!(
6824                duration_codec::parse(lit).unwrap(),
6825                dur,
6826                "parse({lit:?}) should be {dur:?}"
6827            );
6828        }
6829    }
6830
6831    #[test]
6832    fn parse_accepts_bare_integer_as_seconds() {
6833        // The `"s" | ""` arm: a bare integer with no unit is read as
6834        // seconds. Pin this so the unit-empty form keeps parsing (it
6835        // renders to `"<n>s"` on serialize — that's a unit-choice
6836        // drift the integer-magnitude gate does NOT close, matching
6837        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6838        // the peer `:limits :memory` codec).
6839        assert_eq!(
6840            duration_codec::parse("30").unwrap(),
6841            Duration::from_secs(30)
6842        );
6843    }
6844
6845    #[test]
6846    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6847        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6848        // on first serialize — DRIFT. The integer-magnitude gate names
6849        // the offending `"1.5"` verbatim and points at the canonical
6850        // remediation `"1500ms"`.
6851        let err = duration_codec::parse("1.5s").unwrap_err();
6852        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6853        assert!(
6854            err.contains("not a non-negative integer"),
6855            "missing canonical-form reason in {err:?}"
6856        );
6857        assert!(
6858            err.contains("\"1500ms\""),
6859            "missing canonical-form remediation in {err:?}"
6860        );
6861    }
6862
6863    #[test]
6864    fn parse_rejects_decimal_shaped_integer_seconds() {
6865        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6866        // `1s` exactly, so the round-trip looks correct — but the
6867        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6868        // decimal-shape-with-integer-value form so author intent is
6869        // never silently rewritten.
6870        let err = duration_codec::parse("1.0s").unwrap_err();
6871        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6872        assert!(
6873            err.contains("not a non-negative integer"),
6874            "missing canonical-form reason in {err:?}"
6875        );
6876    }
6877
6878    #[test]
6879    fn parse_rejects_half_unit_minute() {
6880        // `"0.5m"` is the unit-fraction footgun — author writes a
6881        // human-readable half-minute, serde silently rewrites to
6882        // `"30s"` on next emit. The gate names the offending
6883        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6884        // form.
6885        let err = duration_codec::parse("0.5m").unwrap_err();
6886        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6887        assert!(
6888            err.contains("\"30s\""),
6889            "missing canonical-form remediation in {err:?}"
6890        );
6891    }
6892
6893    #[test]
6894    fn parse_rejects_leading_plus_sign() {
6895        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6896        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6897        // cleanly to 30s and round-tripped to `"30s"` on next emit
6898        // (DRIFT). The digit-only gate closes the leading-sign class
6899        // first; the diagnostic names `"+30"` verbatim.
6900        let err = duration_codec::parse("+30s").unwrap_err();
6901        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6902        assert!(
6903            err.contains("not a non-negative integer"),
6904            "missing canonical-form reason in {err:?}"
6905        );
6906    }
6907
6908    #[test]
6909    fn parse_rejects_leading_minus_sign() {
6910        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6911        // rejected with `"negative duration in \"-30s\""`. Under the
6912        // integer-magnitude gate the diagnostic is unified — `-30` is
6913        // non-digit-only, f64-numeric, and surfaces with the canonical-
6914        // form reason (no leading `+` / `-` sign) naming the offending
6915        // `"-30"` verbatim. Same diagnostic shape as every other
6916        // rejected non-integer magnitude.
6917        let err = duration_codec::parse("-30s").unwrap_err();
6918        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6919        assert!(
6920            err.contains("not a non-negative integer"),
6921            "missing canonical-form reason in {err:?}"
6922        );
6923    }
6924
6925    #[test]
6926    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6927        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6928        // through to the narrower "bad duration magnitude" arm — the
6929        // canonical-form diagnostic is reserved for the parser-shape
6930        // footgun case, not the "not a number at all" case. Same
6931        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6932        // the peer `:limits :memory` codec.
6933        let err = duration_codec::parse("--1s").unwrap_err();
6934        assert!(
6935            err.contains("bad duration magnitude"),
6936            "expected bad-magnitude wording in {err:?}"
6937        );
6938    }
6939
6940    #[test]
6941    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6942        // The accepted set is now closed under `u64`-exact integer
6943        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6944        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6945        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6946        // possible. Pin the integer-exact arms across the four unit
6947        // suffixes so a future refactor that reaches back for f64
6948        // (`from_secs_f64`, `mul_f64`) surfaces here.
6949        assert_eq!(
6950            duration_codec::parse("3600s").unwrap(),
6951            Duration::from_secs(3600)
6952        );
6953        assert_eq!(
6954            duration_codec::parse("60m").unwrap(),
6955            Duration::from_secs(3600)
6956        );
6957        assert_eq!(
6958            duration_codec::parse("1h").unwrap(),
6959            Duration::from_secs(3600)
6960        );
6961        assert_eq!(
6962            duration_codec::parse("999ms").unwrap(),
6963            Duration::from_millis(999)
6964        );
6965    }
6966
6967    #[test]
6968    fn restart_window_serde_rejects_fractional_seconds() {
6969        // The shared codec backs `SupervisorSpec::restart_window`
6970        // (`with = "duration_codec"`) — so the gate applies on serde
6971        // deserialize for the typed Supervisor slot. A
6972        // `{"restartWindow":"1.5s"}` payload that previously round-
6973        // tripped to a different canonical string on next serialize
6974        // is now refused at deserialize with the integer-magnitude
6975        // diagnostic.
6976        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6977            "restartWindow":"1.5s",
6978            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6979        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6980        let msg = err.to_string();
6981        assert!(
6982            msg.contains("not a non-negative integer"),
6983            "expected integer-magnitude diagnostic in {msg:?}"
6984        );
6985        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6986    }
6987
6988    #[test]
6989    fn restart_window_serde_rejects_leading_plus() {
6990        // The `u64::from_str` leading-`+` permissiveness gap that
6991        // motivated the digit-only gate (the `f64`-side accepted
6992        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6993        // is now closed on the shared codec — surfaces as a structured
6994        // diagnostic at the serde layer for every typed-duration slot.
6995        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6996            "restartWindow":"+30s",
6997            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6998        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6999        let msg = err.to_string();
7000        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7001        assert!(
7002            msg.contains("not a non-negative integer"),
7003            "missing canonical-form reason in {msg:?}"
7004        );
7005    }
7006
7007    #[test]
7008    fn parse_rejects_leading_zero_magnitude() {
7009        // `"030s"` is digit-only, so the existing non-digit-only / sign
7010        // / fractional arm doesn't catch it — `u64::from_str("030")`
7011        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7012        // `Duration::from_secs(30)` and round-tripped through `render`
7013        // to `"30s"` — a *different* canonical string on the next emit,
7014        // breaking the THEORY.md Part V render-determinism contract
7015        // exactly the way `"+30s"` did before the leading-`+` arm
7016        // landed. Peer with the `rate_limit_codec` leading-zero arm
7017        // (4f46830) on the same canonical-form-drift axis.
7018        let err = duration_codec::parse("030s").unwrap_err();
7019        assert!(
7020            err.contains("non-canonical leading zero"),
7021            "expected leading-zero diagnostic in {err:?}"
7022        );
7023        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7024        assert!(
7025            err.contains("\"30s\""),
7026            "missing canonical-form remediation in {err:?}"
7027        );
7028        assert!(
7029            err.contains("THEORY.md"),
7030            "missing render-determinism citation in {err:?}"
7031        );
7032    }
7033
7034    #[test]
7035    fn parse_rejects_multi_digit_zero_magnitude() {
7036        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7037        // digit-only, parse losslessly to `Duration::ZERO`, but render
7038        // back to `"0s"` (the single-byte canonical form) on the next
7039        // emit. The leading-zero arm refuses the drift class at the
7040        // codec layer; the semantic-zero gate downstream
7041        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7042        // the single-byte canonical form `"0s"` separately on the
7043        // typed-validate layer.
7044        let err = duration_codec::parse("00s").unwrap_err();
7045        assert!(
7046            err.contains("non-canonical leading zero"),
7047            "expected leading-zero diagnostic in {err:?}"
7048        );
7049        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7050    }
7051
7052    #[test]
7053    fn parse_rejects_leading_zero_per_hour_window() {
7054        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7055        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7056        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7057        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7058        // `h` / bare-integer-as-seconds) inherits the same gate.
7059        let err = duration_codec::parse("01h").unwrap_err();
7060        assert!(
7061            err.contains("non-canonical leading zero"),
7062            "expected leading-zero diagnostic in {err:?}"
7063        );
7064        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7065    }
7066
7067    #[test]
7068    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7069        // The `parse_accepts_bare_integer_as_seconds` happy-path
7070        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7071        // multi-byte starts-with-`0`, parses losslessly to
7072        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7073        // bare-integer surface accepts permissive unit-empty
7074        // shorthand but still must reject leading-zero padding.
7075        let err = duration_codec::parse("030").unwrap_err();
7076        assert!(
7077            err.contains("non-canonical leading zero"),
7078            "expected leading-zero diagnostic in {err:?}"
7079        );
7080        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7081    }
7082
7083    #[test]
7084    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7085        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7086        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7087        // each round-trips losslessly through `render`
7088        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7089        // accepts them. The downstream semantic-zero gates
7090        // (`SupervisorError::ZeroRestartWindow`,
7091        // `AplicacaoError::PolicyTimeoutZero`,
7092        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7093        // zero-magnitude authoring at the typed-validate layer above,
7094        // peer with the `rate_limit_codec` codec-layer / typed-
7095        // validate-layer partition for `"0/s"`.
7096        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7097        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7098        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7099    }
7100
7101    #[test]
7102    fn parse_accepts_canonical_magnitude_with_leading_one() {
7103        // The complementary boundary: a future tightening cannot
7104        // drift into rejecting valid canonical magnitudes that
7105        // happen to start with `1` (or any digit `[1-9]`). Pin
7106        // every canonical-unit suffix so the leading-zero arm
7107        // remains strictly narrower than the digit-only arm.
7108        assert_eq!(
7109            duration_codec::parse("100ms").unwrap(),
7110            Duration::from_millis(100)
7111        );
7112        assert_eq!(
7113            duration_codec::parse("100s").unwrap(),
7114            Duration::from_secs(100)
7115        );
7116        assert_eq!(
7117            duration_codec::parse("10m").unwrap(),
7118            Duration::from_secs(600)
7119        );
7120        assert_eq!(
7121            duration_codec::parse("10h").unwrap(),
7122            Duration::from_secs(36_000)
7123        );
7124    }
7125
7126    #[test]
7127    fn restart_window_serde_rejects_leading_zero() {
7128        // The shared codec backs `SupervisorSpec::restart_window`
7129        // (`with = "duration_codec"`) — so the leading-zero arm
7130        // applies on serde deserialize for the typed Supervisor slot.
7131        // A `{"restartWindow":"030s"}` payload that previously round-
7132        // tripped to a different canonical string on next serialize
7133        // is now refused at deserialize with the leading-zero
7134        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7135        // / `restart_window_serde_rejects_fractional_seconds` on the
7136        // same canonical-form-drift axis.
7137        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7138            "restartWindow":"030s",
7139            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7140        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7141        let msg = err.to_string();
7142        assert!(
7143            msg.contains("non-canonical leading zero"),
7144            "expected leading-zero diagnostic in {msg:?}"
7145        );
7146        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7147    }
7148
7149    #[test]
7150    fn parse_rejects_leading_whitespace() {
7151        // `" 30s"` — the canonical paste-from-aligned-doc /
7152        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7153        // gate the top-level `s.trim()` at parse entry silently ate
7154        // the leading space and parsed the value to
7155        // `Duration::from_secs(30)`, which then round-tripped through
7156        // `render` to `"30s"` (a *different* canonical string on the
7157        // next emit) — the exact canonical-form-drift class the
7158        // leading-`+` / leading-zero arms already close, extended
7159        // to the whitespace-byte class. Peer with the sibling
7160        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7161        // the M3 `:politicas` axis.
7162        let err = duration_codec::parse(" 30s").unwrap_err();
7163        assert!(
7164            err.contains("contains whitespace byte"),
7165            "expected whitespace diagnostic in {err:?}"
7166        );
7167        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7168        assert!(
7169            err.contains("THEORY.md"),
7170            "missing render-determinism contract citation in {err:?}"
7171        );
7172    }
7173
7174    #[test]
7175    fn parse_rejects_trailing_whitespace() {
7176        // `"30s "` — the canonical shell-history / trailing-space
7177        // paste footgun. Before this gate the top-level `s.trim()`
7178        // silently ate the trailing space and parsed to
7179        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7180        // next emit — same canonical-form drift as the leading-space
7181        // sibling, closed on the same whitespace-byte arm.
7182        let err = duration_codec::parse("30s ").unwrap_err();
7183        assert!(
7184            err.contains("contains whitespace byte"),
7185            "expected whitespace diagnostic in {err:?}"
7186        );
7187        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7188    }
7189
7190    #[test]
7191    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7192        // `"30 s"` — the canonical typographically-spaced author
7193        // shape (the same idiom every prose reference to a duration
7194        // renders as, mistakenly retained when the value is pasted
7195        // into a codec-shaped slot). Before this gate the per-part
7196        // `num_part.trim()` / `unit.trim()` calls silently ate the
7197        // whitespace between the magnitude and the unit and parsed
7198        // the value to `Duration::from_secs(30)`, round-tripping to
7199        // `"30s"` — the codec's *internal* whitespace-tolerance
7200        // vector, orthogonal to the leading / trailing surface but
7201        // the same canonical-form-drift class. Pins the arm as
7202        // strictly stronger than the pre-existing top-level
7203        // `s.trim()` behavior: it fires on whitespace anywhere in
7204        // the value, not just at the string boundary.
7205        let err = duration_codec::parse("30 s").unwrap_err();
7206        assert!(
7207            err.contains("contains whitespace byte"),
7208            "expected whitespace diagnostic in {err:?}"
7209        );
7210        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7211    }
7212
7213    #[test]
7214    fn parse_rejects_tab_byte() {
7215        // `"\t30s"` — the canonical paste-from-indented-doc /
7216        // paste-from-YAML-block-scalar footgun where a tab byte leads
7217        // the magnitude. Pins that the gate covers tab (`0x09`) as
7218        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7219        // members and both would be silently swallowed by `s.trim()`
7220        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7221        // space alone to the full ASCII-whitespace set (space `0x20`,
7222        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7223        // the tab arm as a representative of the non-space members.
7224        let err = duration_codec::parse("\t30s").unwrap_err();
7225        assert!(
7226            err.contains("contains whitespace byte"),
7227            "expected whitespace diagnostic in {err:?}"
7228        );
7229        assert!(
7230            err.contains("0x09"),
7231            "missing offending tab byte in {err:?}"
7232        );
7233    }
7234
7235    #[test]
7236    fn restart_window_serde_rejects_whitespace() {
7237        // The shared codec backs `SupervisorSpec::restart_window`
7238        // (`with = "duration_codec"`) — so the whitespace arm
7239        // applies on serde deserialize for the typed Supervisor slot.
7240        // A `{"restartWindow":" 30s"}` payload that previously round-
7241        // tripped to a different canonical string on next serialize
7242        // is now refused at deserialize with the whitespace-byte
7243        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7244        // / `restart_window_serde_rejects_leading_plus` /
7245        // `restart_window_serde_rejects_fractional_seconds` on the
7246        // same canonical-form-drift axis.
7247        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7248            "restartWindow":" 30s",
7249            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7250        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7251        let msg = err.to_string();
7252        assert!(
7253            msg.contains("contains whitespace byte"),
7254            "expected whitespace diagnostic in {msg:?}"
7255        );
7256        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7257    }
7258
7259    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7260    //
7261    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7262    // duration codec — closes the strictly-complementary class the
7263    // byte-scan cannot see, through the lifted
7264    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7265    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7266    // and `:politicas :circuit-breaker :window` simultaneously via
7267    // this shared codec.
7268
7269    #[test]
7270    fn duration_codec_parse_rejects_leading_nbsp() {
7271        // NBSP prefix — the strictly-complementary drift class the
7272        // ASCII byte-scan cannot see. `str::trim` strips it silently
7273        // and the value drifts to `"30s"` on next serialize.
7274        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7275        assert!(
7276            err.contains("non-ASCII Unicode whitespace character"),
7277            "expected non-ASCII whitespace diagnostic in {err:?}"
7278        );
7279        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7280    }
7281
7282    #[test]
7283    fn duration_codec_parse_rejects_trailing_line_separator() {
7284        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7285        // footgun.
7286        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7287        assert!(
7288            err.contains("non-ASCII Unicode whitespace character"),
7289            "expected non-ASCII whitespace diagnostic in {err:?}"
7290        );
7291        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7292    }
7293
7294    #[test]
7295    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7296        // Positive-control pin: every ASCII-only canonical form the
7297        // renderer emits stays accepted through the new arm.
7298        assert_eq!(
7299            duration_codec::parse("30s").unwrap(),
7300            Duration::from_secs(30)
7301        );
7302        assert_eq!(
7303            duration_codec::parse("500ms").unwrap(),
7304            Duration::from_millis(500)
7305        );
7306        assert_eq!(
7307            duration_codec::parse("1h").unwrap(),
7308            Duration::from_secs(3600)
7309        );
7310    }
7311
7312    #[test]
7313    fn restart_window_serde_rejects_non_ascii_whitespace() {
7314        // The shared codec backs `SupervisorSpec::restart_window` — so
7315        // the new non-ASCII Unicode whitespace arm applies on serde
7316        // deserialize for the typed Supervisor slot. A
7317        // `{"restartWindow":" 30s"}` payload that previously
7318        // survived the ASCII byte-scan (only ASCII whitespace was
7319        // refused) is now refused at deserialize with the
7320        // non-ASCII-whitespace-and-codepoint diagnostic.
7321        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7322            \"restartWindow\":\"\u{00A0}30s\",\
7323            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7324        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7325        let msg = err.to_string();
7326        assert!(
7327            msg.contains("non-ASCII Unicode whitespace character"),
7328            "expected non-ASCII whitespace diagnostic in {msg:?}"
7329        );
7330        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7331    }
7332
7333    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7334
7335    #[test]
7336    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7337        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7338        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7339        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7340        // name the exact camelCase JSON keys the
7341        // `#[serde(rename_all = "camelCase")]` attribute on
7342        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7343        // field carries `Some(_)` / non-empty) and pin that each canonical
7344        // byte-sequence appears verbatim in the JSON — a future accidental
7345        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7346        // name flip at the derive attribute (any of which would silently
7347        // break every downstream JSON consumer that reaches for one of the
7348        // four consts via `Value::get(...)`) surfaces here as a build-time
7349        // test failure at `supervisor.rs`, not as an apply-time
7350        // `.get(<stale-canonical-const>)` returning `None` far from the
7351        // derive-attr drift's commit. Peer with the sibling
7352        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7353        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7354        // M2 typed-slot family established, extended here to close the
7355        // top-level Supervisor axis.
7356        let spec = SupervisorSpec {
7357            estrategia: RestartStrategy::OneForOne,
7358            max_restarts: 5,
7359            restart_window: Some(Duration::from_secs(60)),
7360            children: vec![ChildSpec {
7361                caixa: "w".into(),
7362                versao: "^0.1".into(),
7363                restart: RestartPolicy::Permanent,
7364            }],
7365        };
7366        let json = serde_json::to_string(&spec).unwrap();
7367        for key in [
7368            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7369            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7370            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7371            crate::render::SUPERVISOR_KEY_CHILDREN,
7372        ] {
7373            let quoted = format!("\"{key}\"");
7374            assert!(
7375                json.contains(&quoted),
7376                "serialized SupervisorSpec must carry the lifted \
7377                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7378                 the JSON emission (got: {json})",
7379            );
7380        }
7381    }
7382
7383    #[test]
7384    fn supervisor_key_consts_are_pairwise_distinct() {
7385        // Cross-axis drift-detection pin: a future collapse of two
7386        // canonical top-level byte-strings onto the same value (e.g. an
7387        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7388        // also read `"estrategia"`) would silently reroute every
7389        // downstream probe on one axis onto the sibling axis's overlay
7390        // entry and pass every propagation-probe test that expected only
7391        // the stale axis's value. Peer of the sibling four-way distinct
7392        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7393        let all = [
7394            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7395            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7396            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7397            crate::render::SUPERVISOR_KEY_CHILDREN,
7398        ];
7399        for (i, a) in all.iter().enumerate() {
7400            for b in all.iter().skip(i + 1) {
7401                assert_ne!(
7402                    a, b,
7403                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7404                     canonical byte-sequences — got `{a}` == `{b}`",
7405                );
7406            }
7407        }
7408    }
7409
7410    #[test]
7411    fn supervisor_key_consts_are_lower_camel_case_shape() {
7412        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7413        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7414        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7415        // capital, no whitespace / dots) — the canonical shape the
7416        // `#[serde(rename_all = "camelCase")]` derive produces on
7417        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7418        // at the derive surfaces both here (this test fails on the
7419        // stale-constant shape) and at
7420        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7421        // (that test fails on the mismatch between const and derive).
7422        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7423        // (d8b8b4f) on the sibling M2 `:limits` axis.
7424        for key in [
7425            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7426            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7427            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7428            crate::render::SUPERVISOR_KEY_CHILDREN,
7429        ] {
7430            assert!(
7431                !key.is_empty(),
7432                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7433            );
7434            let first = key.chars().next().unwrap();
7435            assert!(
7436                first.is_ascii_lowercase(),
7437                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7438                 (got {key:?}, leads with {first:?})",
7439            );
7440            assert!(
7441                key.chars().all(|c| c.is_ascii_alphanumeric()),
7442                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7443                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7444            );
7445        }
7446    }
7447
7448    #[test]
7449    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7450        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7451        // (camelCase JSON keys, no leading colon) must never collide
7452        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7453        // consts (kebab-case author-facing labels with leading colon)
7454        // that sit next to them at `caixa_core::render`. Both families
7455        // cover the same four typed Supervisor slots on two distinct
7456        // axes (author-side kebab vs renderer-side camelCase);
7457        // collapsing either family onto the other's byte-shape would
7458        // silently reroute the render-side probe onto the author-facing
7459        // surface, or vice versa. Peer of the byte-distinctness
7460        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7461        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7462        let pairs = [
7463            (
7464                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7465                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7466            ),
7467            (
7468                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7469                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7470            ),
7471            (
7472                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7473                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7474            ),
7475            (
7476                crate::render::SUPERVISOR_KEY_CHILDREN,
7477                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7478            ),
7479        ];
7480        for (json_key, author_key) in pairs {
7481            assert_ne!(
7482                json_key, author_key,
7483                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7484                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7485                 got JSON `{json_key}` == author `{author_key}`",
7486            );
7487        }
7488    }
7489
7490    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7491
7492    #[test]
7493    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7494        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7495        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7496        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7497        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7498        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7499        // pin that each canonical byte-sequence appears verbatim in the
7500        // JSON — a future accidental `rename_all = "snake_case"` /
7501        // `"kebab-case"` / verbatim-field-name flip at the derive
7502        // attribute (any of which would silently break every downstream
7503        // JSON consumer that reaches for one of the three consts via
7504        // `Value::get(...)`) surfaces here as a build-time test failure at
7505        // `supervisor.rs`, not as an apply-time
7506        // `.get(<stale-canonical-const>)` returning `None` far from the
7507        // derive-attr drift's commit. Peer with the enclosing
7508        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7509        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7510        // discipline the SupervisorSpec top-level lift established,
7511        // extended here to the sibling per-`:children` entry `ChildSpec`
7512        // derive so the last M2 typed-struct sub-block
7513        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7514        // surface without a lifted serde-key peer joins the substrate's
7515        // "one canonical byte-string per typed serialized-key axis"
7516        // discipline.
7517        let c = ChildSpec {
7518            caixa: "worker".into(),
7519            versao: "^0.1".into(),
7520            restart: RestartPolicy::Permanent,
7521        };
7522        let json = serde_json::to_string(&c).unwrap();
7523        for key in [
7524            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7525            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7526            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7527        ] {
7528            let quoted = format!("\"{key}\"");
7529            assert!(
7530                json.contains(&quoted),
7531                "serialized ChildSpec must carry the lifted \
7532                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7533                 in the JSON emission (got: {json})",
7534            );
7535        }
7536    }
7537
7538    #[test]
7539    fn supervisor_child_key_consts_are_pairwise_distinct() {
7540        // Cross-axis drift-detection pin: a future collapse of two
7541        // canonical `ChildSpec` per-entry byte-strings onto the same
7542        // value (e.g. an accidental copy-paste flip of
7543        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7544        // silently reroute every downstream probe on one axis onto the
7545        // sibling axis's overlay entry and pass every propagation-probe
7546        // test that expected only the stale axis's value. Peer of the
7547        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7548        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7549        // pair (ce80ca0).
7550        let all = [
7551            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7552            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7553            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7554        ];
7555        for (i, a) in all.iter().enumerate() {
7556            for b in all.iter().skip(i + 1) {
7557                assert_ne!(
7558                    a, b,
7559                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7560                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7561                );
7562            }
7563        }
7564    }
7565
7566    #[test]
7567    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7568        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7569        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7570        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7571        // capital, no whitespace / dots) — the canonical shape the
7572        // `#[serde(rename_all = "camelCase")]` derive produces on
7573        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7574        // derive surfaces both here (this test fails on the
7575        // stale-constant shape) and at
7576        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7577        // (that test fails on the mismatch between const and derive).
7578        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7579        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7580        for key in [
7581            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7582            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7583            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7584        ] {
7585            assert!(
7586                !key.is_empty(),
7587                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7588            );
7589            let first = key.chars().next().unwrap();
7590            assert!(
7591                first.is_ascii_lowercase(),
7592                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7593                 byte (got {key:?}, leads with {first:?})",
7594            );
7595            assert!(
7596                key.chars().all(|c| c.is_ascii_alphanumeric()),
7597                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7598                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7599            );
7600        }
7601    }
7602
7603    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7604
7605    #[test]
7606    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7607        // The fail-before-pass-after pin: pre-lift there was no
7608        // single-source binding between the [`RestartStrategy`] variant
7609        // name the un-`rename`d `Serialize` derive emits under
7610        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7611        // every downstream cluster-side dispatcher (the future
7612        // wasm-operator's per-supervisor sibling-restart branch, the
7613        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7614        // admission-time enum-arm bind, the `caixa-operator`'s
7615        // hierarchical reconciliation scheduler's per-strategy fan-out)
7616        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7617        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7618        // override, or a variant rename in the source — would silently
7619        // rebrand the emitted scalar under one spelling while every
7620        // downstream dispatcher still probed the other, with the failure
7621        // surfacing at the operator's reconcile posture (subtrees coming
7622        // up under the `default()` `OneForOne` arm rather than the typed
7623        // slot's declared strategy — a bad child would then only take
7624        // itself down instead of the sibling set the author intended, so
7625        // shared-state children fall out of sync) far from the source
7626        // rebrand commit and with no field naming the drift. Pinning the
7627        // two paths (the `Serialize` derive's serialized string AND the
7628        // [`RestartStrategy::as_str`] helper) to the same four lifted
7629        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7630        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7631        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7632        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7633        // byte-strings makes any future drift on either endpoint fail
7634        // here at caixa-core build time. Peer of the M3
7635        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7636        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7637        // three-path-convergence discipline, extended to close the
7638        // OTP-shaped per-supervisor sibling-restart axis.
7639        for (variant, expected) in [
7640            (
7641                RestartStrategy::OneForOne,
7642                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7643            ),
7644            (
7645                RestartStrategy::OneForAll,
7646                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7647            ),
7648            (
7649                RestartStrategy::RestForOne,
7650                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7651            ),
7652            (
7653                RestartStrategy::SimpleOneForOne,
7654                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7655            ),
7656        ] {
7657            let json = serde_json::to_string(&variant).unwrap();
7658            assert_eq!(
7659                json,
7660                format!("\"{expected}\""),
7661                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7662            );
7663            assert_eq!(
7664                variant.as_str(),
7665                expected,
7666                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7667                 SUPERVISOR_ESTRATEGIA_* constant"
7668            );
7669        }
7670    }
7671
7672    #[test]
7673    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7674        // Cross-arm drift-detection pin: a future collapse of two
7675        // canonical variant byte-strings onto the same value (e.g. an
7676        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7677        // to also read `"OneForOne"`) would silently reroute every
7678        // downstream operator's per-strategy dispatch onto the sibling
7679        // arm's reconcile branch and pass every propagation-probe test
7680        // that expected only the stale arm's value — the mis-strategied
7681        // subtree would come up with the wrong sibling-restart posture
7682        // on every subsequent failure. Peer of the sibling four-way
7683        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7684        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7685        let all = [
7686            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7687            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7688            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7689            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7690        ];
7691        for (i, a) in all.iter().enumerate() {
7692            for (j, b) in all.iter().enumerate() {
7693                if i != j {
7694                    assert_ne!(
7695                        a, b,
7696                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7697                         — got duplicate {a:?} at indices {i} and {j}",
7698                    );
7699                }
7700            }
7701        }
7702    }
7703
7704    #[test]
7705    fn restart_strategy_display_routes_through_as_str_helper() {
7706        // The fail-before-pass-after pin on the first half of the
7707        // three-path convergence: pre-convergence the sibling
7708        // OTP-shape typed enum [`RestartStrategy`] carried a
7709        // [`std::fmt::Display`] surface via its
7710        // `#[discriminant(also_display)]` gen-platform derive route,
7711        // which arrived kebab-case as `"one-for-one"` /
7712        // `"one-for-all"` / `"rest-for-one"` /
7713        // `"simple-one-for-one"` while the wire format ran as
7714        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7715        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7716        // Every consumer reaching for a strategy byte-string past the
7717        // wire format had to pick between three paths
7718        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7719        // serialized string, or `format!("{v}")` on the
7720        // discriminant-Display route), any two of which a future
7721        // variant rename or `#[serde(rename_all = "kebab-case")]`
7722        // attribute would silently desynchronize. Wiring
7723        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7724        // closes the third path: every `format!("{v}")` call reaches
7725        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7726        // const the wire format and the [`RestartStrategy::as_str`]
7727        // helper already route through, so a future variant rename
7728        // lands at exactly one place. Pin the routing here so a future
7729        // `impl std::fmt::Display for RestartStrategy`
7730        // reimplementation that hand-rolls the arms instead of
7731        // delegating to [`RestartStrategy::as_str`] fails at
7732        // caixa-core build time. Peer of the M3
7733        // `placement_strategy_display_routes_through_as_str_helper`
7734        // (cc8f749) which the M3 axis converged first.
7735        for &variant in RestartStrategy::ALL {
7736            assert_eq!(
7737                variant.to_string(),
7738                variant.as_str(),
7739                "RestartStrategy::{variant:?} Display must route through \
7740                 RestartStrategy::as_str (single source of truth: the lifted \
7741                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7742            );
7743        }
7744    }
7745
7746    #[test]
7747    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7748        // The fail-before-pass-after pin on the second half of the
7749        // three-path convergence: `Display` (user-facing text) agrees
7750        // byte-for-byte with the `Serialize` derive's wire format
7751        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7752        // scalar) on every variant. Pre-convergence the two paths
7753        // were structurally independent — a future
7754        // `#[serde(rename_all = "kebab-case")]` attribute on the
7755        // enum would silently rebrand the emitted wire scalar
7756        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7757        // `simple-one-for-one`) while every consumer that
7758        // pretty-prints the strategy (the future wasm-operator's
7759        // per-supervisor sibling-restart-strategy diagnostic line,
7760        // the future `feira app graph` per-supervisor strategy line,
7761        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7762        // materializer's admission-webhook rejection body) would
7763        // still emit the PascalCase form the `as_str` / `Display`
7764        // route returns, with the mismatch surfacing at consumer
7765        // parse time / operator dispatch time far from the source
7766        // rebrand commit. Pin the two paths byte-for-byte here so any
7767        // future serde-attribute or variant-rename drift is a
7768        // caixa-core-build-time test failure at this call, not a
7769        // silent per-consumer dispatch miss. Peer of the M3
7770        // `placement_strategy_display_matches_serialized_wire_byte_string`
7771        // (cc8f749) which the M3 axis converged first.
7772        for &variant in RestartStrategy::ALL {
7773            let wire = serde_json::to_string(&variant).unwrap();
7774            let unquoted = wire
7775                .strip_prefix('"')
7776                .and_then(|s| s.strip_suffix('"'))
7777                .expect("serialized RestartStrategy is a JSON string");
7778            assert_eq!(
7779                variant.to_string(),
7780                unquoted,
7781                "RestartStrategy::{variant:?} Display byte-string must match the \
7782                 Serialize derive's wire byte-string (three-path convergence: \
7783                 Display + as_str + Serialize all resolve to the same \
7784                 SUPERVISOR_ESTRATEGIA_* const)"
7785            );
7786        }
7787    }
7788
7789    #[test]
7790    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7791        // Fail-before-pass-after byte-parity pin on the lifted
7792        // `impl AsRef<str> for RestartStrategy` — asserts the
7793        // standard-library trait impl and the substrate-primitive
7794        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7795        // to the same `&str` per instance across the four-arm
7796        // closed set, so any future silent detour that routes the
7797        // impl through a divergent projection (a per-arm inline
7798        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7799        // re-inlining that opens a compile-time link to the un-lifted
7800        // arm-literal, a swap onto the kebab-case
7801        // [`gen_platform::Discriminant`] catalog identity that would
7802        // collide the wire axis with the dispatcher-catalog axis) trips
7803        // at caixa-core test time under `PartialEq` rather than at a
7804        // downstream `impl AsRef<str>`-bound consumer's silent split.
7805        // Sweeps every one of the four arms
7806        // [`RestartStrategy::ALL`] carries so no arm's projection is
7807        // covered only by the sibling wire-format `Serialize` derive
7808        // path. Peer of the sibling
7809        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7810        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7811        // top-level `:versao` typed newtype — the two pins together
7812        // cover the substrate primitive's `AsRef<str>` projection axis
7813        // on the paired newtype + closed-set-typed-enum surface.
7814        for &variant in RestartStrategy::ALL {
7815            assert_eq!(
7816                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7817                variant.as_str(),
7818                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7819                 byte-equal RestartStrategy::as_str on the same instance \
7820                 — divergence signals a silent detour off the substrate-\
7821                 primitive accessor"
7822            );
7823        }
7824    }
7825
7826    #[test]
7827    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7828        // Fail-before-pass-after byte-parity pin on the three-path
7829        // convergence discipline the M2 sibling-restart primitive now
7830        // carries on the `&str`-projection axis:
7831        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7832        // lifted impl), `format!("{s}")` (the pre-existing
7833        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7834        // primitive `pub const fn` accessor both trait impls delegate
7835        // through) must resolve to the same byte-string on every
7836        // instance across the four-arm closed set. Refuses any future
7837        // divergence between the two trait impls (a stray
7838        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7839        // rather than delegating through the shared accessor; a
7840        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7841        // literal cascade) that would silently split the two
7842        // projection paths of the same closed-set typed enum. Mirrors
7843        // the sibling three-path-convergence discipline the peer
7844        // [`crate::CaixaVersion`] typed newtype carries on its
7845        // `AsRef<str>` / `Display` / `as_str` triple
7846        // (version.rs pin
7847        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7848        // 16d5c7e).
7849        for &variant in RestartStrategy::ALL {
7850            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7851            let via_display: String = format!("{variant}");
7852            let via_accessor: &str = variant.as_str();
7853            assert_eq!(via_as_ref, via_accessor);
7854            assert_eq!(via_display, via_accessor);
7855            assert_eq!(via_as_ref, via_display.as_str());
7856        }
7857    }
7858
7859    #[test]
7860    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7861        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7862        // exhaustive-iteration surface: every variant appears exactly
7863        // once, and the slice length matches the arm count of the
7864        // closed set. Every consumer that walks the accepted-strategy
7865        // set (a future `feira supervisor --estrategia …` CLI-side
7866        // arg-parse's "did you mean" hint, a future M4 admission-
7867        // webhook's rejection body naming the accepted-`:estrategia`
7868        // list, the [`RestartStrategy::from_wire`] reverse-projection
7869        // consumers that iterate the accept-set for diagnostic
7870        // rendering) reads through this slice, so a future arm addition
7871        // that grows the enum but forgets to grow [`Self::ALL`]
7872        // silently truncates every downstream consumer's accept-set at
7873        // the same pre-addition boundary — this pin fails at caixa-core
7874        // build time on the pairwise-distinct + arm-count invariants.
7875        //
7876        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7877        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7878        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7879        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7880        // pins on the peer closed-set typed-enum axes.
7881        let all: &[RestartStrategy] = RestartStrategy::ALL;
7882        assert_eq!(
7883            all.len(),
7884            4,
7885            "RestartStrategy::ALL must enumerate every variant of the \
7886             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7887             SimpleOneForOne); got {all:?}"
7888        );
7889        for (i, a) in all.iter().enumerate() {
7890            for (j, b) in all.iter().enumerate() {
7891                if i != j {
7892                    assert_ne!(
7893                        a, b,
7894                        "RestartStrategy::ALL must carry every variant exactly \
7895                         once — got duplicate {a:?} at indices {i} and {j}"
7896                    );
7897                }
7898            }
7899        }
7900        for variant in [
7901            RestartStrategy::OneForOne,
7902            RestartStrategy::OneForAll,
7903            RestartStrategy::RestForOne,
7904            RestartStrategy::SimpleOneForOne,
7905        ] {
7906            assert!(
7907                all.contains(&variant),
7908                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7909                 addition that grows the enum but forgets to grow the ALL slice \
7910                 silently truncates every downstream consumer's accept-set at \
7911                 the pre-addition boundary"
7912            );
7913        }
7914    }
7915
7916    #[test]
7917    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7918        // Fail-before-pass-after pin on the forward accept-set of the
7919        // [`RestartStrategy::from_wire`] reverse projection: every
7920        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7921        // constant the [`RestartStrategy::as_str`] emitter walks parses
7922        // back to its paired variant. Any future arm addition that
7923        // grows the emitter's `as_str` match but forgets to grow the
7924        // parser's `from_wire` match silently splits the two halves of
7925        // the round-trip — the wire byte-string one non-serde consumer
7926        // parses from the one the emitter wrote — with the failure
7927        // surfacing at parse time far from the rebrand commit. Pinning
7928        // the four-arm accept-set here catches the drift at caixa-core
7929        // build time.
7930        //
7931        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7932        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7933        // accept-set pins on the peer closed-set typed-enum `str → Self`
7934        // axes.
7935        for (wire, expected) in [
7936            (
7937                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7938                RestartStrategy::OneForOne,
7939            ),
7940            (
7941                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7942                RestartStrategy::OneForAll,
7943            ),
7944            (
7945                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7946                RestartStrategy::RestForOne,
7947            ),
7948            (
7949                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7950                RestartStrategy::SimpleOneForOne,
7951            ),
7952        ] {
7953            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7954                panic!(
7955                    "RestartStrategy::from_wire({wire:?}) must accept every \
7956                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7957                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7958                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7959                )
7960            });
7961            assert_eq!(
7962                parsed, expected,
7963                "RestartStrategy::from_wire({wire:?}) must return \
7964                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7965            );
7966        }
7967    }
7968
7969    #[test]
7970    fn restart_strategy_from_wire_round_trips_through_as_str() {
7971        // Fail-before-pass-after pin on the closed round-trip between
7972        // the forward [`RestartStrategy::as_str`] emitter and the
7973        // reverse [`RestartStrategy::from_wire`] parser: for every
7974        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7975        // output must return exactly the same variant. Any per-arm
7976        // divergence — a future arm added to `as_str` but not
7977        // `from_wire`, an accidental copy-paste flip in one but not
7978        // the other — silently splits the emit and parse halves and
7979        // the failure surfaces at consumer parse time far from the
7980        // drift site. The `ALL`-iterating shape means a future arm
7981        // addition picks up the coverage by construction.
7982        //
7983        // Peer of the sibling
7984        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7985        // (18c7342) round-trip pin on
7986        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7987        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7988        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7989        for &variant in RestartStrategy::ALL {
7990            let wire = variant.as_str();
7991            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7992                panic!(
7993                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7994                     must be Some({variant:?}) — the two halves of the round-trip \
7995                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7996                     got None on wire byte-string {wire:?}"
7997                )
7998            });
7999            assert_eq!(
8000                parsed, variant,
8001                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8002                 must round-trip to the same variant; got {parsed:?}"
8003            );
8004        }
8005    }
8006
8007    #[test]
8008    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8009        // Fail-before-pass-after pin on the closed-set refusal
8010        // discipline of [`RestartStrategy::from_wire`]: every
8011        // byte-string outside the four-arm accept-set returns `None`
8012        // rather than silently collapsing onto the [`Default`]
8013        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8014        // exercised here sweeps the load-bearing drift shapes: the
8015        // empty string (a stripped serde-attribute drift), all-
8016        // whitespace strings (the canonical text-editor accidental
8017        // padding shape), the kebab-case dispatcher-catalog identities
8018        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8019        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8020        // derived [`std::str::FromStr`] accept-set, which parses the
8021        // *other* axis of this enum's two-axis split and must not leak
8022        // into the `from_wire` PascalCase-wire accept-set), the
8023        // lowercased single-word forms (`"oneforone"`), the padded
8024        // canonical scalar (`" OneForOne "`), the trailing-newline
8025        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8026        // (`"AllForOne"` — the canonical typo direction).
8027        //
8028        // Peer of the sibling
8029        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8030        // (2aa6d23) +
8031        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8032        // (18c7342) refusal pins on the peer closed-set typed-enum
8033        // axes.
8034        for bad in [
8035            "",
8036            " ",
8037            "\n",
8038            "\t",
8039            "one-for-one",
8040            "one-for-all",
8041            "rest-for-one",
8042            "simple-one-for-one",
8043            "oneforone",
8044            "OneForOnes",
8045            "one_for_one",
8046            "one for one",
8047            "ONEFORONE",
8048            "OneForOne ",
8049            " OneForOne",
8050            " SimpleOneForOne ",
8051            "OneForOne\n",
8052            "restforone",
8053            "REST_FOR_ONE",
8054            "AllForOne",
8055            "Simple",
8056            "?",
8057        ] {
8058            assert!(
8059                RestartStrategy::from_wire(bad).is_none(),
8060                "RestartStrategy::from_wire({bad:?}) must return None — the \
8061                 parser's accept-set is exactly the four RestartStrategy::as_str \
8062                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8063                 and this byte-string is outside that closed set"
8064            );
8065        }
8066    }
8067
8068    #[test]
8069    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8070        // Fail-before-pass-after pin on the fourth path of the four-path
8071        // convergence: `from_wire` (the reverse projection) inverts the
8072        // `Serialize` derive's wire byte-string on every variant.
8073        // Together with the pre-existing three-path convergence
8074        // (`Display` + `as_str` + `Serialize` all resolve to the same
8075        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8076        // pinned by
8077        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8078        // this closes the round-trip: the wire byte-string the
8079        // `Serialize` derive emits parses back to the same variant
8080        // through `from_wire`, so any future serde-attribute or variant-
8081        // rename drift on the emit half now surfaces as a matched drift
8082        // on the parse half at caixa-core build time — the two halves
8083        // migrate as a unit through the lifted consts on any future
8084        // rename, and the round-trip cannot silently split.
8085        //
8086        // Peer of the sibling
8087        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8088        // (18c7342) wire-format pin on
8089        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8090        for &variant in RestartStrategy::ALL {
8091            let wire = serde_json::to_string(&variant).unwrap();
8092            let unquoted = wire
8093                .strip_prefix('"')
8094                .and_then(|s| s.strip_suffix('"'))
8095                .expect("serialized RestartStrategy is a JSON string");
8096            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8097                panic!(
8098                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8099                     Serialize derive's wire byte-string for \
8100                     RestartStrategy::{variant:?} — the four-path convergence \
8101                     (Display + as_str + Serialize + from_wire) resolves through \
8102                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8103                )
8104            });
8105            assert_eq!(
8106                parsed, variant,
8107                "RestartStrategy::from_wire of the Serialize derive's wire \
8108                 byte-string for RestartStrategy::{variant:?} must round-trip \
8109                 to the same variant; got {parsed:?}"
8110            );
8111        }
8112    }
8113
8114    #[test]
8115    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8116        // Fail-before-pass-after byte-parity pin on the newly lifted
8117        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8118        // library trait impl and the substrate-primitive
8119        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8120        // the same four-arm accept-set across every arm the exhaustive
8121        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8122        // detour that routes the trait impl through a divergent projection
8123        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8124        // … }` re-inlining that opens a compile-time link to the un-
8125        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8126        // attribute drift that silently splits the wire byte-string from
8127        // every consumer that reaches for this typed dispatch, an
8128        // accidental swap onto the kebab-case dispatcher-catalog axis the
8129        // pre-existing [`std::str::FromStr`] impl parses through and which
8130        // would collide the two-axis wire/catalog split the sibling
8131        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8132        // trips at caixa-core test time under `assert_eq!` rather than at
8133        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8134        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8135        // carries so no arm's projection is covered only by the sibling
8136        // method-named `from_wire` path. Peer of the sibling
8137        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8138        // (3c83606),
8139        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8140        // (bf33136), and the M3
8141        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8142        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8143        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8144        // surface.
8145        for &variant in RestartStrategy::ALL {
8146            let wire = variant.as_str();
8147            assert_eq!(
8148                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8149                Ok(variant),
8150                "TryFrom<&str> impl on RestartStrategy must round-trip \
8151                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8152                 Ok(RestartStrategy::{variant:?}) — divergence from \
8153                 RestartStrategy::from_wire signals a silent detour off \
8154                 the substrate-primitive accessor"
8155            );
8156            assert_eq!(
8157                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8158                RestartStrategy::from_wire(wire),
8159                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8160                 RestartStrategy::from_wire on the same input"
8161            );
8162        }
8163    }
8164
8165    #[test]
8166    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8167        // Rejection witness on the `impl TryFrom<&str> for
8168        // RestartStrategy` — sweeps a candidate set of byte-strings
8169        // outside the four-arm PascalCase wire accept-set the sibling
8170        // [`RestartStrategy::as_str`] emits and asserts every one lands on
8171        // `Err(())`, so a future accidental widening of the trait impl's
8172        // accept-set (a stray additional
8173        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8174        // path, a silent inclusion of the kebab-case dispatcher-catalog
8175        // byte-string the pre-existing [`std::str::FromStr`] impl the
8176        // [`gen_platform::FromStrKind`] derive installs parses onto the
8177        // wire axis — which would collide the two-axis
8178        // wire/dispatcher-catalog split the sibling
8179        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8180        // an English-rebrand or plural-arm silent alias that would
8181        // widen the wire accept-set past the OTP-canonical four) trips at
8182        // caixa-core test time. The candidate set includes the empty
8183        // string, whitespace-only padding, the kebab-case dispatcher-
8184        // catalog byte-strings on the sibling axis (a caller who confuses
8185        // the two axes trips here rather than at a downstream consumer's
8186        // silent reject), a lowercase / uppercase / mixed-case fold of
8187        // each PascalCase arm (a caller who assumes case-fold acceptance
8188        // trips here), leading/trailing whitespace padding, the trailing-
8189        // newline shape, quote-wrapped candidates, and a residual set of
8190        // plausible-but-wrong English rebrand candidates. Peer of the
8191        // sibling
8192        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8193        // (3c83606) and
8194        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8195        // (6fd00cd) rejection witnesses.
8196        let rejected: &[&str] = &[
8197            "",
8198            " ",
8199            "\n",
8200            "\t",
8201            "one-for-one",
8202            "one-for-all",
8203            "rest-for-one",
8204            "simple-one-for-one",
8205            "oneforone",
8206            "one_for_one",
8207            "OneForOnes",
8208            "ONEFORONE",
8209            "oneforall",
8210            "restforone",
8211            "simpleoneforone",
8212            "OneForOne ",
8213            " OneForOne",
8214            " OneForAll ",
8215            "OneForOne\n",
8216            "RestForOne\t",
8217            "OneForEach",
8218            "AllForOne",
8219            "one for one",
8220            "\"OneForOne\"",
8221            "?",
8222        ];
8223        for &input in rejected {
8224            assert_eq!(
8225                <RestartStrategy as TryFrom<&str>>::try_from(input),
8226                Err(()),
8227                "TryFrom<&str> impl on RestartStrategy must reject the \
8228                 non-wire byte-string {input:?} — silent acceptance signals \
8229                 an accept-set widening off the paired \
8230                 RestartStrategy::from_wire resolver"
8231            );
8232        }
8233    }
8234
8235    #[test]
8236    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8237        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8238        // `from_wire` reverse projections must resolve identically on
8239        // *every* input, not just the ones [`RestartStrategy::ALL`]
8240        // enumerates. Sweeps a mixed candidate set spanning accepted
8241        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8242        // dispatcher-catalog byte-strings, empty, whitespace-padded,
8243        // quoted, English-rebrand candidates) inputs and asserts the
8244        // trait's `Result::ok()` projection byte-equals the method-named
8245        // resolver's `Option<Self>` return-shape on each, locking the two
8246        // paths together by construction so any future detour (a stray
8247        // `try_from` special-case that widens or narrows the accept-set
8248        // outside the paired `from_wire` resolver, an accidental swap
8249        // onto the kebab-case [`std::str::FromStr`] impl the
8250        // [`gen_platform::FromStrKind`] derive installs on the sibling
8251        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8252        // the sibling
8253        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8254        // pin — extends the round-trip discipline onto the M2-OTP-shape
8255        // sibling-restart axis.
8256        let candidates: &[&str] = &[
8257            "OneForOne",
8258            "OneForAll",
8259            "RestForOne",
8260            "SimpleOneForOne",
8261            "",
8262            "one-for-one",
8263            "one-for-all",
8264            "rest-for-one",
8265            "simple-one-for-one",
8266            "oneforone",
8267            "unknown",
8268            "OneForOne ",
8269            " OneForOne",
8270            "\"OneForOne\"",
8271            "OneForEach",
8272            "?",
8273        ];
8274        for &input in candidates {
8275            let via_trait: Option<RestartStrategy> =
8276                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8277            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8278            assert_eq!(
8279                via_trait, via_method,
8280                "TryFrom<&str> and from_wire must resolve identically on \
8281                 input {input:?} — divergence signals the two reverse-\
8282                 projection paths have drifted onto different accept-sets"
8283            );
8284        }
8285    }
8286
8287    #[test]
8288    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8289        // Fail-before-pass-after byte-parity pin on the newly lifted
8290        // `impl From<RestartStrategy> for &'static str` — asserts the
8291        // standard-library trait impl and the substrate-primitive
8292        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8293        // the same four-arm emit-set across every arm the exhaustive
8294        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8295        // detour that routes the trait impl through a divergent
8296        // projection (a per-arm inline `match strategy { OneForOne =>
8297        // "OneForOne", … }` re-inlining that opens a compile-time link to
8298        // the un-lifted arm-literal, an accidental swap onto the sibling
8299        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8300        // would collide the two-axis wire/catalog split the sibling
8301        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8302        // at caixa-core test time under `assert_eq!` rather than at a
8303        // downstream `impl Into<&'static str>`-bound consumer's silent
8304        // split. Sweeps every one of the four arms
8305        // [`RestartStrategy::ALL`] carries so no arm's projection is
8306        // covered only by the sibling method-named `as_str` /
8307        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8308        // `<&'static str as From<RestartStrategy>>::from` output in a
8309        // `const`-shape binding to make the `'static` lifetime promise a
8310        // build-time invariant — a future accidental downgrade of any of
8311        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8312        // constants to a non-`&'static str` (a `String::leak()`-produced
8313        // return, a `Box::leak`-cast) trips at caixa-core build time
8314        // rather than at a downstream `'static`-bound consumer.
8315        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8316        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8317        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8318        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8319        for &variant in RestartStrategy::ALL {
8320            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8321            let via_method: &'static str = variant.as_str();
8322            assert_eq!(
8323                via_trait, via_method,
8324                "From<RestartStrategy> for &'static str impl must round-trip \
8325                 RestartStrategy::{variant:?} to the same lifted \
8326                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8327                 divergence signals a silent detour off the substrate-primitive \
8328                 accessor"
8329            );
8330            let via_into: &'static str = variant.into();
8331            assert_eq!(
8332                via_into, via_method,
8333                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8334                 byte-equal RestartStrategy::as_str on the same input — the \
8335                 blanket-derived Into shape must resolve to the same as_str \
8336                 dispatch as the explicit From impl"
8337            );
8338        }
8339        assert_eq!(
8340            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8341            [
8342                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8343                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8344                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8345                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8346            ],
8347            "const-context RestartStrategy::as_str must resolve to the four \
8348             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8349             downgrade of any arm to a non-const or non-static byte-string \
8350             breaks the `&'static str`-lifetime promise the paired \
8351             From<RestartStrategy> for &'static str impl carries by \
8352             construction"
8353        );
8354    }
8355
8356    #[test]
8357    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8358        // Cross-axis partition pin: the paired trait-idiomatic
8359        // `From<RestartStrategy> for &'static str` forward projection and
8360        // the method-named [`RestartStrategy::as_str`] forward projection
8361        // must resolve identically on *every* arm, not just the ones
8362        // named in the primary byte-parity pin above. Sweeps every
8363        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8364        // output byte-equals the method-named accessor's return-value on
8365        // each, locking the two forward-projection paths together by
8366        // construction so any future detour (a stray `From` special-case
8367        // that lands on a divergent per-arm literal outside the paired
8368        // `as_str` dispatch, a hypothetical rebrand touching one axis
8369        // without the other) trips at caixa-core test time. Peer of the
8370        // sibling reverse-projection partition pin
8371        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8372        // — extends the round-trip discipline onto the trait-idiomatic
8373        // *forward* axis, closing the two-way `Self ↔ &'static str`
8374        // round-trip on the trait-idiomatic pair
8375        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8376        // well as the pre-existing method-named pair
8377        // (`as_str` + `from_wire`).
8378        for &variant in RestartStrategy::ALL {
8379            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8380            let via_method: &'static str = variant.as_str();
8381            assert_eq!(
8382                via_trait, via_method,
8383                "From<RestartStrategy> for &'static str and \
8384                 RestartStrategy::as_str must resolve identically on \
8385                 RestartStrategy::{variant:?} — divergence signals the \
8386                 two forward-projection paths have drifted onto different \
8387                 emit-sets"
8388            );
8389        }
8390        // Round-trip witness: every arm's forward `From` output re-parses
8391        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8392        // to the original variant. Closes the two-way `RestartStrategy ↔
8393        // &'static str` round-trip on the trait-idiomatic axis pair,
8394        // mirroring the pre-existing method-named `as_str` + `from_wire`
8395        // round-trip on the substrate-primitive axis pair.
8396        for &variant in RestartStrategy::ALL {
8397            let emitted: &'static str = variant.into();
8398            let re_parsed: Result<RestartStrategy, ()> =
8399                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8400            assert_eq!(
8401                re_parsed,
8402                Ok(variant),
8403                "trait-idiomatic axis pair must round-trip \
8404                 RestartStrategy::{variant:?} through `.into::<&'static \
8405                 str>()` and back through `TryFrom<&str>` — a break signals \
8406                 the forward-emit and reverse-parse axes have drifted onto \
8407                 different vocabularies"
8408            );
8409        }
8410    }
8411
8412    #[test]
8413    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8414        // Fail-before-pass-after byte-parity pin on the newly lifted
8415        // `impl From<&RestartStrategy> for &'static str` — asserts the
8416        // borrowed-input standard-library trait impl and the substrate-
8417        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8418        // resolve to the same four-arm emit-set across every arm the
8419        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8420        // `From` trait does not auto-derive the borrowed-input sibling
8421        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8422        // where T: Copy, U: From<T>` blanket in `core`), so the
8423        // borrowed-input axis is a distinct trait-idiomatic surface
8424        // that a `.iter().map(Into::into)` shape over
8425        // [`RestartStrategy::ALL`] (whose iterator yields
8426        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8427        // this impl and no other — the paired owned-input
8428        // [`From<RestartStrategy>`] impl requires an explicit
8429        // `.copied()` / dereference before the trait fires.
8430        // Materializes the `<&'static str as
8431        // From<&RestartStrategy>>::from` output in a `const`-shape
8432        // binding to make the `'static` lifetime promise a build-time
8433        // invariant.
8434        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8435        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8436        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8437        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8438        for variant in RestartStrategy::ALL {
8439            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8440            let via_method: &'static str = variant.as_str();
8441            assert_eq!(
8442                via_trait, via_method,
8443                "From<&RestartStrategy> for &'static str impl must \
8444                 round-trip &RestartStrategy::{variant:?} to the same \
8445                 lifted SUPERVISOR_ESTRATEGIA_* const \
8446                 RestartStrategy::as_str returns — divergence signals a \
8447                 silent detour off the substrate-primitive accessor"
8448            );
8449            let via_into: &'static str = variant.into();
8450            assert_eq!(
8451                via_into, via_method,
8452                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8453                 must byte-equal RestartStrategy::as_str on the same input — \
8454                 the blanket-derived Into shape must resolve to the same \
8455                 as_str dispatch as the explicit From impl"
8456            );
8457        }
8458        assert_eq!(
8459            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8460            [
8461                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8462                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8463                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8464                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8465            ],
8466            "const-context RestartStrategy::as_str must resolve to the \
8467             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8468             input From<&RestartStrategy> for &'static str impl inherits \
8469             its `'static` lifetime promise from the same accessor the \
8470             owned-input sibling routes through"
8471        );
8472    }
8473
8474    #[test]
8475    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8476        // Cross-axis partition pin: the paired trait-idiomatic
8477        // owned-input `From<RestartStrategy> for &'static str` (523157d
8478        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8479        // &'static str` (this lift) forward projections must resolve
8480        // identically on every arm, locking the two input-shape paths
8481        // together so any future detour trips at caixa-core test time.
8482        // Then a witness that a `.iter().map(Into::into)` pipe over
8483        // [`RestartStrategy::ALL`] (whose iterator yields
8484        // `&RestartStrategy`) materializes the four-arm accept-set
8485        // through the borrowed-input axis alone — the exact shape a
8486        // future wasm-operator per-supervisor sibling-restart-strategy
8487        // diagnostic line, a future substrate-wide per-arm diagnostic
8488        // column, or a
8489        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8490        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8491        // per-strategy lookup reaches through — closing the two-way
8492        // owned/borrowed input-shape symmetry on the forward-projection
8493        // trait-idiomatic axis. Peer of the sibling
8494        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8495        // (64aa742) /
8496        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8497        // (5ab993a) /
8498        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8499        // (807b0b5) partition pins on the sibling closed-set typed-enum
8500        // discriminator axes — extends the borrowed-input axis
8501        // discipline onto the first M2 OTP-shape sibling-restart
8502        // closed-set typed enum on the caixa surface. Also closes the
8503        // direct two-way `&Self → &'static str → Self` round-trip via
8504        // the paired [`TryFrom<&str>`] axis — unlike the peer
8505        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8506        // lowercase Portuguese diagnostic bytes while the reverse
8507        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8508        // trip through an intermediate wire-vocab hop), the
8509        // [`RestartStrategy::as_str`] emit and
8510        // [`RestartStrategy::from_wire`] parse share the same
8511        // `PascalCase` vocabulary by construction, so the borrowed-
8512        // input forward axis and the reverse axis compose directly.
8513        for &variant in RestartStrategy::ALL {
8514            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8515            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8516            assert_eq!(
8517                owned, borrowed,
8518                "From<RestartStrategy> and From<&RestartStrategy> for \
8519                 &'static str must resolve identically on \
8520                 RestartStrategy::{variant:?} — divergence signals the \
8521                 owned-input and borrowed-input forward-projection paths \
8522                 have drifted onto different emit-sets"
8523            );
8524        }
8525        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8526        let via_method: Vec<&'static str> =
8527            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8528        assert_eq!(
8529            via_iter, via_method,
8530            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8531             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8532             borrowed-input `From<&RestartStrategy> for &'static str` \
8533             axis is what makes the `.iter().map(Into::into)` shape route \
8534             through the substrate-primitive `RestartStrategy::as_str` \
8535             accessor rather than through a per-call-site `.copied()` / \
8536             dereference detour"
8537        );
8538        for variant in RestartStrategy::ALL {
8539            let emitted: &'static str = variant.into();
8540            let re_parsed: Result<RestartStrategy, ()> =
8541                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8542            assert_eq!(
8543                re_parsed,
8544                Ok(*variant),
8545                "trait-idiomatic borrowed-input forward-projection + \
8546                 reverse-projection axis pair must round-trip \
8547                 &RestartStrategy::{variant:?} through `.into::<&'static \
8548                 str>()` (via the borrowed-input axis) and back through \
8549                 `TryFrom<&str>` — a break signals the borrowed-input \
8550                 forward-emit and reverse-parse axes have drifted onto \
8551                 different vocabularies"
8552            );
8553        }
8554    }
8555
8556    #[test]
8557    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8558        // Fail-before-pass-after byte-parity pin on the newly lifted
8559        // `impl From<RestartStrategy> for String` — asserts the
8560        // owned-`String`-returning standard-library trait impl and the
8561        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8562        // accessor resolve to the same four-arm emit-set across every
8563        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8564        // Rust's standard library does not carry a blanket
8565        // `impl<T: AsRef<str>> From<T> for String` (nor an
8566        // `impl<T: fmt::Display> From<T> for String`), so the
8567        // owned-`String` forward-projection axis is a distinct
8568        // trait-idiomatic surface that a
8569        // `let key: String = strategy.into();`-shaped call site
8570        // reaches through this impl and no other — the paired sibling
8571        // `From<RestartStrategy> for &'static str` impl forces every
8572        // owned-`String` call site through an explicit
8573        // `.to_owned()` / `String::from` restatement.
8574        for &variant in RestartStrategy::ALL {
8575            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8576            let via_method: &'static str = variant.as_str();
8577            assert_eq!(
8578                via_trait.as_str(),
8579                via_method,
8580                "From<RestartStrategy> for String impl must round-trip \
8581                 RestartStrategy::{variant:?} to the same lifted \
8582                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8583                 returns — divergence signals a silent detour off the \
8584                 substrate-primitive accessor"
8585            );
8586            let via_into: String = variant.into();
8587            assert_eq!(
8588                via_into.as_str(),
8589                via_method,
8590                "Into<String>::into on RestartStrategy::{variant:?} must \
8591                 byte-equal RestartStrategy::as_str on the same input — the \
8592                 blanket-derived Into shape must resolve to the same as_str \
8593                 dispatch as the explicit From impl"
8594            );
8595        }
8596    }
8597
8598    #[test]
8599    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8600        // Cross-axis partition pin: the paired trait-idiomatic
8601        // owned-`String` `From<RestartStrategy> for String` (this lift)
8602        // and owned-`&'static str` `From<RestartStrategy> for &'static
8603        // str` (523157d) forward projections must resolve identically
8604        // on every arm, locking the two return-type-shape paths
8605        // together so any future detour trips at caixa-core test time.
8606        // Also byte-parity witness against the sibling
8607        // [`ToString::to_string`] surface routed through
8608        // [`std::fmt::Display`] — the three owned-heap-string paths
8609        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8610        // resolve identically on every arm so a future consumer that
8611        // picks any of the three lands on the same lifted
8612        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8613        // witness through the paired trait-idiomatic reverse
8614        // [`TryFrom<&str>`] axis on the owned-`String`'s
8615        // [`String::as_str`] borrow that closes the two-way
8616        // `Self → String → Self` round-trip on the trait-idiomatic
8617        // owned-`String` forward + reverse axis pair.
8618        for &variant in RestartStrategy::ALL {
8619            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8620            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8621            assert_eq!(
8622                owned_string.as_str(),
8623                owned_static,
8624                "From<RestartStrategy> for String and From<RestartStrategy> \
8625                 for &'static str must resolve identically on \
8626                 RestartStrategy::{variant:?} — divergence signals the \
8627                 owned-`String` and owned-`&'static str` forward-projection \
8628                 return-type-shape paths have drifted onto different \
8629                 emit-sets"
8630            );
8631            let via_to_string: String = variant.to_string();
8632            assert_eq!(
8633                owned_string, via_to_string,
8634                "From<RestartStrategy> for String must byte-equal \
8635                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8636                 divergence signals the trait-idiomatic owned-`String` \
8637                 forward-projection axis and the ToString-through-Display \
8638                 axis have drifted onto different emit-sets"
8639            );
8640        }
8641        let via_iter: Vec<String> = RestartStrategy::ALL
8642            .iter()
8643            .copied()
8644            .map(String::from)
8645            .collect();
8646        let via_method: Vec<String> = RestartStrategy::ALL
8647            .iter()
8648            .map(|s| s.as_str().to_owned())
8649            .collect();
8650        assert_eq!(
8651            via_iter, via_method,
8652            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8653             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8654             every arm — the owned-`String` `From<RestartStrategy> for \
8655             String` axis is what makes the `String::from` composition \
8656             route through the substrate-primitive `RestartStrategy::as_str` \
8657             accessor rather than through a per-call-site `.to_owned()` / \
8658             `String::from(strategy.as_str())` detour"
8659        );
8660        for &variant in RestartStrategy::ALL {
8661            let emitted: String = variant.into();
8662            let re_parsed: Result<RestartStrategy, ()> =
8663                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8664            assert_eq!(
8665                re_parsed,
8666                Ok(variant),
8667                "trait-idiomatic owned-`String` forward-projection + \
8668                 reverse-projection axis pair must round-trip \
8669                 RestartStrategy::{variant:?} through `.into::<String>()` \
8670                 and back through `TryFrom<&str>` on the owned-`String`'s \
8671                 String::as_str borrow — a break signals the owned-`String` \
8672                 forward-emit and reverse-parse axes have drifted onto \
8673                 different vocabularies"
8674            );
8675        }
8676    }
8677
8678    #[test]
8679    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8680        // Fail-before-pass-after byte-parity pin on the newly lifted
8681        // `impl From<&RestartStrategy> for String` — asserts the
8682        // borrowed-input owned-`String`-returning standard-library trait
8683        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8684        // `pub const fn` accessor resolve to the same four-arm emit-set
8685        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8686        // enumerates. Rust's standard library does not carry a blanket
8687        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8688        // `impl<T: fmt::Display> From<&T> for String`), so the
8689        // borrowed-input owned-`String` forward-projection axis is a
8690        // distinct trait-idiomatic surface that a
8691        // `let key: String = (&strategy).into();`-shaped call site
8692        // reaches through this impl and no other — the paired sibling
8693        // `From<RestartStrategy> for String` impl forces every
8694        // borrowed-input call site through an explicit `Copy` deref
8695        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8696        // `.to_string()` detour.
8697        for &variant in RestartStrategy::ALL {
8698            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8699            let via_method: &'static str = variant.as_str();
8700            assert_eq!(
8701                via_trait.as_str(),
8702                via_method,
8703                "From<&RestartStrategy> for String impl must round-trip \
8704                 &RestartStrategy::{variant:?} to the same lifted \
8705                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8706                 returns — divergence signals a silent detour off the \
8707                 substrate-primitive accessor"
8708            );
8709            let via_into: String = (&variant).into();
8710            assert_eq!(
8711                via_into.as_str(),
8712                via_method,
8713                "Into<String>::into on &RestartStrategy::{variant:?} must \
8714                 byte-equal RestartStrategy::as_str on the same input — the \
8715                 blanket-derived Into shape must resolve to the same as_str \
8716                 dispatch as the explicit From impl"
8717            );
8718        }
8719    }
8720
8721    #[test]
8722    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8723        // Cross-axis partition pin: the newly lifted trait-idiomatic
8724        // borrowed-input owned-`String` `From<&RestartStrategy> for
8725        // String` (this lift), the paired owned-input owned-`String`
8726        // `From<RestartStrategy> for String` (7baa18a), the paired
8727        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8728        // for &'static str` (e941836), and the paired owned-input
8729        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8730        // (523157d) — every corner of the `{Self, &Self} × {&'static
8731        // str, String}` 2×2 trait-idiomatic projection family — must
8732        // resolve identically on every arm, locking the four
8733        // return-shape × input-shape paths together so any future
8734        // detour trips at caixa-core test time. Also byte-parity
8735        // witness against the sibling [`ToString::to_string`] surface
8736        // routed through [`std::fmt::Display`] and a direct round-trip
8737        // witness through the paired trait-idiomatic reverse
8738        // [`TryFrom<&str>`] axis on the owned-`String`'s
8739        // [`String::as_str`] borrow that closes the two-way
8740        // `&Self → String → Self` round-trip on the trait-idiomatic
8741        // borrowed-input owned-`String` forward + reverse axis pair.
8742        for &variant in RestartStrategy::ALL {
8743            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8744            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8745            let borrowed_static: &'static str =
8746                <&'static str as From<&RestartStrategy>>::from(&variant);
8747            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8748            assert_eq!(
8749                borrowed_string, owned_string,
8750                "From<&RestartStrategy> for String and From<RestartStrategy> \
8751                 for String must resolve identically on \
8752                 RestartStrategy::{variant:?} — divergence signals the \
8753                 borrowed-input and owned-input owned-`String` \
8754                 forward-projection input-shape paths have drifted onto \
8755                 different emit-sets"
8756            );
8757            assert_eq!(
8758                borrowed_string.as_str(),
8759                borrowed_static,
8760                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8761                 for &'static str must resolve identically on \
8762                 RestartStrategy::{variant:?} — divergence signals the \
8763                 borrowed-input `&'static str` and owned-`String` \
8764                 return-shape paths have drifted onto different emit-sets"
8765            );
8766            assert_eq!(
8767                borrowed_string.as_str(),
8768                owned_static,
8769                "From<&RestartStrategy> for String and From<RestartStrategy> \
8770                 for &'static str must resolve identically on \
8771                 RestartStrategy::{variant:?} — divergence signals a break \
8772                 in the diagonal corner of the {{Self, &Self}} × \
8773                 {{&'static str, String}} 2×2 trait-idiomatic \
8774                 projection family"
8775            );
8776            let via_to_string: String = variant.to_string();
8777            assert_eq!(
8778                borrowed_string, via_to_string,
8779                "From<&RestartStrategy> for String must byte-equal \
8780                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8781                 divergence signals the trait-idiomatic borrowed-input \
8782                 owned-`String` forward-projection axis and the \
8783                 ToString-through-Display axis have drifted onto different \
8784                 emit-sets"
8785            );
8786        }
8787        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8788        let via_method: Vec<String> = RestartStrategy::ALL
8789            .iter()
8790            .map(|s| s.as_str().to_owned())
8791            .collect();
8792        assert_eq!(
8793            via_iter, via_method,
8794            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8795             call site whose iteration axis holds `&RestartStrategy` by \
8796             construction — must byte-equal `.iter().map(|s| \
8797             s.as_str().to_owned())` on every arm — the borrowed-input \
8798             owned-`String` `From<&RestartStrategy> for String` axis is \
8799             what makes the `String::from` composition route through the \
8800             substrate-primitive `RestartStrategy::as_str` accessor \
8801             without a spurious `Copy` deref (which would only be \
8802             reachable through the owned-input `From<RestartStrategy> for \
8803             String` axis by first calling `.copied()` on the iterator)"
8804        );
8805        for &variant in RestartStrategy::ALL {
8806            let emitted: String = (&variant).into();
8807            let re_parsed: Result<RestartStrategy, ()> =
8808                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8809            assert_eq!(
8810                re_parsed,
8811                Ok(variant),
8812                "trait-idiomatic borrowed-input owned-`String` \
8813                 forward-projection + reverse-projection axis pair must \
8814                 round-trip &RestartStrategy::{variant:?} through \
8815                 `.into::<String>()` on the borrowed-input surface and \
8816                 back through `TryFrom<&str>` on the owned-`String`'s \
8817                 String::as_str borrow — a break signals the \
8818                 borrowed-input owned-`String` forward-emit and \
8819                 reverse-parse axes have drifted onto different \
8820                 vocabularies"
8821            );
8822        }
8823    }
8824
8825    #[test]
8826    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8827        // Fail-before-pass-after byte-parity pin on the newly lifted
8828        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8829        // asserts the standard-library trait impl and the substrate-
8830        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8831        // accessor resolve to the same four-arm emit-set across every
8832        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8833        // enumerates. Rust's standard library does not carry a blanket
8834        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8835        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8836        // the `Cow<'static, str>` forward-projection axis is a
8837        // distinct trait-idiomatic surface that a
8838        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8839        // site reaches through this impl and no other — the paired
8840        // sibling `From<RestartStrategy> for &'static str` and
8841        // `From<RestartStrategy> for String` impls force every
8842        // `Cow<'static, str>`-parameterized call site through a
8843        // `Cow::Borrowed(strategy.as_str())` /
8844        // `Cow::Owned(strategy.to_string())` composition whose type
8845        // bounds have no compile-time link back to the substrate
8846        // primitive.
8847        //
8848        // Also asserts the projection lands on the zero-alloc
8849        // [`std::borrow::Cow::Borrowed`] arm (not the
8850        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8851        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8852        // return lifetime by construction makes the borrowed arm the
8853        // type-correct projection with no runtime allocation. Any
8854        // future silent detour that routes the impl through the owned
8855        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8856        // that would allocate on every call site where the
8857        // `&'static str` return of [`super::RestartStrategy::as_str`]
8858        // makes the zero-alloc borrowed projection type-correct) trips
8859        // at caixa-core test time under the
8860        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8861        // than at a downstream `Cow<'static, str>`-bound consumer's
8862        // silent allocation.
8863        //
8864        // First peer on the substrate-wide trait-idiomatic
8865        // [`std::borrow::Cow<'static, str>`] forward-projection family
8866        // to extend the axis off the top-level [`super::CaixaKind`]
8867        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8868        // first M2 OTP-shape closed-set fieldless typed enum on the
8869        // caixa surface.
8870        for &variant in RestartStrategy::ALL {
8871            let via_trait: std::borrow::Cow<'static, str> =
8872                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8873            let via_method: &'static str = variant.as_str();
8874            assert_eq!(
8875                via_trait.as_ref(),
8876                via_method,
8877                "From<RestartStrategy> for Cow<'static, str> impl must \
8878                 round-trip RestartStrategy::{variant:?} to the same \
8879                 lifted SUPERVISOR_ESTRATEGIA_* const \
8880                 RestartStrategy::as_str returns — divergence signals a \
8881                 silent detour off the substrate-primitive accessor"
8882            );
8883            assert!(
8884                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8885                "From<RestartStrategy> for Cow<'static, str> impl must \
8886                 land on the zero-alloc Cow::Borrowed arm on \
8887                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8888                 signals the projection has silently allocated where \
8889                 the substrate-primitive RestartStrategy::as_str \
8890                 `&'static str` return makes the borrowed arm the \
8891                 type-correct projection"
8892            );
8893            let via_into: std::borrow::Cow<'static, str> = variant.into();
8894            assert_eq!(
8895                via_into.as_ref(),
8896                via_method,
8897                "Into<Cow<'static, str>>::into on \
8898                 RestartStrategy::{variant:?} must byte-equal \
8899                 RestartStrategy::as_str on the same input — the \
8900                 blanket-derived Into shape must resolve to the same \
8901                 as_str dispatch as the explicit From impl"
8902            );
8903            assert!(
8904                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8905                "Into<Cow<'static, str>>::into on \
8906                 RestartStrategy::{variant:?} must land on the \
8907                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8908                 Into shape must resolve to the same Cow::Borrowed \
8909                 dispatch as the explicit From impl"
8910            );
8911        }
8912    }
8913
8914    #[test]
8915    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8916        // Cross-axis partition pin: the newly lifted trait-idiomatic
8917        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8918        // (this lift), the paired owned-input `From<RestartStrategy>
8919        // for &'static str` (523157d), and the paired owned-input
8920        // `From<RestartStrategy> for String` (7baa18a) forward
8921        // projections must resolve identically on every arm, locking
8922        // the three return-shape paths together by construction so any
8923        // future detour trips at caixa-core test time. Also byte-parity
8924        // witness against the sibling [`ToString::to_string`] surface
8925        // routed through [`std::fmt::Display`] — every owned-heap-
8926        // string path (the `Cow::Owned` promotion of this axis's
8927        // `.into_owned()`, `From<RestartStrategy> for String`, and
8928        // `.to_string()`) resolves to the same lifted
8929        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8930        //
8931        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8932        // witness over [`super::RestartStrategy::ALL`] that
8933        // materializes the four-arm accept-set through the
8934        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8935        // shape a future `axum::response::IntoResponse` per-strategy
8936        // rejection-body composer, a future M4 admission-webhook
8937        // per-strategy rejection-reason emitter whose typing rules out
8938        // the sibling [`AsRef<str>`] borrowed return, or a future
8939        // substrate-wide per-strategy diagnostic surface that binds
8940        // through a [`Cow<'static, str>`] boundary reaches through.
8941        // The pipe witness also pins the zero-alloc discipline: every
8942        // element in the collected vector satisfies the
8943        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8944        // accidental silent-allocation regression on the pipe's
8945        // iteration axis is a caixa-core-test-time failure.
8946        for &variant in RestartStrategy::ALL {
8947            let via_cow: std::borrow::Cow<'static, str> =
8948                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8949            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8950            let via_string: String = <String as From<RestartStrategy>>::from(variant);
8951            assert_eq!(
8952                via_cow.as_ref(),
8953                via_static,
8954                "From<RestartStrategy> for Cow<'static, str> and \
8955                 From<RestartStrategy> for &'static str must resolve \
8956                 identically on RestartStrategy::{variant:?} — \
8957                 divergence signals the Cow<'static, str> and \
8958                 &'static str return-shape paths have drifted onto \
8959                 different emit-sets"
8960            );
8961            assert_eq!(
8962                via_cow.as_ref(),
8963                via_string.as_str(),
8964                "From<RestartStrategy> for Cow<'static, str> and \
8965                 From<RestartStrategy> for String must resolve \
8966                 identically on RestartStrategy::{variant:?} — \
8967                 divergence signals the Cow<'static, str> and String \
8968                 return-shape paths have drifted onto different \
8969                 emit-sets"
8970            );
8971            let via_to_string: String = variant.to_string();
8972            assert_eq!(
8973                via_cow.as_ref(),
8974                via_to_string.as_str(),
8975                "From<RestartStrategy> for Cow<'static, str> must \
8976                 byte-equal RestartStrategy::to_string on \
8977                 RestartStrategy::{variant:?} — divergence signals the \
8978                 trait-idiomatic Cow<'static, str> forward-projection \
8979                 axis and the ToString-through-Display axis have \
8980                 drifted onto different emit-sets"
8981            );
8982        }
8983        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8984            .iter()
8985            .copied()
8986            .map(std::borrow::Cow::from)
8987            .collect();
8988        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8989            .iter()
8990            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8991            .collect();
8992        assert_eq!(
8993            via_iter, via_method,
8994            "`.iter().copied().map(Cow::from)` over \
8995             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8996             Cow::Borrowed(s.as_str()))` on every arm — the \
8997             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8998             str>` axis is what makes the `Cow::from` composition \
8999             route through the substrate-primitive \
9000             `RestartStrategy::as_str` accessor with the zero-alloc \
9001             Cow::Borrowed arm by construction, rather than a \
9002             per-call-site `Cow::Owned(strategy.to_string())` \
9003             allocation"
9004        );
9005        for cow in &via_iter {
9006            assert!(
9007                matches!(cow, std::borrow::Cow::Borrowed(_)),
9008                "every element of the \
9009                 .iter().copied().map(Cow::from) pipe over \
9010                 RestartStrategy::ALL must land on the zero-alloc \
9011                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9012                 signals the pipe's iteration axis has silently \
9013                 allocated where the substrate-primitive \
9014                 RestartStrategy::as_str `&'static str` return makes \
9015                 the borrowed arm the type-correct projection"
9016            );
9017        }
9018    }
9019
9020    #[test]
9021    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9022        // Fail-before-pass-after byte-parity pin on the newly lifted
9023        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9024        // asserts the borrowed-input standard-library trait impl and
9025        // the substrate-primitive [`super::RestartStrategy::as_str`]
9026        // `pub const fn` accessor resolve to the same four-arm emit-
9027        // set across every arm the exhaustive
9028        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9029        // standard library does not carry a blanket
9030        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9031        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9032        // the borrowed-input `Cow<'static, str>` forward-projection
9033        // axis is a distinct trait-idiomatic surface that a
9034        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9035        // call site or a
9036        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9037        // reaches through this impl and no other — the paired owned-
9038        // input `From<RestartStrategy> for Cow<'static, str>` impl
9039        // (7dd28b3) forces every borrowed-input call site through an
9040        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9041        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9042        // bounds have no compile-time link back to the substrate
9043        // primitive.
9044        //
9045        // Also asserts the projection lands on the zero-alloc
9046        // [`std::borrow::Cow::Borrowed`] arm (not the
9047        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9048        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9049        // return lifetime by construction makes the borrowed arm the
9050        // type-correct projection with no runtime allocation on the
9051        // borrowed-input surface just as on the paired owned-input
9052        // surface.
9053        //
9054        // Second peer on the substrate-wide trait-idiomatic
9055        // [`std::borrow::Cow<'static, str>`] forward-projection family
9056        // on this enum — closes the `{Self, &Self}` input-shape
9057        // corner of the [`Cow<'static, str>`] axis on the first M2
9058        // OTP-shape closed-set fieldless typed enum peer on the caixa
9059        // surface (`:supervisor :estrategia`), exactly as d45c409
9060        // closed it on the top-level [`super::CaixaKind`] one commit
9061        // after the owning half (99c1735) landed. Every future
9062        // closed-set fieldless typed enum peer on the substrate is a
9063        // future target of the campaign.
9064        for &variant in RestartStrategy::ALL {
9065            let via_trait: std::borrow::Cow<'static, str> =
9066                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9067            let via_method: &'static str = variant.as_str();
9068            assert_eq!(
9069                via_trait.as_ref(),
9070                via_method,
9071                "From<&RestartStrategy> for Cow<'static, str> impl must \
9072                 round-trip &RestartStrategy::{variant:?} to the same \
9073                 lifted SUPERVISOR_ESTRATEGIA_* const \
9074                 RestartStrategy::as_str returns — divergence signals a \
9075                 silent detour off the substrate-primitive accessor"
9076            );
9077            assert!(
9078                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9079                "From<&RestartStrategy> for Cow<'static, str> impl must \
9080                 land on the zero-alloc Cow::Borrowed arm on \
9081                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9082                 signals the projection has silently allocated where \
9083                 the substrate-primitive RestartStrategy::as_str \
9084                 `&'static str` return makes the borrowed arm the \
9085                 type-correct projection"
9086            );
9087            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9088            assert_eq!(
9089                via_into.as_ref(),
9090                via_method,
9091                "Into<Cow<'static, str>>::into on \
9092                 &RestartStrategy::{variant:?} must byte-equal \
9093                 RestartStrategy::as_str on the same input — the \
9094                 blanket-derived Into shape must resolve to the same \
9095                 as_str dispatch as the explicit From impl"
9096            );
9097            assert!(
9098                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9099                "Into<Cow<'static, str>>::into on \
9100                 &RestartStrategy::{variant:?} must land on the \
9101                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9102                 Into shape must resolve to the same Cow::Borrowed \
9103                 dispatch as the explicit From impl"
9104            );
9105        }
9106    }
9107
9108    #[test]
9109    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9110        // Cross-axis partition pin: the newly lifted trait-idiomatic
9111        // borrowed-input `From<&RestartStrategy> for
9112        // std::borrow::Cow<'static, str>` (this lift), the paired
9113        // owned-input `From<RestartStrategy> for
9114        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9115        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9116        // for &'static str`, and the paired borrowed-input owned-
9117        // `String` `From<&RestartStrategy> for String` must resolve
9118        // identically on every arm, locking the four
9119        // return-shape × input-shape paths together by construction so
9120        // any future detour trips at caixa-core test time. Also byte-
9121        // parity witness against the sibling [`ToString::to_string`]
9122        // surface routed through [`std::fmt::Display`] — every owned-
9123        // heap-string path (this axis's `.into_owned()` promotion, the
9124        // paired [`From<&RestartStrategy> for String`], and
9125        // `.to_string()`) resolves to the same lifted
9126        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9127        //
9128        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9129        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9130        // `&RestartStrategy` by construction, so the borrowed-input
9131        // [`Cow<'static, str>`] axis is what routes the pipe through
9132        // the substrate-primitive [`super::RestartStrategy::as_str`]
9133        // accessor without a spurious [`Copy`] deref (which would only
9134        // be reachable through the owned-input
9135        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9136        // first calling `.copied()` on the iterator). The pipe witness
9137        // also pins the zero-alloc discipline: every element in the
9138        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9139        // arm predicate, so a future accidental silent-allocation
9140        // regression on the pipe's iteration axis is a caixa-core-
9141        // test-time failure.
9142        for &strategy in RestartStrategy::ALL {
9143            let borrowed_cow: std::borrow::Cow<'static, str> =
9144                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9145            let owned_cow: std::borrow::Cow<'static, str> =
9146                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9147            let borrowed_static: &'static str =
9148                <&'static str as From<&RestartStrategy>>::from(&strategy);
9149            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9150            assert_eq!(
9151                borrowed_cow, owned_cow,
9152                "From<&RestartStrategy> for Cow<'static, str> and \
9153                 From<RestartStrategy> for Cow<'static, str> must \
9154                 resolve identically on RestartStrategy::{strategy:?} — \
9155                 divergence signals the borrowed-input and owned-input \
9156                 Cow<'static, str> forward-projection input-shape \
9157                 paths have drifted onto different emit-sets"
9158            );
9159            assert_eq!(
9160                borrowed_cow.as_ref(),
9161                borrowed_static,
9162                "From<&RestartStrategy> for Cow<'static, str> and \
9163                 From<&RestartStrategy> for &'static str must resolve \
9164                 identically on RestartStrategy::{strategy:?} — \
9165                 divergence signals the borrowed-input Cow<'static, \
9166                 str> and &'static str return-shape paths have drifted \
9167                 onto different emit-sets"
9168            );
9169            assert_eq!(
9170                borrowed_cow.as_ref(),
9171                borrowed_string.as_str(),
9172                "From<&RestartStrategy> for Cow<'static, str> and \
9173                 From<&RestartStrategy> for String must resolve \
9174                 identically on RestartStrategy::{strategy:?} — \
9175                 divergence signals the borrowed-input Cow<'static, \
9176                 str> and owned-`String` return-shape paths have \
9177                 drifted onto different emit-sets"
9178            );
9179            let via_to_string: String = strategy.to_string();
9180            assert_eq!(
9181                borrowed_cow.as_ref(),
9182                via_to_string.as_str(),
9183                "From<&RestartStrategy> for Cow<'static, str> must \
9184                 byte-equal RestartStrategy::to_string on \
9185                 RestartStrategy::{strategy:?} — divergence signals \
9186                 the trait-idiomatic borrowed-input Cow<'static, str> \
9187                 forward-projection axis and the ToString-through-\
9188                 Display axis have drifted onto different emit-sets"
9189            );
9190        }
9191        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9192            .iter()
9193            .map(std::borrow::Cow::from)
9194            .collect();
9195        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9196            .iter()
9197            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9198            .collect();
9199        assert_eq!(
9200            via_iter, via_method,
9201            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9202             call site whose iteration axis holds `&RestartStrategy` \
9203             by construction — must byte-equal `.iter().map(|s| \
9204             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9205             input Cow<'static, str> `From<&RestartStrategy> for \
9206             Cow<'static, str>` axis is what makes the `Cow::from` \
9207             composition route through the substrate-primitive \
9208             `RestartStrategy::as_str` accessor with the zero-alloc \
9209             Cow::Borrowed arm by construction and without a spurious \
9210             `Copy` deref (which would only be reachable through the \
9211             owned-input `From<RestartStrategy> for Cow<'static, str>` \
9212             axis by first calling `.copied()` on the iterator)"
9213        );
9214        for cow in &via_iter {
9215            assert!(
9216                matches!(cow, std::borrow::Cow::Borrowed(_)),
9217                "every element of the .iter().map(Cow::from) pipe \
9218                 over RestartStrategy::ALL must land on the zero-\
9219                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9220                 any arm signals the pipe's iteration axis has \
9221                 silently allocated where the substrate-primitive \
9222                 RestartStrategy::as_str `&'static str` return makes \
9223                 the borrowed arm the type-correct projection"
9224            );
9225        }
9226    }
9227
9228    #[test]
9229    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9230        // Fail-before-pass-after byte-parity pin on the newly lifted
9231        // `impl From<RestartStrategy> for Box<str>` — asserts the
9232        // owned-input standard-library trait impl and the
9233        // substrate-primitive [`super::RestartStrategy::as_str`]
9234        // `pub const fn` accessor resolve to the same four-arm emit-
9235        // set across every arm the exhaustive
9236        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9237        // substrate-wide `Box<str>` forward-projection campaign tier
9238        // on the first M2 OTP-shape closed-set fieldless typed enum
9239        // peer on the caixa surface (`:supervisor :estrategia`),
9240        // immediately after the paired `Cow<'static, str>` axis
9241        // (7dd28b3 / ee577fd) closed the
9242        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9243        // 2×3 corner on this enum. Rust's standard library carries
9244        // `impl From<&str> for Box<str>` and
9245        // `impl From<String> for Box<str>` but no blanket
9246        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9247        // a distinct trait-idiomatic surface that a
9248        // `let key: Box<str> = strategy.into();`-shaped call site
9249        // reaches through this impl and no other — a paired
9250        // `Box::from(strategy.as_str())` open-code has no compile-
9251        // time link back to the substrate primitive.
9252        for &variant in RestartStrategy::ALL {
9253            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9254            let via_method: &'static str = variant.as_str();
9255            assert_eq!(
9256                via_trait.as_ref(),
9257                via_method,
9258                "From<RestartStrategy> for Box<str> impl must round-\
9259                 trip RestartStrategy::{variant:?} to the same lifted \
9260                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9261                 returns — divergence signals a silent detour off the \
9262                 substrate-primitive accessor"
9263            );
9264            let via_into: Box<str> = variant.into();
9265            assert_eq!(
9266                via_into.as_ref(),
9267                via_method,
9268                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9269                 must byte-equal RestartStrategy::as_str on the same \
9270                 input — the blanket-derived Into shape must resolve \
9271                 to the same as_str dispatch as the explicit From impl"
9272            );
9273        }
9274    }
9275
9276    #[test]
9277    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9278        // Fail-before-pass-after byte-parity pin on the newly lifted
9279        // `impl From<&RestartStrategy> for Box<str>` — asserts the
9280        // borrowed-input standard-library trait impl and the
9281        // substrate-primitive [`super::RestartStrategy::as_str`]
9282        // `pub const fn` accessor resolve to the same four-arm emit-
9283        // set across every arm the exhaustive
9284        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9285        // standard library does not carry a blanket
9286        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9287        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9288        // so the borrowed-input `Box<str>` forward-projection axis
9289        // is a distinct trait-idiomatic surface that a
9290        // `let key: Box<str> = (&strategy).into();`-shaped call site
9291        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9292        // shaped pipe reaches through this impl and no other — the
9293        // paired owned-input `From<RestartStrategy> for Box<str>`
9294        // impl (69ef45c) forces every borrowed-input call site
9295        // through an explicit `Copy` deref
9296        // (`Box::<str>::from((*strategy).as_str())`) or a
9297        // `Box::<str>::from(strategy.as_str())` open-code whose
9298        // type bounds have no compile-time link back to the
9299        // substrate primitive.
9300        //
9301        // Second peer on the substrate-wide trait-idiomatic
9302        // [`Box<str>`] forward-projection family on this enum —
9303        // closes the `{Self, &Self}` input-shape corner of the
9304        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9305        // fieldless typed enum peer on the caixa surface
9306        // (`:supervisor :estrategia`), exactly as ee577fd closed
9307        // the paired [`Cow<'static, str>`] axis one commit after
9308        // its owning half (7dd28b3) landed. Every future closed-
9309        // set fieldless typed enum peer on the substrate is a
9310        // future target of the campaign.
9311        //
9312        // Also byte-parity witness against the paired owned-input
9313        // [`From<RestartStrategy> for Box<str>`] and the sibling
9314        // borrowed-input [`From<&RestartStrategy> for &'static str`],
9315        // [`From<&RestartStrategy> for String`], and
9316        // [`From<&RestartStrategy> for Cow<'static, str>`]
9317        // return-shape axes — locking the four
9318        // return-shape × input-shape paths together by construction
9319        // so any future detour trips at caixa-core test time. Then a
9320        // `.iter().map(Box::<str>::from)` pipe witness over
9321        // [`super::RestartStrategy::ALL`] — whose iterator yields
9322        // `&RestartStrategy` by construction, so the borrowed-input
9323        // [`Box<str>`] axis is what routes the pipe through the
9324        // substrate-primitive [`super::RestartStrategy::as_str`]
9325        // accessor without a spurious [`Copy`] deref (which would
9326        // only be reachable through the owned-input
9327        // [`From<RestartStrategy> for Box<str>`] axis by first
9328        // calling `.copied()` on the iterator).
9329        for &variant in RestartStrategy::ALL {
9330            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9331            let via_method: &'static str = variant.as_str();
9332            assert_eq!(
9333                via_trait.as_ref(),
9334                via_method,
9335                "From<&RestartStrategy> for Box<str> impl must \
9336                 round-trip &RestartStrategy::{variant:?} to the same \
9337                 lifted SUPERVISOR_ESTRATEGIA_* const \
9338                 RestartStrategy::as_str returns — divergence signals \
9339                 a silent detour off the substrate-primitive accessor"
9340            );
9341            let via_into: Box<str> = (&variant).into();
9342            assert_eq!(
9343                via_into.as_ref(),
9344                via_method,
9345                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9346                 must byte-equal RestartStrategy::as_str on the same \
9347                 input — the blanket-derived Into shape must resolve \
9348                 to the same as_str dispatch as the explicit From impl"
9349            );
9350            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9351            assert_eq!(
9352                via_trait, owned_box,
9353                "From<&RestartStrategy> for Box<str> and \
9354                 From<RestartStrategy> for Box<str> must resolve \
9355                 identically on RestartStrategy::{variant:?} — \
9356                 divergence signals the borrowed-input and owned-input \
9357                 Box<str> forward-projection input-shape paths have \
9358                 drifted onto different emit-sets"
9359            );
9360            let borrowed_static: &'static str =
9361                <&'static str as From<&RestartStrategy>>::from(&variant);
9362            assert_eq!(
9363                via_trait.as_ref(),
9364                borrowed_static,
9365                "From<&RestartStrategy> for Box<str> and \
9366                 From<&RestartStrategy> for &'static str must resolve \
9367                 identically on RestartStrategy::{variant:?} — \
9368                 divergence signals the borrowed-input Box<str> and \
9369                 &'static str return-shape paths have drifted onto \
9370                 different emit-sets"
9371            );
9372            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9373            assert_eq!(
9374                via_trait.as_ref(),
9375                borrowed_string.as_str(),
9376                "From<&RestartStrategy> for Box<str> and \
9377                 From<&RestartStrategy> for String must resolve \
9378                 identically on RestartStrategy::{variant:?} — \
9379                 divergence signals the borrowed-input Box<str> and \
9380                 owned-`String` return-shape paths have drifted onto \
9381                 different emit-sets"
9382            );
9383            let borrowed_cow: std::borrow::Cow<'static, str> =
9384                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9385            assert_eq!(
9386                via_trait.as_ref(),
9387                borrowed_cow.as_ref(),
9388                "From<&RestartStrategy> for Box<str> and \
9389                 From<&RestartStrategy> for Cow<'static, str> must \
9390                 resolve identically on RestartStrategy::{variant:?} — \
9391                 divergence signals the borrowed-input Box<str> and \
9392                 Cow<'static, str> return-shape paths have drifted \
9393                 onto different emit-sets"
9394            );
9395        }
9396        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9397        let via_method: Vec<Box<str>> = RestartStrategy::ALL
9398            .iter()
9399            .map(|s| Box::<str>::from(s.as_str()))
9400            .collect();
9401        assert_eq!(
9402            via_iter, via_method,
9403            "`.iter().map(Box::<str>::from)` over \
9404             RestartStrategy::ALL — a call site whose iteration axis \
9405             holds `&RestartStrategy` by construction — must byte-\
9406             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9407             on every arm — the borrowed-input Box<str> \
9408             `From<&RestartStrategy> for Box<str>` axis is what \
9409             makes the `Box::<str>::from` composition route through \
9410             the substrate-primitive `RestartStrategy::as_str` \
9411             accessor without a spurious `Copy` deref (which would \
9412             only be reachable through the owned-input \
9413             `From<RestartStrategy> for Box<str>` axis by first \
9414             calling `.copied()` on the iterator)"
9415        );
9416    }
9417
9418    #[test]
9419    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9420        // Fail-before-pass-after byte-parity pin on the newly lifted
9421        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9422        // the owned-input standard-library trait impl and the
9423        // substrate-primitive [`super::RestartStrategy::as_str`]
9424        // `pub const fn` accessor resolve to the same four-arm emit-
9425        // set across every arm the exhaustive
9426        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9427        // substrate-wide [`std::sync::Arc<str>`] forward-projection
9428        // campaign tier on the first M2 OTP-shape closed-set fieldless
9429        // typed enum peer on the caixa surface
9430        // (`:supervisor :estrategia`), immediately after the paired
9431        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9432        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9433        // Box<str>}` 2×4 corner on this enum. Rust's standard library
9434        // carries `impl From<&str> for std::sync::Arc<str>` and
9435        // `impl From<String> for std::sync::Arc<str>` but no blanket
9436        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9437        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9438        // so this axis is a distinct trait-idiomatic surface that a
9439        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9440        // site reaches through this impl and no other — a paired
9441        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9442        // has no compile-time link back to the substrate primitive,
9443        // and a two-step `std::sync::Arc::<str>::from(String::from(
9444        // strategy))` composition through the owned-`String` axis
9445        // allocates twice (once into the intermediate `String`, once
9446        // into the [`Arc<str>`] on the `From<String>` conversion)
9447        // where the single-step trait impl allocates once.
9448        //
9449        // Cross-axis byte-parity witness against the sibling owned-
9450        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9451        // return-shape axes — locking the five return-shape paths on
9452        // the owned-input surface together by construction so any
9453        // future detour off the substrate-primitive
9454        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9455        // core test time.
9456        for &variant in RestartStrategy::ALL {
9457            let via_trait: std::sync::Arc<str> =
9458                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9459            let via_method: &'static str = variant.as_str();
9460            assert_eq!(
9461                via_trait.as_ref(),
9462                via_method,
9463                "From<RestartStrategy> for std::sync::Arc<str> impl \
9464                 must round-trip RestartStrategy::{variant:?} to the \
9465                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9466                 RestartStrategy::as_str returns — divergence signals \
9467                 a silent detour off the substrate-primitive accessor"
9468            );
9469            let via_into: std::sync::Arc<str> = variant.into();
9470            assert_eq!(
9471                via_into.as_ref(),
9472                via_method,
9473                "Into<std::sync::Arc<str>>::into on \
9474                 RestartStrategy::{variant:?} must byte-equal \
9475                 RestartStrategy::as_str on the same input — the \
9476                 blanket-derived Into shape must resolve to the same \
9477                 as_str dispatch as the explicit From impl"
9478            );
9479            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9480            assert_eq!(
9481                via_trait.as_ref(),
9482                owned_static,
9483                "From<RestartStrategy> for std::sync::Arc<str> and \
9484                 From<RestartStrategy> for &'static str must resolve \
9485                 identically on RestartStrategy::{variant:?} — \
9486                 divergence signals the owned-input std::sync::Arc<str> \
9487                 and &'static str return-shape paths have drifted onto \
9488                 different emit-sets"
9489            );
9490            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9491            assert_eq!(
9492                via_trait.as_ref(),
9493                owned_string.as_str(),
9494                "From<RestartStrategy> for std::sync::Arc<str> and \
9495                 From<RestartStrategy> for String must resolve \
9496                 identically on RestartStrategy::{variant:?} — \
9497                 divergence signals the owned-input std::sync::Arc<str> \
9498                 and owned-`String` return-shape paths have drifted \
9499                 onto different emit-sets"
9500            );
9501            let owned_cow: std::borrow::Cow<'static, str> =
9502                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9503            assert_eq!(
9504                via_trait.as_ref(),
9505                owned_cow.as_ref(),
9506                "From<RestartStrategy> for std::sync::Arc<str> and \
9507                 From<RestartStrategy> for Cow<'static, str> must \
9508                 resolve identically on RestartStrategy::{variant:?} — \
9509                 divergence signals the owned-input std::sync::Arc<str> \
9510                 and Cow<'static, str> return-shape paths have drifted \
9511                 onto different emit-sets"
9512            );
9513            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9514            assert_eq!(
9515                via_trait.as_ref(),
9516                owned_box.as_ref(),
9517                "From<RestartStrategy> for std::sync::Arc<str> and \
9518                 From<RestartStrategy> for Box<str> must resolve \
9519                 identically on RestartStrategy::{variant:?} — \
9520                 divergence signals the owned-input std::sync::Arc<str> \
9521                 and Box<str> return-shape paths have drifted onto \
9522                 different emit-sets"
9523            );
9524        }
9525    }
9526
9527    #[test]
9528    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
9529        // Fail-before-pass-after byte-parity pin on the newly lifted
9530        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
9531        // asserts the borrowed-input standard-library trait impl and
9532        // the substrate-primitive [`super::RestartStrategy::as_str`]
9533        // `pub const fn` accessor resolve to the same four-arm emit-
9534        // set across every arm the exhaustive
9535        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9536        // standard library does not carry a blanket
9537        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
9538        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9539        // so the borrowed-input [`std::sync::Arc<str>`] forward-
9540        // projection axis is a distinct trait-idiomatic surface that a
9541        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
9542        // call site or a
9543        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
9544        // shaped pipe reaches through this impl and no other — the
9545        // paired owned-input
9546        // `From<RestartStrategy> for std::sync::Arc<str>` impl
9547        // (bca2ec8) forces every borrowed-input call site through an
9548        // explicit `Copy` deref
9549        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
9550        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9551        // whose type bounds have no compile-time link back to the
9552        // substrate primitive.
9553        //
9554        // Second peer on the substrate-wide trait-idiomatic
9555        // [`std::sync::Arc<str>`] forward-projection family on this
9556        // enum — closes the `{Self, &Self}` input-shape corner of
9557        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
9558        // closed-set fieldless typed enum peer on the caixa surface
9559        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
9560        // paired [`Box<str>`] axis one commit after its owning half
9561        // (69ef45c) landed. Every future closed-set fieldless typed
9562        // enum peer on the substrate is a future target of the
9563        // campaign.
9564        //
9565        // Also byte-parity witness against the paired owned-input
9566        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
9567        // sibling borrowed-input
9568        // [`From<&RestartStrategy> for &'static str`],
9569        // [`From<&RestartStrategy> for String`],
9570        // [`From<&RestartStrategy> for Cow<'static, str>`], and
9571        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
9572        // locking the five return-shape × input-shape paths together
9573        // by construction so any future detour trips at caixa-core
9574        // test time. Then a
9575        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
9576        // [`super::RestartStrategy::ALL`] — whose iterator yields
9577        // `&RestartStrategy` by construction, so the borrowed-input
9578        // [`std::sync::Arc<str>`] axis is what routes the pipe
9579        // through the substrate-primitive
9580        // [`super::RestartStrategy::as_str`] accessor without a
9581        // spurious [`Copy`] deref (which would only be reachable
9582        // through the owned-input
9583        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
9584        // first calling `.copied()` on the iterator).
9585        for &variant in RestartStrategy::ALL {
9586            let via_trait: std::sync::Arc<str> =
9587                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
9588            let via_method: &'static str = variant.as_str();
9589            assert_eq!(
9590                via_trait.as_ref(),
9591                via_method,
9592                "From<&RestartStrategy> for std::sync::Arc<str> impl \
9593                 must round-trip &RestartStrategy::{variant:?} to the \
9594                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9595                 RestartStrategy::as_str returns — divergence signals \
9596                 a silent detour off the substrate-primitive accessor"
9597            );
9598            let via_into: std::sync::Arc<str> = (&variant).into();
9599            assert_eq!(
9600                via_into.as_ref(),
9601                via_method,
9602                "Into<std::sync::Arc<str>>::into on \
9603                 &RestartStrategy::{variant:?} must byte-equal \
9604                 RestartStrategy::as_str on the same input — the \
9605                 blanket-derived Into shape must resolve to the same \
9606                 as_str dispatch as the explicit From impl"
9607            );
9608            let owned_arc: std::sync::Arc<str> =
9609                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9610            assert_eq!(
9611                via_trait, owned_arc,
9612                "From<&RestartStrategy> for std::sync::Arc<str> and \
9613                 From<RestartStrategy> for std::sync::Arc<str> must \
9614                 resolve identically on RestartStrategy::{variant:?} — \
9615                 divergence signals the borrowed-input and owned-input \
9616                 std::sync::Arc<str> forward-projection input-shape \
9617                 paths have drifted onto different emit-sets"
9618            );
9619            let borrowed_static: &'static str =
9620                <&'static str as From<&RestartStrategy>>::from(&variant);
9621            assert_eq!(
9622                via_trait.as_ref(),
9623                borrowed_static,
9624                "From<&RestartStrategy> for std::sync::Arc<str> and \
9625                 From<&RestartStrategy> for &'static str must resolve \
9626                 identically on RestartStrategy::{variant:?} — \
9627                 divergence signals the borrowed-input \
9628                 std::sync::Arc<str> and &'static str return-shape \
9629                 paths have drifted onto different emit-sets"
9630            );
9631            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9632            assert_eq!(
9633                via_trait.as_ref(),
9634                borrowed_string.as_str(),
9635                "From<&RestartStrategy> for std::sync::Arc<str> and \
9636                 From<&RestartStrategy> for String must resolve \
9637                 identically on RestartStrategy::{variant:?} — \
9638                 divergence signals the borrowed-input \
9639                 std::sync::Arc<str> and owned-`String` return-shape \
9640                 paths have drifted onto different emit-sets"
9641            );
9642            let borrowed_cow: std::borrow::Cow<'static, str> =
9643                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9644            assert_eq!(
9645                via_trait.as_ref(),
9646                borrowed_cow.as_ref(),
9647                "From<&RestartStrategy> for std::sync::Arc<str> and \
9648                 From<&RestartStrategy> for Cow<'static, str> must \
9649                 resolve identically on RestartStrategy::{variant:?} — \
9650                 divergence signals the borrowed-input \
9651                 std::sync::Arc<str> and Cow<'static, str> return-shape \
9652                 paths have drifted onto different emit-sets"
9653            );
9654            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9655            assert_eq!(
9656                via_trait.as_ref(),
9657                borrowed_box.as_ref(),
9658                "From<&RestartStrategy> for std::sync::Arc<str> and \
9659                 From<&RestartStrategy> for Box<str> must resolve \
9660                 identically on RestartStrategy::{variant:?} — \
9661                 divergence signals the borrowed-input \
9662                 std::sync::Arc<str> and Box<str> return-shape paths \
9663                 have drifted onto different emit-sets"
9664            );
9665        }
9666        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9667            .iter()
9668            .map(std::sync::Arc::<str>::from)
9669            .collect();
9670        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9671            .iter()
9672            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
9673            .collect();
9674        assert_eq!(
9675            via_iter, via_method,
9676            "`.iter().map(std::sync::Arc::<str>::from)` over \
9677             RestartStrategy::ALL — a call site whose iteration axis \
9678             holds `&RestartStrategy` by construction — must byte-\
9679             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
9680             on every arm — the borrowed-input std::sync::Arc<str> \
9681             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
9682             what makes the `std::sync::Arc::<str>::from` composition \
9683             route through the substrate-primitive \
9684             `RestartStrategy::as_str` accessor without a spurious \
9685             `Copy` deref (which would only be reachable through the \
9686             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
9687             axis by first calling `.copied()` on the iterator)"
9688        );
9689    }
9690
9691    #[test]
9692    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9693        // Fail-before-pass-after byte-parity pin on the newly lifted
9694        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9695        // library trait impl and the substrate-primitive
9696        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9697        // the same three-arm accept-set across every arm the exhaustive
9698        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9699        // detour that routes the trait impl through a divergent
9700        // projection (a per-arm inline `match s { "Permanent" =>
9701        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9702        // link to the un-lifted arm-literal, a hypothetical
9703        // `#[serde(rename_all = "…")]` attribute drift that silently
9704        // splits the wire byte-string from every consumer that reaches
9705        // for this typed dispatch, an accidental swap onto the kebab-case
9706        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9707        // impl parses through and which would collide the two-axis
9708        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9709        // doc block makes load-bearing) trips at caixa-core test time
9710        // under `assert_eq!` rather than at a downstream
9711        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9712        // every one of the three arms [`RestartPolicy::ALL`] carries so
9713        // no arm's projection is covered only by the sibling method-
9714        // named `from_wire` path. Peer of the sibling
9715        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9716        // (5b828ed) — extends the trait-idiomatic reverse-projection
9717        // axis onto the third and final M2-OTP-shape closed-set typed
9718        // enum on the caixa surface (the paired per-child restart-
9719        // decision-policy sibling on the same M2 `:supervisor` slot).
9720        for &variant in RestartPolicy::ALL {
9721            let wire = variant.as_str();
9722            assert_eq!(
9723                <RestartPolicy as TryFrom<&str>>::try_from(wire),
9724                Ok(variant),
9725                "TryFrom<&str> impl on RestartPolicy must round-trip \
9726                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9727                 Ok(RestartPolicy::{variant:?}) — divergence from \
9728                 RestartPolicy::from_wire signals a silent detour off \
9729                 the substrate-primitive accessor"
9730            );
9731            assert_eq!(
9732                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9733                RestartPolicy::from_wire(wire),
9734                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9735                 equal RestartPolicy::from_wire on the same input"
9736            );
9737        }
9738    }
9739
9740    #[test]
9741    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9742        // Rejection witness on the `impl TryFrom<&str> for
9743        // RestartPolicy` — sweeps a candidate set of byte-strings
9744        // outside the three-arm PascalCase wire accept-set the sibling
9745        // [`RestartPolicy::as_str`] emits and asserts every one lands on
9746        // `Err(())`, so a future accidental widening of the trait impl's
9747        // accept-set (a stray additional
9748        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9749        // path, a silent inclusion of the kebab-case dispatcher-catalog
9750        // byte-string the pre-existing [`std::str::FromStr`] impl the
9751        // [`gen_platform::FromStrKind`] derive installs parses onto the
9752        // wire axis — which would collide the two-axis
9753        // wire/dispatcher-catalog split the sibling
9754        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9755        // an English-rebrand or plural-arm silent alias that would widen
9756        // the wire accept-set past the OTP-canonical three) trips at
9757        // caixa-core test time. The candidate set includes the empty
9758        // string, whitespace-only padding, the kebab-case dispatcher-
9759        // catalog byte-strings on the sibling axis (a caller who
9760        // confuses the two axes trips here rather than at a downstream
9761        // consumer's silent reject), a lowercase / uppercase / mixed-case
9762        // fold of each PascalCase arm (a caller who assumes case-fold
9763        // acceptance trips here), leading/trailing whitespace padding,
9764        // the trailing-newline shape, quote-wrapped candidates, and a
9765        // residual set of plausible-but-wrong English rebrand
9766        // candidates. Peer of the sibling
9767        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9768        // (5b828ed) rejection witness.
9769        let rejected: &[&str] = &[
9770            "",
9771            " ",
9772            "\n",
9773            "\t",
9774            "permanent",
9775            "temporary",
9776            "transient",
9777            "PERMANENT",
9778            "TEMPORARY",
9779            "TRANSIENT",
9780            "Permanents",
9781            "Permanent ",
9782            " Permanent",
9783            " Temporary ",
9784            "Permanent\n",
9785            "Transient\t",
9786            "\"Permanent\"",
9787            "Ephemeral",
9788            "Always",
9789            "Never",
9790            "OnAbnormalExit",
9791            "intrinsic",
9792            "?",
9793        ];
9794        for &input in rejected {
9795            assert_eq!(
9796                <RestartPolicy as TryFrom<&str>>::try_from(input),
9797                Err(()),
9798                "TryFrom<&str> impl on RestartPolicy must reject the \
9799                 non-wire byte-string {input:?} — silent acceptance \
9800                 signals an accept-set widening off the paired \
9801                 RestartPolicy::from_wire resolver"
9802            );
9803        }
9804    }
9805
9806    #[test]
9807    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9808        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9809        // `from_wire` reverse projections must resolve identically on
9810        // *every* input, not just the ones [`RestartPolicy::ALL`]
9811        // enumerates. Sweeps a mixed candidate set spanning accepted
9812        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9813        // case dispatcher-catalog byte-strings, empty, whitespace-
9814        // padded, quoted, English-rebrand candidates) inputs and asserts
9815        // the trait's `Result::ok()` projection byte-equals the method-
9816        // named resolver's `Option<Self>` return-shape on each, locking
9817        // the two paths together by construction so any future detour
9818        // (a stray `try_from` special-case that widens or narrows the
9819        // accept-set outside the paired `from_wire` resolver, an
9820        // accidental swap onto the kebab-case [`std::str::FromStr`]
9821        // impl the [`gen_platform::FromStrKind`] derive installs on the
9822        // sibling dispatcher-catalog axis) trips at caixa-core test
9823        // time. Peer of the sibling
9824        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9825        // pin — extends the round-trip discipline onto the M2-OTP-shape
9826        // per-child restart-policy axis.
9827        let candidates: &[&str] = &[
9828            "Permanent",
9829            "Temporary",
9830            "Transient",
9831            "",
9832            "permanent",
9833            "temporary",
9834            "transient",
9835            "PERMANENT",
9836            "unknown",
9837            "Permanent ",
9838            " Permanent",
9839            "\"Permanent\"",
9840            "Ephemeral",
9841            "OnAbnormalExit",
9842            "?",
9843        ];
9844        for &input in candidates {
9845            let via_trait: Option<RestartPolicy> =
9846                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9847            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9848            assert_eq!(
9849                via_trait, via_method,
9850                "TryFrom<&str> and from_wire must resolve identically on \
9851                 input {input:?} — divergence signals the two reverse-\
9852                 projection paths have drifted onto different accept-sets"
9853            );
9854        }
9855    }
9856
9857    #[test]
9858    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9859        // Fail-before-pass-after byte-parity pin on the newly lifted
9860        // `impl From<RestartPolicy> for &'static str` — asserts the
9861        // standard-library trait impl and the substrate-primitive
9862        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9863        // the same three-arm emit-set across every arm the exhaustive
9864        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9865        // detour that routes the trait impl through a divergent
9866        // projection (a per-arm inline `match policy { Permanent =>
9867        // "Permanent", … }` re-inlining that opens a compile-time link
9868        // to the un-lifted arm-literal, an accidental swap onto the
9869        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9870        // axis that would collide the two-axis wire/catalog split the
9871        // sibling [`RestartPolicy::from_wire`] doc block makes
9872        // load-bearing) trips at caixa-core test time under
9873        // `assert_eq!` rather than at a downstream
9874        // `impl Into<&'static str>`-bound consumer's silent split.
9875        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9876        // carries so no arm's projection is covered only by the sibling
9877        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9878        // paths. Materializes the `<&'static str as
9879        // From<RestartPolicy>>::from` output in a `const`-shape binding
9880        // to make the `'static` lifetime promise a build-time invariant
9881        // — a future accidental downgrade of any of the three arms'
9882        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9883        // non-`&'static str` (a `String::leak()`-produced return, a
9884        // `Box::leak`-cast) trips at caixa-core build time rather than
9885        // at a downstream `'static`-bound consumer. Peer of the sibling
9886        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9887        // (523157d) — extends the trait-idiomatic forward-projection
9888        // axis onto the second (and second-of-two-in-M2) closed-set
9889        // typed enum on the caixa surface (the paired per-child
9890        // restart-decision-policy sibling on the same M2 `:supervisor`
9891        // slot).
9892        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9893        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9894        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9895        for &variant in RestartPolicy::ALL {
9896            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9897            let via_method: &'static str = variant.as_str();
9898            assert_eq!(
9899                via_trait, via_method,
9900                "From<RestartPolicy> for &'static str impl must round-trip \
9901                 RestartPolicy::{variant:?} to the same lifted \
9902                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9903                 divergence signals a silent detour off the substrate-primitive \
9904                 accessor"
9905            );
9906            let via_into: &'static str = variant.into();
9907            assert_eq!(
9908                via_into, via_method,
9909                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9910                 byte-equal RestartPolicy::as_str on the same input — the \
9911                 blanket-derived Into shape must resolve to the same as_str \
9912                 dispatch as the explicit From impl"
9913            );
9914        }
9915        assert_eq!(
9916            [PERMANENT, TEMPORARY, TRANSIENT],
9917            [
9918                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9919                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9920                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9921            ],
9922            "const-context RestartPolicy::as_str must resolve to the three \
9923             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9924             downgrade of any arm to a non-const or non-static byte-string \
9925             breaks the `&'static str`-lifetime promise the paired \
9926             From<RestartPolicy> for &'static str impl carries by \
9927             construction"
9928        );
9929    }
9930
9931    #[test]
9932    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9933        // Cross-axis partition pin: the paired trait-idiomatic
9934        // `From<RestartPolicy> for &'static str` forward projection and
9935        // the method-named [`RestartPolicy::as_str`] forward projection
9936        // must resolve identically on *every* arm, not just the ones
9937        // named in the primary byte-parity pin above. Sweeps every
9938        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9939        // output byte-equals the method-named accessor's return-value on
9940        // each, locking the two forward-projection paths together by
9941        // construction so any future detour (a stray `From` special-case
9942        // that lands on a divergent per-arm literal outside the paired
9943        // `as_str` dispatch, a hypothetical rebrand touching one axis
9944        // without the other) trips at caixa-core test time. Peer of the
9945        // sibling forward-projection partition pin
9946        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9947        // (523157d) — extends the round-trip discipline onto the
9948        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9949        // surface, closing the two-way `Self ↔ &'static str` round-trip
9950        // on the trait-idiomatic pair (`From<Self> for &'static str` +
9951        // `TryFrom<&str> for Self`) as well as the pre-existing method-
9952        // named pair (`as_str` + `from_wire`).
9953        for &variant in RestartPolicy::ALL {
9954            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9955            let via_method: &'static str = variant.as_str();
9956            assert_eq!(
9957                via_trait, via_method,
9958                "From<RestartPolicy> for &'static str and \
9959                 RestartPolicy::as_str must resolve identically on \
9960                 RestartPolicy::{variant:?} — divergence signals the \
9961                 two forward-projection paths have drifted onto different \
9962                 emit-sets"
9963            );
9964        }
9965        // Round-trip witness: every arm's forward `From` output re-parses
9966        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9967        // to the original variant. Closes the two-way `RestartPolicy ↔
9968        // &'static str` round-trip on the trait-idiomatic axis pair,
9969        // mirroring the pre-existing method-named `as_str` + `from_wire`
9970        // round-trip on the substrate-primitive axis pair.
9971        for &variant in RestartPolicy::ALL {
9972            let emitted: &'static str = variant.into();
9973            let re_parsed: Result<RestartPolicy, ()> =
9974                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9975            assert_eq!(
9976                re_parsed,
9977                Ok(variant),
9978                "trait-idiomatic axis pair must round-trip \
9979                 RestartPolicy::{variant:?} through `.into::<&'static \
9980                 str>()` and back through `TryFrom<&str>` — a break signals \
9981                 the forward-emit and reverse-parse axes have drifted onto \
9982                 different vocabularies"
9983            );
9984        }
9985    }
9986
9987    #[test]
9988    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9989        // Fail-before-pass-after byte-parity pin on the newly lifted
9990        // `impl From<&RestartPolicy> for &'static str` — asserts the
9991        // borrowed-input standard-library trait impl and the substrate-
9992        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9993        // resolve to the same three-arm emit-set across every arm the
9994        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9995        // `From` trait does not auto-derive the borrowed-input sibling
9996        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9997        // where T: Copy, U: From<T>` blanket in `core`), so the
9998        // borrowed-input axis is a distinct trait-idiomatic surface
9999        // that a `.iter().map(Into::into)` shape over
10000        // [`RestartPolicy::ALL`] (whose iterator yields
10001        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10002        // impl and no other — the paired owned-input
10003        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10004        // / dereference before the trait fires. Materializes the
10005        // `<&'static str as From<&RestartPolicy>>::from` output in a
10006        // `const`-shape binding to make the `'static` lifetime promise
10007        // a build-time invariant.
10008        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10009        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10010        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10011        for variant in RestartPolicy::ALL {
10012            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10013            let via_method: &'static str = variant.as_str();
10014            assert_eq!(
10015                via_trait, via_method,
10016                "From<&RestartPolicy> for &'static str impl must round-trip \
10017                 &RestartPolicy::{variant:?} to the same lifted \
10018                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10019                 returns — divergence signals a silent detour off the \
10020                 substrate-primitive accessor"
10021            );
10022            let via_into: &'static str = variant.into();
10023            assert_eq!(
10024                via_into, via_method,
10025                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10026                 must byte-equal RestartPolicy::as_str on the same input — \
10027                 the blanket-derived Into shape must resolve to the same \
10028                 as_str dispatch as the explicit From impl"
10029            );
10030        }
10031        assert_eq!(
10032            [PERMANENT, TEMPORARY, TRANSIENT],
10033            [
10034                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10035                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10036                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10037            ],
10038            "const-context RestartPolicy::as_str must resolve to the three \
10039             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10040             From<&RestartPolicy> for &'static str impl inherits its \
10041             `'static` lifetime promise from the same accessor the \
10042             owned-input sibling routes through"
10043        );
10044    }
10045
10046    #[test]
10047    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10048        // Cross-axis partition pin: the paired trait-idiomatic
10049        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10050        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10051        // &'static str` (this lift) forward projections must resolve
10052        // identically on every arm, locking the two input-shape paths
10053        // together so any future detour trips at caixa-core test time.
10054        // Then a witness that a `.iter().map(Into::into)` pipe over
10055        // [`RestartPolicy::ALL`] (whose iterator yields
10056        // `&RestartPolicy`) materializes the three-arm accept-set
10057        // through the borrowed-input axis alone — the exact shape a
10058        // future wasm-operator per-child post-exit restart-decision
10059        // diagnostic line, a future substrate-wide per-arm diagnostic
10060        // column, or a
10061        // `HashMap::<&'static str, RestartPolicy>::from_iter(
10062        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10063        // per-policy lookup reaches through — closing the two-way
10064        // owned/borrowed input-shape symmetry on the forward-projection
10065        // trait-idiomatic axis. Peer of the sibling
10066        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10067        // (64aa742) /
10068        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10069        // (5ab993a) /
10070        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10071        // (807b0b5) /
10072        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10073        // (e941836) partition pins on the sibling closed-set typed-enum
10074        // discriminator axes — extends the borrowed-input axis
10075        // discipline onto the second-of-two M2 OTP-shape closed-set
10076        // typed enum on the caixa surface (per-child restart-decision
10077        // policy). Also closes the direct two-way `&Self → &'static
10078        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10079        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10080        // forward `From` emits lowercase Portuguese diagnostic bytes
10081        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10082        // forcing the round-trip through an intermediate wire-vocab
10083        // hop), the [`RestartPolicy::as_str`] emit and
10084        // [`RestartPolicy::from_wire`] parse share the same
10085        // `PascalCase` vocabulary by construction, so the borrowed-
10086        // input forward axis and the reverse axis compose directly.
10087        for &variant in RestartPolicy::ALL {
10088            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10089            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10090            assert_eq!(
10091                owned, borrowed,
10092                "From<RestartPolicy> and From<&RestartPolicy> for \
10093                 &'static str must resolve identically on \
10094                 RestartPolicy::{variant:?} — divergence signals the \
10095                 owned-input and borrowed-input forward-projection paths \
10096                 have drifted onto different emit-sets"
10097            );
10098        }
10099        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10100        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10101        assert_eq!(
10102            via_iter, via_method,
10103            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10104             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10105             borrowed-input `From<&RestartPolicy> for &'static str` axis \
10106             is what makes the `.iter().map(Into::into)` shape route \
10107             through the substrate-primitive `RestartPolicy::as_str` \
10108             accessor rather than through a per-call-site `.copied()` / \
10109             dereference detour"
10110        );
10111        for variant in RestartPolicy::ALL {
10112            let emitted: &'static str = variant.into();
10113            let re_parsed: Result<RestartPolicy, ()> =
10114                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10115            assert_eq!(
10116                re_parsed,
10117                Ok(*variant),
10118                "trait-idiomatic borrowed-input forward-projection + \
10119                 reverse-projection axis pair must round-trip \
10120                 &RestartPolicy::{variant:?} through `.into::<&'static \
10121                 str>()` (via the borrowed-input axis) and back through \
10122                 `TryFrom<&str>` — a break signals the borrowed-input \
10123                 forward-emit and reverse-parse axes have drifted onto \
10124                 different vocabularies"
10125            );
10126        }
10127    }
10128
10129    #[test]
10130    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10131        // Fail-before-pass-after byte-parity pin on the newly lifted
10132        // `impl From<RestartPolicy> for String` — asserts the
10133        // owned-`String`-returning standard-library trait impl and the
10134        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10135        // accessor resolve to the same three-arm emit-set across every
10136        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10137        // Rust's standard library does not carry a blanket
10138        // `impl<T: AsRef<str>> From<T> for String` (nor an
10139        // `impl<T: fmt::Display> From<T> for String`), so the
10140        // owned-`String` forward-projection axis is a distinct
10141        // trait-idiomatic surface that a `let key: String =
10142        // policy.into();`-shaped call site reaches through this impl
10143        // and no other — the paired sibling `From<RestartPolicy> for
10144        // &'static str` impl forces every owned-`String` call site
10145        // through an explicit `.to_owned()` / `String::from`
10146        // restatement. Peer of the first-mover
10147        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10148        // (7baa18a) — extends the trait-idiomatic owned-`String`
10149        // forward-projection axis onto the second-of-two M2 OTP-shape
10150        // closed-set typed enums on the caixa surface (per-child
10151        // restart-decision-policy sibling on the same M2 `:supervisor`
10152        // slot).
10153        for &variant in RestartPolicy::ALL {
10154            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10155            let via_method: &'static str = variant.as_str();
10156            assert_eq!(
10157                via_trait.as_str(),
10158                via_method,
10159                "From<RestartPolicy> for String impl must round-trip \
10160                 RestartPolicy::{variant:?} to the same lifted \
10161                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10162                 returns — divergence signals a silent detour off the \
10163                 substrate-primitive accessor"
10164            );
10165            let via_into: String = variant.into();
10166            assert_eq!(
10167                via_into.as_str(),
10168                via_method,
10169                "Into<String>::into on RestartPolicy::{variant:?} must \
10170                 byte-equal RestartPolicy::as_str on the same input — the \
10171                 blanket-derived Into shape must resolve to the same as_str \
10172                 dispatch as the explicit From impl"
10173            );
10174        }
10175    }
10176
10177    #[test]
10178    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10179        // Cross-axis partition pin: the paired trait-idiomatic
10180        // owned-`String` `From<RestartPolicy> for String` (this lift)
10181        // and owned-`&'static str` `From<RestartPolicy> for &'static
10182        // str` (9fb37d0) forward projections must resolve identically
10183        // on every arm, locking the two return-type-shape paths
10184        // together so any future detour trips at caixa-core test time.
10185        // Also byte-parity witness against the sibling
10186        // [`ToString::to_string`] surface routed through
10187        // [`std::fmt::Display`] — the three owned-heap-string paths
10188        // (`.into::<String>()`, `String::from`, `.to_string()`) must
10189        // resolve identically on every arm so a future consumer that
10190        // picks any of the three lands on the same lifted
10191        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10192        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10193        // that materializes the three-arm accept-set through the
10194        // owned-`String` axis alone — the exact shape a future
10195        // wasm-operator per-child post-exit restart-decision
10196        // diagnostic line composer or a
10197        // `HashMap::<String, RestartPolicy>::from_iter(
10198        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10199        // owned-key per-policy lookup reaches through — closing the
10200        // owned-`String` forward-projection axis's iterator-pipe
10201        // shape. Then a direct round-trip witness through the paired
10202        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10203        // owned-`String`'s [`String::as_str`] borrow that closes the
10204        // two-way `Self → String → Self` round-trip on the trait-
10205        // idiomatic owned-`String` forward + reverse axis pair —
10206        // unlike the peer [`crate::CaixaKind`] axis pair (whose
10207        // forward `From` emits lowercase Portuguese diagnostic bytes
10208        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10209        // forcing the round-trip through an intermediate wire-vocab
10210        // hop), the [`RestartPolicy::as_str`] emit and
10211        // [`RestartPolicy::from_wire`] parse share the same
10212        // `PascalCase` vocabulary by construction, so the owned-
10213        // `String` forward axis and the reverse axis compose directly.
10214        for &variant in RestartPolicy::ALL {
10215            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10216            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10217            assert_eq!(
10218                owned_string.as_str(),
10219                owned_static,
10220                "From<RestartPolicy> for String and From<RestartPolicy> \
10221                 for &'static str must resolve identically on \
10222                 RestartPolicy::{variant:?} — divergence signals the \
10223                 owned-`String` and owned-`&'static str` forward-projection \
10224                 return-type-shape paths have drifted onto different \
10225                 emit-sets"
10226            );
10227            let via_to_string: String = variant.to_string();
10228            assert_eq!(
10229                owned_string, via_to_string,
10230                "From<RestartPolicy> for String must byte-equal \
10231                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10232                 divergence signals the trait-idiomatic owned-`String` \
10233                 forward-projection axis and the ToString-through-Display \
10234                 axis have drifted onto different emit-sets"
10235            );
10236        }
10237        let via_iter: Vec<String> = RestartPolicy::ALL
10238            .iter()
10239            .copied()
10240            .map(String::from)
10241            .collect();
10242        let via_method: Vec<String> = RestartPolicy::ALL
10243            .iter()
10244            .map(|p| p.as_str().to_owned())
10245            .collect();
10246        assert_eq!(
10247            via_iter, via_method,
10248            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10249             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10250             every arm — the owned-`String` `From<RestartPolicy> for \
10251             String` axis is what makes the `String::from` composition \
10252             route through the substrate-primitive `RestartPolicy::as_str` \
10253             accessor rather than through a per-call-site `.to_owned()` / \
10254             `String::from(policy.as_str())` detour"
10255        );
10256        for &variant in RestartPolicy::ALL {
10257            let emitted: String = variant.into();
10258            let re_parsed: Result<RestartPolicy, ()> =
10259                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10260            assert_eq!(
10261                re_parsed,
10262                Ok(variant),
10263                "trait-idiomatic owned-`String` forward-projection + \
10264                 reverse-projection axis pair must round-trip \
10265                 RestartPolicy::{variant:?} through `.into::<String>()` \
10266                 and back through `TryFrom<&str>` on the owned-`String`'s \
10267                 String::as_str borrow — a break signals the owned-`String` \
10268                 forward-emit and reverse-parse axes have drifted onto \
10269                 different vocabularies"
10270            );
10271        }
10272    }
10273
10274    #[test]
10275    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10276        // Fail-before-pass-after byte-parity pin on the newly lifted
10277        // `impl From<&RestartPolicy> for String` — asserts the
10278        // borrowed-input owned-`String`-returning standard-library
10279        // trait impl and the substrate-primitive
10280        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10281        // the same three-arm emit-set across every arm the exhaustive
10282        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10283        // library does not carry a blanket `impl<T: AsRef<str>>
10284        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10285        // for String`), so the borrowed-input owned-`String` forward-
10286        // projection axis is a distinct trait-idiomatic surface that a
10287        // `let key: String = (&policy).into();`-shaped call site
10288        // reaches through this impl and no other — the paired sibling
10289        // `From<RestartPolicy> for String` impl forces every borrowed-
10290        // input call site through an explicit `Copy` deref
10291        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10292        // `.to_string()` detour. Peer of the first-mover
10293        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10294        // (579385f) — extends the trait-idiomatic borrowed-input
10295        // owned-`String` forward-projection axis onto the second-of-
10296        // two M2 OTP-shape closed-set typed enums on the caixa surface
10297        // (per-child restart-decision-policy sibling on the same M2
10298        // `:supervisor` slot).
10299        for &variant in RestartPolicy::ALL {
10300            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10301            let via_method: &'static str = variant.as_str();
10302            assert_eq!(
10303                via_trait.as_str(),
10304                via_method,
10305                "From<&RestartPolicy> for String impl must round-trip \
10306                 &RestartPolicy::{variant:?} to the same lifted \
10307                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10308                 returns — divergence signals a silent detour off the \
10309                 substrate-primitive accessor"
10310            );
10311            let via_into: String = (&variant).into();
10312            assert_eq!(
10313                via_into.as_str(),
10314                via_method,
10315                "Into<String>::into on &RestartPolicy::{variant:?} must \
10316                 byte-equal RestartPolicy::as_str on the same input — \
10317                 the blanket-derived Into shape must resolve to the \
10318                 same as_str dispatch as the explicit From impl"
10319            );
10320        }
10321    }
10322
10323    #[test]
10324    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10325        // Cross-axis partition pin: the newly lifted trait-idiomatic
10326        // borrowed-input owned-`String` `From<&RestartPolicy> for
10327        // String` (this lift), the paired owned-input owned-`String`
10328        // `From<RestartPolicy> for String` (7851725), the paired
10329        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10330        // for &'static str` (842c7f3), and the paired owned-input
10331        // owned-`&'static str` `From<RestartPolicy> for &'static str`
10332        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10333        // str, String}` 2×2 trait-idiomatic projection family — must
10334        // resolve identically on every arm, locking the four
10335        // return-shape × input-shape paths together so any future
10336        // detour trips at caixa-core test time. Also byte-parity
10337        // witness against the sibling [`ToString::to_string`] surface
10338        // routed through [`std::fmt::Display`] and a direct round-trip
10339        // witness through the paired trait-idiomatic reverse
10340        // [`TryFrom<&str>`] axis on the owned-`String`'s
10341        // [`String::as_str`] borrow that closes the two-way
10342        // `&Self → String → Self` round-trip on the trait-idiomatic
10343        // borrowed-input owned-`String` forward + reverse axis pair.
10344        // Peer of the first-mover
10345        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10346        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10347        // String}` 2×2 projection corner on both M2 OTP-shape sibling
10348        // peers.
10349        for &variant in RestartPolicy::ALL {
10350            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10351            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10352            let borrowed_static: &'static str =
10353                <&'static str as From<&RestartPolicy>>::from(&variant);
10354            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10355            assert_eq!(
10356                borrowed_string, owned_string,
10357                "From<&RestartPolicy> for String and From<RestartPolicy> \
10358                 for String must resolve identically on \
10359                 RestartPolicy::{variant:?} — divergence signals the \
10360                 borrowed-input and owned-input owned-`String` \
10361                 forward-projection input-shape paths have drifted onto \
10362                 different emit-sets"
10363            );
10364            assert_eq!(
10365                borrowed_string.as_str(),
10366                borrowed_static,
10367                "From<&RestartPolicy> for String and From<&RestartPolicy> \
10368                 for &'static str must resolve identically on \
10369                 RestartPolicy::{variant:?} — divergence signals the \
10370                 borrowed-input `&'static str` and owned-`String` \
10371                 return-shape paths have drifted onto different \
10372                 emit-sets"
10373            );
10374            assert_eq!(
10375                borrowed_string.as_str(),
10376                owned_static,
10377                "From<&RestartPolicy> for String and From<RestartPolicy> \
10378                 for &'static str must resolve identically on \
10379                 RestartPolicy::{variant:?} — divergence signals a \
10380                 break in the diagonal corner of the {{Self, &Self}} × \
10381                 {{&'static str, String}} 2×2 trait-idiomatic \
10382                 projection family"
10383            );
10384            let via_to_string: String = variant.to_string();
10385            assert_eq!(
10386                borrowed_string, via_to_string,
10387                "From<&RestartPolicy> for String must byte-equal \
10388                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10389                 — divergence signals the trait-idiomatic borrowed-input \
10390                 owned-`String` forward-projection axis and the \
10391                 ToString-through-Display axis have drifted onto \
10392                 different emit-sets"
10393            );
10394        }
10395        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10396        let via_method: Vec<String> = RestartPolicy::ALL
10397            .iter()
10398            .map(|p| p.as_str().to_owned())
10399            .collect();
10400        assert_eq!(
10401            via_iter, via_method,
10402            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10403             call site whose iteration axis holds `&RestartPolicy` by \
10404             construction — must byte-equal `.iter().map(|p| \
10405             p.as_str().to_owned())` on every arm — the borrowed-input \
10406             owned-`String` `From<&RestartPolicy> for String` axis is \
10407             what makes the `String::from` composition route through \
10408             the substrate-primitive `RestartPolicy::as_str` accessor \
10409             without a spurious `Copy` deref (which would only be \
10410             reachable through the owned-input `From<RestartPolicy> \
10411             for String` axis by first calling `.copied()` on the \
10412             iterator)"
10413        );
10414        for &variant in RestartPolicy::ALL {
10415            let emitted: String = (&variant).into();
10416            let re_parsed: Result<RestartPolicy, ()> =
10417                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10418            assert_eq!(
10419                re_parsed,
10420                Ok(variant),
10421                "trait-idiomatic borrowed-input owned-`String` \
10422                 forward-projection + reverse-projection axis pair must \
10423                 round-trip &RestartPolicy::{variant:?} through \
10424                 `.into::<String>()` on the borrowed-input surface and \
10425                 back through `TryFrom<&str>` on the owned-`String`'s \
10426                 String::as_str borrow — a break signals the \
10427                 borrowed-input owned-`String` forward-emit and \
10428                 reverse-parse axes have drifted onto different \
10429                 vocabularies"
10430            );
10431        }
10432    }
10433
10434    #[test]
10435    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10436        // Fail-before-pass-after byte-parity pin on the newly lifted
10437        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10438        // asserts the standard-library trait impl and the substrate-
10439        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10440        // accessor resolve to the same three-arm emit-set across every
10441        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10442        // enumerates. Rust's standard library does not carry a blanket
10443        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10444        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10445        // the `Cow<'static, str>` forward-projection axis is a
10446        // distinct trait-idiomatic surface that a
10447        // `let key: Cow<'static, str> = policy.into();`-shaped call
10448        // site reaches through this impl and no other — the paired
10449        // sibling `From<RestartPolicy> for &'static str` and
10450        // `From<RestartPolicy> for String` impls force every
10451        // `Cow<'static, str>`-parameterized call site through a
10452        // `Cow::Borrowed(policy.as_str())` /
10453        // `Cow::Owned(policy.to_string())` composition whose type
10454        // bounds have no compile-time link back to the substrate
10455        // primitive.
10456        //
10457        // Also asserts the projection lands on the zero-alloc
10458        // [`std::borrow::Cow::Borrowed`] arm (not the
10459        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10460        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10461        // return lifetime by construction makes the borrowed arm the
10462        // type-correct projection with no runtime allocation. Any
10463        // future silent detour that routes the impl through the owned
10464        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10465        // that would allocate on every call site where the
10466        // `&'static str` return of [`super::RestartPolicy::as_str`]
10467        // makes the zero-alloc borrowed projection type-correct) trips
10468        // at caixa-core test time under the
10469        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10470        // than at a downstream `Cow<'static, str>`-bound consumer's
10471        // silent allocation.
10472        //
10473        // Second peer on the substrate-wide trait-idiomatic
10474        // [`std::borrow::Cow<'static, str>`] forward-projection family
10475        // to extend the axis off the top-level [`super::CaixaKind`]
10476        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10477        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10478        // fieldless typed enum peer on the caixa surface — closes the
10479        // M2 OTP-shape tier of the campaign on the owned-input axis
10480        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10481        // now carry the owned-input Cow<'static, str> forward
10482        // projection).
10483        for &variant in RestartPolicy::ALL {
10484            let via_trait: std::borrow::Cow<'static, str> =
10485                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10486            let via_method: &'static str = variant.as_str();
10487            assert_eq!(
10488                via_trait.as_ref(),
10489                via_method,
10490                "From<RestartPolicy> for Cow<'static, str> impl must \
10491                 round-trip RestartPolicy::{variant:?} to the same \
10492                 lifted SUPERVISOR_CHILD_RESTART_* const \
10493                 RestartPolicy::as_str returns — divergence signals a \
10494                 silent detour off the substrate-primitive accessor"
10495            );
10496            assert!(
10497                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10498                "From<RestartPolicy> for Cow<'static, str> impl must \
10499                 land on the zero-alloc Cow::Borrowed arm on \
10500                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10501                 signals the projection has silently allocated where \
10502                 the substrate-primitive RestartPolicy::as_str \
10503                 `&'static str` return makes the borrowed arm the \
10504                 type-correct projection"
10505            );
10506            let via_into: std::borrow::Cow<'static, str> = variant.into();
10507            assert_eq!(
10508                via_into.as_ref(),
10509                via_method,
10510                "Into<Cow<'static, str>>::into on \
10511                 RestartPolicy::{variant:?} must byte-equal \
10512                 RestartPolicy::as_str on the same input — the \
10513                 blanket-derived Into shape must resolve to the same \
10514                 as_str dispatch as the explicit From impl"
10515            );
10516            assert!(
10517                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10518                "Into<Cow<'static, str>>::into on \
10519                 RestartPolicy::{variant:?} must land on the \
10520                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10521                 Into shape must resolve to the same Cow::Borrowed \
10522                 dispatch as the explicit From impl"
10523            );
10524        }
10525    }
10526
10527    #[test]
10528    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10529        // Cross-axis partition pin: the newly lifted trait-idiomatic
10530        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10531        // (this lift), the paired owned-input `From<RestartPolicy>
10532        // for &'static str` (9fb37d0), and the paired owned-input
10533        // `From<RestartPolicy> for String` (7851725) forward
10534        // projections must resolve identically on every arm, locking
10535        // the three return-shape paths together by construction so any
10536        // future detour trips at caixa-core test time. Also byte-parity
10537        // witness against the sibling [`ToString::to_string`] surface
10538        // routed through [`std::fmt::Display`] — every owned-heap-
10539        // string path (the `Cow::Owned` promotion of this axis's
10540        // `.into_owned()`, `From<RestartPolicy> for String`, and
10541        // `.to_string()`) resolves to the same lifted
10542        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10543        //
10544        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10545        // witness over [`super::RestartPolicy::ALL`] that
10546        // materializes the three-arm accept-set through the
10547        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10548        // shape a future `axum::response::IntoResponse` per-policy
10549        // rejection-body composer, a future M4 admission-webhook
10550        // per-policy rejection-reason emitter whose typing rules out
10551        // the sibling [`AsRef<str>`] borrowed return, or a future
10552        // substrate-wide per-policy diagnostic surface that binds
10553        // through a [`Cow<'static, str>`] boundary reaches through.
10554        // The pipe witness also pins the zero-alloc discipline: every
10555        // element in the collected vector satisfies the
10556        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10557        // accidental silent-allocation regression on the pipe's
10558        // iteration axis is a caixa-core-test-time failure. Peer of
10559        // the first-mover
10560        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10561        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10562        // — closes the whole owned-input `Cow<'static, str>` +
10563        // paired `{&'static str, String}` cross-axis-parity corner on
10564        // both M2 OTP-shape sibling peers.
10565        for &variant in RestartPolicy::ALL {
10566            let via_cow: std::borrow::Cow<'static, str> =
10567                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10568            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10569            let via_string: String = <String as From<RestartPolicy>>::from(variant);
10570            assert_eq!(
10571                via_cow.as_ref(),
10572                via_static,
10573                "From<RestartPolicy> for Cow<'static, str> and \
10574                 From<RestartPolicy> for &'static str must resolve \
10575                 identically on RestartPolicy::{variant:?} — \
10576                 divergence signals the Cow<'static, str> and \
10577                 &'static str return-shape paths have drifted onto \
10578                 different emit-sets"
10579            );
10580            assert_eq!(
10581                via_cow.as_ref(),
10582                via_string.as_str(),
10583                "From<RestartPolicy> for Cow<'static, str> and \
10584                 From<RestartPolicy> for String must resolve \
10585                 identically on RestartPolicy::{variant:?} — \
10586                 divergence signals the Cow<'static, str> and String \
10587                 return-shape paths have drifted onto different \
10588                 emit-sets"
10589            );
10590            let via_to_string: String = variant.to_string();
10591            assert_eq!(
10592                via_cow.as_ref(),
10593                via_to_string.as_str(),
10594                "From<RestartPolicy> for Cow<'static, str> must \
10595                 byte-equal RestartPolicy::to_string on \
10596                 RestartPolicy::{variant:?} — divergence signals the \
10597                 trait-idiomatic Cow<'static, str> forward-projection \
10598                 axis and the ToString-through-Display axis have \
10599                 drifted onto different emit-sets"
10600            );
10601        }
10602        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10603            .iter()
10604            .copied()
10605            .map(std::borrow::Cow::from)
10606            .collect();
10607        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10608            .iter()
10609            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10610            .collect();
10611        assert_eq!(
10612            via_iter, via_method,
10613            "`.iter().copied().map(Cow::from)` over \
10614             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10615             Cow::Borrowed(p.as_str()))` on every arm — the \
10616             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10617             str>` axis is what makes the `Cow::from` composition \
10618             route through the substrate-primitive \
10619             `RestartPolicy::as_str` accessor with the zero-alloc \
10620             Cow::Borrowed arm by construction, rather than a \
10621             per-call-site `Cow::Owned(policy.to_string())` \
10622             allocation"
10623        );
10624        for cow in &via_iter {
10625            assert!(
10626                matches!(cow, std::borrow::Cow::Borrowed(_)),
10627                "every element of the \
10628                 .iter().copied().map(Cow::from) pipe over \
10629                 RestartPolicy::ALL must land on the zero-alloc \
10630                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10631                 signals the pipe's iteration axis has silently \
10632                 allocated where the substrate-primitive \
10633                 RestartPolicy::as_str `&'static str` return makes \
10634                 the borrowed arm the type-correct projection"
10635            );
10636        }
10637    }
10638
10639    #[test]
10640    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10641        // Fail-before-pass-after byte-parity pin on the newly lifted
10642        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10643        // asserts the borrowed-input standard-library trait impl and
10644        // the substrate-primitive [`super::RestartPolicy::as_str`]
10645        // `pub const fn` accessor resolve to the same three-arm emit-
10646        // set across every arm the exhaustive
10647        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10648        // standard library does not carry a blanket
10649        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10650        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10651        // the borrowed-input `Cow<'static, str>` forward-projection
10652        // axis is a distinct trait-idiomatic surface that a
10653        // `let key: Cow<'static, str> = (&policy).into();`-shaped
10654        // call site or a
10655        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10656        // reaches through this impl and no other — the paired owned-
10657        // input `From<RestartPolicy> for Cow<'static, str>` impl
10658        // (0612398) forces every borrowed-input call site through an
10659        // explicit `Copy` deref (`Cow::from(*policy)`) or a
10660        // `Cow::Borrowed(policy.as_str())` open-code whose type
10661        // bounds have no compile-time link back to the substrate
10662        // primitive.
10663        //
10664        // Also asserts the projection lands on the zero-alloc
10665        // [`std::borrow::Cow::Borrowed`] arm (not the
10666        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10667        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10668        // return lifetime by construction makes the borrowed arm the
10669        // type-correct projection with no runtime allocation on the
10670        // borrowed-input surface just as on the paired owned-input
10671        // surface.
10672        //
10673        // Closes the `{Self, &Self}` input-shape corner on the M2
10674        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10675        // the second-of-two-in-M2 closed-set fieldless typed enum peer
10676        // on the caixa surface (`:supervisor :children :restart`),
10677        // exactly as d45c409 closed it on the top-level
10678        // [`super::CaixaKind`] one commit after the owning half
10679        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10680        // M2 OTP-shape [`super::RestartStrategy`] one commit after
10681        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10682        // tier of the substrate-wide Cow<'static, str> forward-
10683        // projection campaign on both input-shape corners
10684        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10685        for &variant in RestartPolicy::ALL {
10686            let via_trait: std::borrow::Cow<'static, str> =
10687                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10688            let via_method: &'static str = variant.as_str();
10689            assert_eq!(
10690                via_trait.as_ref(),
10691                via_method,
10692                "From<&RestartPolicy> for Cow<'static, str> impl must \
10693                 round-trip &RestartPolicy::{variant:?} to the same \
10694                 lifted SUPERVISOR_CHILD_RESTART_* const \
10695                 RestartPolicy::as_str returns — divergence signals a \
10696                 silent detour off the substrate-primitive accessor"
10697            );
10698            assert!(
10699                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10700                "From<&RestartPolicy> for Cow<'static, str> impl must \
10701                 land on the zero-alloc Cow::Borrowed arm on \
10702                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10703                 signals the projection has silently allocated where \
10704                 the substrate-primitive RestartPolicy::as_str \
10705                 `&'static str` return makes the borrowed arm the \
10706                 type-correct projection"
10707            );
10708            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10709            assert_eq!(
10710                via_into.as_ref(),
10711                via_method,
10712                "Into<Cow<'static, str>>::into on \
10713                 &RestartPolicy::{variant:?} must byte-equal \
10714                 RestartPolicy::as_str on the same input — the \
10715                 blanket-derived Into shape must resolve to the same \
10716                 as_str dispatch as the explicit From impl"
10717            );
10718            assert!(
10719                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10720                "Into<Cow<'static, str>>::into on \
10721                 &RestartPolicy::{variant:?} must land on the \
10722                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10723                 Into shape must resolve to the same Cow::Borrowed \
10724                 dispatch as the explicit From impl"
10725            );
10726        }
10727    }
10728
10729    #[test]
10730    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10731        // Cross-axis partition pin: the newly lifted trait-idiomatic
10732        // borrowed-input `From<&RestartPolicy> for
10733        // std::borrow::Cow<'static, str>` (this lift), the paired
10734        // owned-input `From<RestartPolicy> for
10735        // std::borrow::Cow<'static, str>` (0612398), the paired
10736        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10737        // for &'static str`, and the paired borrowed-input owned-
10738        // `String` `From<&RestartPolicy> for String` must resolve
10739        // identically on every arm, locking the four
10740        // return-shape × input-shape paths together by construction so
10741        // any future detour trips at caixa-core test time. Also byte-
10742        // parity witness against the sibling [`ToString::to_string`]
10743        // surface routed through [`std::fmt::Display`] — every owned-
10744        // heap-string path (this axis's `.into_owned()` promotion, the
10745        // paired [`From<&RestartPolicy> for String`], and
10746        // `.to_string()`) resolves to the same lifted
10747        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10748        //
10749        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10750        // over [`super::RestartPolicy::ALL`] — whose iterator yields
10751        // `&RestartPolicy` by construction, so the borrowed-input
10752        // [`Cow<'static, str>`] axis is what routes the pipe through
10753        // the substrate-primitive [`super::RestartPolicy::as_str`]
10754        // accessor without a spurious [`Copy`] deref (which would only
10755        // be reachable through the owned-input
10756        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10757        // calling `.copied()` on the iterator). The pipe witness also
10758        // pins the zero-alloc discipline: every element in the
10759        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10760        // arm predicate, so a future accidental silent-allocation
10761        // regression on the pipe's iteration axis is a caixa-core-
10762        // test-time failure. Peer of the sibling
10763        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10764        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10765        // the whole borrowed-input `Cow<'static, str>` +
10766        // paired `{&'static str, String}` cross-axis-parity corner on
10767        // both M2 OTP-shape sibling peers.
10768        for &policy in RestartPolicy::ALL {
10769            let borrowed_cow: std::borrow::Cow<'static, str> =
10770                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10771            let owned_cow: std::borrow::Cow<'static, str> =
10772                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10773            let borrowed_static: &'static str =
10774                <&'static str as From<&RestartPolicy>>::from(&policy);
10775            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10776            assert_eq!(
10777                borrowed_cow, owned_cow,
10778                "From<&RestartPolicy> for Cow<'static, str> and \
10779                 From<RestartPolicy> for Cow<'static, str> must \
10780                 resolve identically on RestartPolicy::{policy:?} — \
10781                 divergence signals the borrowed-input and owned-input \
10782                 Cow<'static, str> forward-projection input-shape \
10783                 paths have drifted onto different emit-sets"
10784            );
10785            assert_eq!(
10786                borrowed_cow.as_ref(),
10787                borrowed_static,
10788                "From<&RestartPolicy> for Cow<'static, str> and \
10789                 From<&RestartPolicy> for &'static str must resolve \
10790                 identically on RestartPolicy::{policy:?} — \
10791                 divergence signals the borrowed-input Cow<'static, \
10792                 str> and &'static str return-shape paths have drifted \
10793                 onto different emit-sets"
10794            );
10795            assert_eq!(
10796                borrowed_cow.as_ref(),
10797                borrowed_string.as_str(),
10798                "From<&RestartPolicy> for Cow<'static, str> and \
10799                 From<&RestartPolicy> for String must resolve \
10800                 identically on RestartPolicy::{policy:?} — \
10801                 divergence signals the borrowed-input Cow<'static, \
10802                 str> and owned-`String` return-shape paths have \
10803                 drifted onto different emit-sets"
10804            );
10805            let via_to_string: String = policy.to_string();
10806            assert_eq!(
10807                borrowed_cow.as_ref(),
10808                via_to_string.as_str(),
10809                "From<&RestartPolicy> for Cow<'static, str> must \
10810                 byte-equal RestartPolicy::to_string on \
10811                 RestartPolicy::{policy:?} — divergence signals \
10812                 the trait-idiomatic borrowed-input Cow<'static, str> \
10813                 forward-projection axis and the ToString-through-\
10814                 Display axis have drifted onto different emit-sets"
10815            );
10816        }
10817        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10818            .iter()
10819            .map(std::borrow::Cow::from)
10820            .collect();
10821        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10822            .iter()
10823            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10824            .collect();
10825        assert_eq!(
10826            via_iter, via_method,
10827            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10828             call site whose iteration axis holds `&RestartPolicy` \
10829             by construction — must byte-equal `.iter().map(|p| \
10830             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10831             input Cow<'static, str> `From<&RestartPolicy> for \
10832             Cow<'static, str>` axis is what makes the `Cow::from` \
10833             composition route through the substrate-primitive \
10834             `RestartPolicy::as_str` accessor with the zero-alloc \
10835             Cow::Borrowed arm by construction and without a spurious \
10836             `Copy` deref (which would only be reachable through the \
10837             owned-input `From<RestartPolicy> for Cow<'static, str>` \
10838             axis by first calling `.copied()` on the iterator)"
10839        );
10840        for cow in &via_iter {
10841            assert!(
10842                matches!(cow, std::borrow::Cow::Borrowed(_)),
10843                "every element of the .iter().map(Cow::from) pipe \
10844                 over RestartPolicy::ALL must land on the zero-\
10845                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10846                 any arm signals the pipe's iteration axis has \
10847                 silently allocated where the substrate-primitive \
10848                 RestartPolicy::as_str `&'static str` return makes \
10849                 the borrowed arm the type-correct projection"
10850            );
10851        }
10852    }
10853
10854    #[test]
10855    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
10856        // Fail-before-pass-after byte-parity pin on the newly lifted
10857        // `impl From<RestartPolicy> for Box<str>` — asserts the
10858        // owned-input standard-library trait impl and the
10859        // substrate-primitive [`super::RestartPolicy::as_str`]
10860        // `pub const fn` accessor resolve to the same three-arm emit-
10861        // set across every arm the exhaustive
10862        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
10863        // substrate-wide `Box<str>` forward-projection campaign tier
10864        // opened one commit prior (69ef45c) on the paired sibling-
10865        // restart [`RestartStrategy`] onto the second (and third-and-
10866        // final) M2 OTP-shape closed-set fieldless typed enum peer on
10867        // the caixa surface (`:children :restart`), immediately after
10868        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
10869        // closed the
10870        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10871        // 2×3 corner on this enum. Rust's standard library carries
10872        // `impl From<&str> for Box<str>` and
10873        // `impl From<String> for Box<str>` but no blanket
10874        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10875        // a distinct trait-idiomatic surface that a
10876        // `let key: Box<str> = policy.into();`-shaped call site
10877        // reaches through this impl and no other — a paired
10878        // `Box::from(policy.as_str())` open-code has no compile-time
10879        // link back to the substrate primitive. Peer of the sibling
10880        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
10881        // (69ef45c) — extends the trait-idiomatic owned-input
10882        // [`Box<str>`] forward-projection axis onto the third and
10883        // final M2-OTP-shape closed-set typed enum on the caixa
10884        // surface.
10885        for &variant in RestartPolicy::ALL {
10886            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10887            let via_method: &'static str = variant.as_str();
10888            assert_eq!(
10889                via_trait.as_ref(),
10890                via_method,
10891                "From<RestartPolicy> for Box<str> impl must round-\
10892                 trip RestartPolicy::{variant:?} to the same lifted \
10893                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10894                 returns — divergence signals a silent detour off the \
10895                 substrate-primitive accessor"
10896            );
10897            let via_into: Box<str> = variant.into();
10898            assert_eq!(
10899                via_into.as_ref(),
10900                via_method,
10901                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
10902                 must byte-equal RestartPolicy::as_str on the same \
10903                 input — the blanket-derived Into shape must resolve \
10904                 to the same as_str dispatch as the explicit From impl"
10905            );
10906        }
10907    }
10908
10909    #[test]
10910    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10911        // Fail-before-pass-after byte-parity pin on the newly lifted
10912        // `impl From<&RestartPolicy> for Box<str>` — asserts the
10913        // borrowed-input standard-library trait impl and the
10914        // substrate-primitive [`super::RestartPolicy::as_str`]
10915        // `pub const fn` accessor resolve to the same three-arm emit-
10916        // set across every arm the exhaustive
10917        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10918        // standard library does not carry a blanket
10919        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10920        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10921        // so the borrowed-input `Box<str>` forward-projection axis
10922        // is a distinct trait-idiomatic surface that a
10923        // `let key: Box<str> = (&policy).into();`-shaped call site
10924        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
10925        // shaped pipe reaches through this impl and no other — the
10926        // paired owned-input `From<RestartPolicy> for Box<str>`
10927        // impl (0a1b313) forces every borrowed-input call site
10928        // through an explicit `Copy` deref
10929        // (`Box::<str>::from((*policy).as_str())`) or a
10930        // `Box::<str>::from(policy.as_str())` open-code whose
10931        // type bounds have no compile-time link back to the
10932        // substrate primitive.
10933        //
10934        // Fourth (and closing) peer on the substrate-wide trait-
10935        // idiomatic [`Box<str>`] forward-projection family on the
10936        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
10937        // shape corner of the [`Box<str>`] axis on the second (and
10938        // third-and-final) M2 OTP-shape closed-set fieldless typed
10939        // enum peer on the caixa surface (`:children :restart`),
10940        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
10941        // axis one commit after its owning half (0612398) landed
10942        // on this enum. Every remaining closed-set fieldless typed
10943        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
10944        // render-side / outside-caixa-core tiers is a future
10945        // target of the campaign.
10946        //
10947        // Also byte-parity witness against the paired owned-input
10948        // [`From<RestartPolicy> for Box<str>`] and the sibling
10949        // borrowed-input [`From<&RestartPolicy> for &'static str`],
10950        // [`From<&RestartPolicy> for String`], and
10951        // [`From<&RestartPolicy> for Cow<'static, str>`]
10952        // return-shape axes — locking the four
10953        // return-shape × input-shape paths together by construction
10954        // so any future detour trips at caixa-core test time. Then a
10955        // `.iter().map(Box::<str>::from)` pipe witness over
10956        // [`super::RestartPolicy::ALL`] — whose iterator yields
10957        // `&RestartPolicy` by construction, so the borrowed-input
10958        // [`Box<str>`] axis is what routes the pipe through the
10959        // substrate-primitive [`super::RestartPolicy::as_str`]
10960        // accessor without a spurious [`Copy`] deref (which would
10961        // only be reachable through the owned-input
10962        // [`From<RestartPolicy> for Box<str>`] axis by first
10963        // calling `.copied()` on the iterator).
10964        for &variant in RestartPolicy::ALL {
10965            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
10966            let via_method: &'static str = variant.as_str();
10967            assert_eq!(
10968                via_trait.as_ref(),
10969                via_method,
10970                "From<&RestartPolicy> for Box<str> impl must round-\
10971                 trip &RestartPolicy::{variant:?} to the same lifted \
10972                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10973                 returns — divergence signals a silent detour off the \
10974                 substrate-primitive accessor"
10975            );
10976            let via_into: Box<str> = (&variant).into();
10977            assert_eq!(
10978                via_into.as_ref(),
10979                via_method,
10980                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
10981                 must byte-equal RestartPolicy::as_str on the same \
10982                 input — the blanket-derived Into shape must resolve \
10983                 to the same as_str dispatch as the explicit From impl"
10984            );
10985            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10986            assert_eq!(
10987                via_trait, owned_box,
10988                "From<&RestartPolicy> for Box<str> and \
10989                 From<RestartPolicy> for Box<str> must resolve \
10990                 identically on RestartPolicy::{variant:?} — \
10991                 divergence signals the borrowed-input and owned-input \
10992                 Box<str> forward-projection input-shape paths have \
10993                 drifted onto different emit-sets"
10994            );
10995            let borrowed_static: &'static str =
10996                <&'static str as From<&RestartPolicy>>::from(&variant);
10997            assert_eq!(
10998                via_trait.as_ref(),
10999                borrowed_static,
11000                "From<&RestartPolicy> for Box<str> and \
11001                 From<&RestartPolicy> for &'static str must resolve \
11002                 identically on RestartPolicy::{variant:?} — \
11003                 divergence signals the borrowed-input Box<str> and \
11004                 &'static str return-shape paths have drifted onto \
11005                 different emit-sets"
11006            );
11007            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11008            assert_eq!(
11009                via_trait.as_ref(),
11010                borrowed_string.as_str(),
11011                "From<&RestartPolicy> for Box<str> and \
11012                 From<&RestartPolicy> for String must resolve \
11013                 identically on RestartPolicy::{variant:?} — \
11014                 divergence signals the borrowed-input Box<str> and \
11015                 owned-`String` return-shape paths have drifted onto \
11016                 different emit-sets"
11017            );
11018            let borrowed_cow: std::borrow::Cow<'static, str> =
11019                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11020            assert_eq!(
11021                via_trait.as_ref(),
11022                borrowed_cow.as_ref(),
11023                "From<&RestartPolicy> for Box<str> and \
11024                 From<&RestartPolicy> for Cow<'static, str> must \
11025                 resolve identically on RestartPolicy::{variant:?} — \
11026                 divergence signals the borrowed-input Box<str> and \
11027                 Cow<'static, str> return-shape paths have drifted \
11028                 onto different emit-sets"
11029            );
11030        }
11031        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11032        let via_method: Vec<Box<str>> = RestartPolicy::ALL
11033            .iter()
11034            .map(|p| Box::<str>::from(p.as_str()))
11035            .collect();
11036        assert_eq!(
11037            via_iter, via_method,
11038            "`.iter().map(Box::<str>::from)` over \
11039             RestartPolicy::ALL — a call site whose iteration axis \
11040             holds `&RestartPolicy` by construction — must byte-\
11041             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11042             on every arm — the borrowed-input Box<str> \
11043             `From<&RestartPolicy> for Box<str>` axis is what \
11044             makes the `Box::<str>::from` composition route through \
11045             the substrate-primitive `RestartPolicy::as_str` \
11046             accessor without a spurious `Copy` deref (which would \
11047             only be reachable through the owned-input \
11048             `From<RestartPolicy> for Box<str>` axis by first \
11049             calling `.copied()` on the iterator)"
11050        );
11051    }
11052
11053    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
11054
11055    #[test]
11056    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
11057        // The fail-before-pass-after pin: pre-lift there was no
11058        // single-source binding between the [`RestartPolicy`] variant
11059        // name the un-`rename`d `Serialize` derive emits under
11060        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
11061        // byte-string every downstream cluster-side dispatcher (the
11062        // future wasm-operator's per-child post-exit restart-decision
11063        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
11064        // materializer's admission-time enum-arm bind, the
11065        // `caixa-operator`'s hierarchical reconciliation scheduler's
11066        // per-child-policy fan-out) probes verbatim. A future
11067        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
11068        // or a per-variant `#[serde(rename = "…")]` override, or a
11069        // variant rename in the source — would silently rebrand the
11070        // emitted scalar under one spelling while every downstream
11071        // dispatcher still probed the other, with the failure surfacing
11072        // at the operator's reconcile posture (children coming up under
11073        // the `default()` `Permanent` arm rather than the typed slot's
11074        // declared policy — a `:temporary` `oneShot` child would be
11075        // restarted on clean exit, treating the successful-completion
11076        // signal as failure and re-running the completion-terminal
11077        // one-shot indefinitely; a `:transient` child that clean-exited
11078        // would be restarted, masking the clean-completion contract)
11079        // far from the source rebrand commit and with no field naming
11080        // the drift. Pinning the two paths (the `Serialize` derive's
11081        // serialized string AND the [`RestartPolicy::as_str`] helper)
11082        // to the same three lifted
11083        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
11084        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
11085        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
11086        // byte-strings makes any future drift on either endpoint fail
11087        // here at caixa-core build time. Peer of the sibling
11088        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
11089        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11090        // and the M3
11091        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
11092        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
11093        // same three-path-convergence discipline, extended to close the
11094        // third OTP-shaped closed-enum discriminator axis on the caixa
11095        // typed surface (per-child restart-decision policy).
11096        for (variant, expected) in [
11097            (
11098                RestartPolicy::Permanent,
11099                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11100            ),
11101            (
11102                RestartPolicy::Temporary,
11103                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11104            ),
11105            (
11106                RestartPolicy::Transient,
11107                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11108            ),
11109        ] {
11110            let json = serde_json::to_string(&variant).unwrap();
11111            assert_eq!(
11112                json,
11113                format!("\"{expected}\""),
11114                "RestartPolicy::{variant:?} must serialize to {expected:?}"
11115            );
11116            assert_eq!(
11117                variant.as_str(),
11118                expected,
11119                "RestartPolicy::{variant:?}.as_str() must return the lifted \
11120                 SUPERVISOR_CHILD_RESTART_* constant"
11121            );
11122        }
11123    }
11124
11125    #[test]
11126    fn supervisor_child_restart_consts_are_pairwise_distinct() {
11127        // Cross-arm drift-detection pin: a future collapse of two
11128        // canonical variant byte-strings onto the same value (e.g. an
11129        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
11130        // to also read `"Permanent"`) would silently reroute every
11131        // downstream operator's per-child-policy dispatch onto the
11132        // sibling arm's reconcile branch and pass every propagation-probe
11133        // test that expected only the stale arm's value — a `:transient`
11134        // child would come up under the `:permanent` restart-decision
11135        // posture on every subsequent clean exit, so a completion-terminal
11136        // child would be restarted indefinitely against its declared
11137        // policy. Peer of the sibling
11138        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
11139        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11140        // and the four-way distinct pin
11141        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
11142        // top-level `SUPERVISOR_KEY_*` axis.
11143        let all = [
11144            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11145            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11146            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11147        ];
11148        for (i, a) in all.iter().enumerate() {
11149            for (j, b) in all.iter().enumerate() {
11150                if i != j {
11151                    assert_ne!(
11152                        a, b,
11153                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
11154                         — got duplicate {a:?} at indices {i} and {j}",
11155                    );
11156                }
11157            }
11158        }
11159    }
11160
11161    #[test]
11162    fn restart_policy_display_routes_through_as_str_helper() {
11163        // The fail-before-pass-after pin on the first half of the
11164        // three-path convergence: pre-convergence [`RestartPolicy`]
11165        // carried a [`std::fmt::Display`] surface via its
11166        // `#[discriminant(also_display)]` gen-platform derive route,
11167        // which arrived kebab-case as `"permanent"` / `"temporary"`
11168        // / `"transient"` on this three-arm enum (whose variant
11169        // names each collapse to their own lowercase form under the
11170        // kebab-case transform) while the wire format ran as
11171        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
11172        // through the un-`rename`d serde derive. Every consumer
11173        // reaching for a policy byte-string past the wire format had
11174        // to pick between three paths ([`RestartPolicy::as_str`],
11175        // the `Serialize` derive's serialized string, or
11176        // `format!("{v}")` on the discriminant-Display route), any
11177        // two of which a future variant rename or
11178        // `#[serde(rename_all = "kebab-case")]` attribute would
11179        // silently desynchronize. Wiring [`std::fmt::Display`]
11180        // through [`RestartPolicy::as_str`] closes the third path:
11181        // every `format!("{v}")` call reaches the same lifted
11182        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
11183        // wire format and the [`RestartPolicy::as_str`] helper
11184        // already route through, so a future variant rename lands at
11185        // exactly one place. Pin the routing here so a future
11186        // `impl std::fmt::Display for RestartPolicy`
11187        // reimplementation that hand-rolls the arms instead of
11188        // delegating to [`RestartPolicy::as_str`] fails at
11189        // caixa-core build time. Peer of the sibling
11190        // [`restart_strategy_display_routes_through_as_str_helper`]
11191        // on the per-supervisor sibling-restart-strategy axis and
11192        // the M3
11193        // `placement_strategy_display_routes_through_as_str_helper`
11194        // (cc8f749) — the third of three OTP-shape closed-enum
11195        // discriminator axes on the caixa typed surface now
11196        // converged onto the same three-path
11197        // (Display → as_str → lifted const) discipline.
11198        for variant in [
11199            RestartPolicy::Permanent,
11200            RestartPolicy::Temporary,
11201            RestartPolicy::Transient,
11202        ] {
11203            assert_eq!(
11204                variant.to_string(),
11205                variant.as_str(),
11206                "RestartPolicy::{variant:?} Display must route through \
11207                 RestartPolicy::as_str (single source of truth: the lifted \
11208                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
11209            );
11210        }
11211    }
11212
11213    #[test]
11214    fn restart_policy_display_matches_serialized_wire_byte_string() {
11215        // The fail-before-pass-after pin on the second half of the
11216        // three-path convergence: `Display` (user-facing text) agrees
11217        // byte-for-byte with the `Serialize` derive's wire format
11218        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
11219        // scalar) on every variant. Pre-convergence the two paths
11220        // were structurally independent — a future
11221        // `#[serde(rename_all = "kebab-case")]` attribute on the
11222        // enum would silently rebrand the emitted wire scalar
11223        // (`permanent`, `temporary`, `transient`) while every
11224        // consumer that pretty-prints the policy (the future
11225        // wasm-operator's per-child post-exit restart-decision
11226        // diagnostic line, the future `feira app graph` per-child
11227        // restart column, the future M4
11228        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
11229        // per-child admission-webhook rejection body) would still
11230        // emit the PascalCase form the `as_str` / `Display` route
11231        // returns, with the mismatch surfacing at consumer parse
11232        // time / operator dispatch time far from the source rebrand
11233        // commit. Pin the two paths byte-for-byte here so any future
11234        // serde-attribute or variant-rename drift is a
11235        // caixa-core-build-time test failure at this call, not a
11236        // silent per-consumer dispatch miss. Peer of the sibling
11237        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
11238        // on the per-supervisor sibling-restart-strategy axis and
11239        // the M3
11240        // `placement_strategy_display_matches_serialized_wire_byte_string`
11241        // (cc8f749).
11242        for variant in [
11243            RestartPolicy::Permanent,
11244            RestartPolicy::Temporary,
11245            RestartPolicy::Transient,
11246        ] {
11247            let wire = serde_json::to_string(&variant).unwrap();
11248            let unquoted = wire
11249                .strip_prefix('"')
11250                .and_then(|s| s.strip_suffix('"'))
11251                .expect("serialized RestartPolicy is a JSON string");
11252            assert_eq!(
11253                variant.to_string(),
11254                unquoted,
11255                "RestartPolicy::{variant:?} Display byte-string must match the \
11256                 Serialize derive's wire byte-string (three-path convergence: \
11257                 Display + as_str + Serialize all resolve to the same \
11258                 SUPERVISOR_CHILD_RESTART_* const)"
11259            );
11260        }
11261    }
11262
11263    #[test]
11264    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11265        // Fail-before-pass-after byte-parity pin on the lifted
11266        // `impl AsRef<str> for RestartPolicy` — asserts the
11267        // standard-library trait impl and the substrate-primitive
11268        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11269        // to the same `&str` per instance across the three-arm
11270        // closed set, so any future silent detour that routes the
11271        // impl through a divergent projection (a per-arm inline
11272        // `match self { RestartPolicy::Permanent => "Permanent", … }`
11273        // re-inlining that opens a compile-time link to the un-lifted
11274        // arm-literal, a swap onto the kebab-case
11275        // [`gen_platform::Discriminant`] catalog identity that would
11276        // collide the wire axis with the dispatcher-catalog axis) trips
11277        // at caixa-core test time under `PartialEq` rather than at a
11278        // downstream `impl AsRef<str>`-bound consumer's silent split.
11279        // Sweeps every one of the three arms
11280        // [`RestartPolicy::ALL`] carries so no arm's projection is
11281        // covered only by the sibling wire-format `Serialize` derive
11282        // path. Peer of the sibling
11283        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11284        // (63eb1a4) on the paired per-supervisor sibling-restart-
11285        // strategy axis and the [`crate::CaixaVersion`]
11286        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11287        // top-level `:versao` typed newtype — the three pins together
11288        // cover the substrate primitive's `AsRef<str>` projection axis
11289        // on the paired newtype + M2 closed-set-typed-enum surface.
11290        for &variant in RestartPolicy::ALL {
11291            assert_eq!(
11292                <RestartPolicy as AsRef<str>>::as_ref(&variant),
11293                variant.as_str(),
11294                "AsRef<str> impl on RestartPolicy::{variant:?} must \
11295                 byte-equal RestartPolicy::as_str on the same instance \
11296                 — divergence signals a silent detour off the substrate-\
11297                 primitive accessor"
11298            );
11299        }
11300    }
11301
11302    #[test]
11303    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11304        // Fail-before-pass-after byte-parity pin on the three-path
11305        // convergence discipline the M2 per-child-restart-policy
11306        // primitive now carries on the `&str`-projection axis:
11307        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11308        // lifted impl), `format!("{v}")` (the pre-existing
11309        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
11310        // primitive `pub const fn` accessor both trait impls delegate
11311        // through) must resolve to the same byte-string on every
11312        // instance across the three-arm closed set. Refuses any future
11313        // divergence between the two trait impls (a stray
11314        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
11315        // rather than delegating through the shared accessor; a
11316        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
11317        // literal cascade) that would silently split the two
11318        // projection paths of the same closed-set typed enum. Mirrors
11319        // the sibling three-path-convergence discipline the peer
11320        // [`RestartStrategy`] typed enum carries on its
11321        // `AsRef<str>` / `Display` / `as_str` triple
11322        // (supervisor.rs pin
11323        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
11324        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
11325        // carries on the same triple (version.rs pin
11326        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
11327        // 16d5c7e).
11328        for &variant in RestartPolicy::ALL {
11329            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
11330            let via_display: String = format!("{variant}");
11331            let via_accessor: &str = variant.as_str();
11332            assert_eq!(via_as_ref, via_accessor);
11333            assert_eq!(via_display, via_accessor);
11334            assert_eq!(via_as_ref, via_display.as_str());
11335        }
11336    }
11337
11338    #[test]
11339    fn restart_policy_all_enumerates_every_variant_exactly_once() {
11340        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
11341        // exhaustive-iteration surface: every variant appears exactly
11342        // once, and the slice length matches the arm count of the
11343        // closed set. Every consumer that walks the accepted-policy
11344        // set (a future `feira supervisor --restart …` CLI-side
11345        // arg-parse's "did you mean" hint, a future M4 admission-
11346        // webhook's per-child rejection body naming the accepted-
11347        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
11348        // projection consumers that iterate the accept-set for
11349        // diagnostic rendering) reads through this slice, so a future
11350        // arm addition that grows the enum but forgets to grow
11351        // [`Self::ALL`] silently truncates every downstream consumer's
11352        // accept-set at the same pre-addition boundary — this pin
11353        // fails at caixa-core build time on the pairwise-distinct +
11354        // arm-count invariants.
11355        //
11356        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
11357        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
11358        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
11359        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
11360        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
11361        // pins on the peer closed-set typed-enum axes.
11362        let all: &[RestartPolicy] = RestartPolicy::ALL;
11363        assert_eq!(
11364            all.len(),
11365            3,
11366            "RestartPolicy::ALL must enumerate every variant of the \
11367             three-arm closed set (Permanent, Temporary, Transient); \
11368             got {all:?}"
11369        );
11370        for (i, a) in all.iter().enumerate() {
11371            for (j, b) in all.iter().enumerate() {
11372                if i != j {
11373                    assert_ne!(
11374                        a, b,
11375                        "RestartPolicy::ALL must carry every variant exactly \
11376                         once — got duplicate {a:?} at indices {i} and {j}"
11377                    );
11378                }
11379            }
11380        }
11381        for variant in [
11382            RestartPolicy::Permanent,
11383            RestartPolicy::Temporary,
11384            RestartPolicy::Transient,
11385        ] {
11386            assert!(
11387                all.contains(&variant),
11388                "RestartPolicy::ALL must contain {variant:?} — a future arm \
11389                 addition that grows the enum but forgets to grow the ALL slice \
11390                 silently truncates every downstream consumer's accept-set at \
11391                 the pre-addition boundary"
11392            );
11393        }
11394    }
11395
11396    #[test]
11397    fn restart_policy_from_wire_accepts_every_lifted_constant() {
11398        // Fail-before-pass-after pin on the forward accept-set of the
11399        // [`RestartPolicy::from_wire`] reverse projection: every
11400        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
11401        // constant the [`RestartPolicy::as_str`] emitter walks parses
11402        // back to its paired variant. Any future arm addition that
11403        // grows the emitter's `as_str` match but forgets to grow the
11404        // parser's `from_wire` match silently splits the two halves of
11405        // the round-trip — the wire byte-string one non-serde consumer
11406        // parses from the one the emitter wrote — with the failure
11407        // surfacing at the operator's reconcile posture (a `:temporary`
11408        // `oneShot` child restarted on clean exit, a `:transient` child
11409        // restarted after clean completion) far from the rebrand
11410        // commit. Pinning the three-arm accept-set here catches the
11411        // drift at caixa-core build time.
11412        //
11413        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
11414        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
11415        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
11416        // accept-set pins on the peer closed-set typed-enum `str → Self`
11417        // axes.
11418        for (wire, expected) in [
11419            (
11420                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11421                RestartPolicy::Permanent,
11422            ),
11423            (
11424                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11425                RestartPolicy::Temporary,
11426            ),
11427            (
11428                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11429                RestartPolicy::Transient,
11430            ),
11431        ] {
11432            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11433                panic!(
11434                    "RestartPolicy::from_wire({wire:?}) must accept every \
11435                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
11436                     lifted canonical byte-string that RestartPolicy::{expected:?} \
11437                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
11438                )
11439            });
11440            assert_eq!(
11441                parsed, expected,
11442                "RestartPolicy::from_wire({wire:?}) must return \
11443                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
11444            );
11445        }
11446    }
11447
11448    #[test]
11449    fn restart_policy_from_wire_round_trips_through_as_str() {
11450        // Fail-before-pass-after pin on the closed round-trip between
11451        // the forward [`RestartPolicy::as_str`] emitter and the
11452        // reverse [`RestartPolicy::from_wire`] parser: for every
11453        // variant in [`RestartPolicy::ALL`], parsing the emitter's
11454        // output must return exactly the same variant. Any per-arm
11455        // divergence — a future arm added to `as_str` but not
11456        // `from_wire`, an accidental copy-paste flip in one but not
11457        // the other — silently splits the emit and parse halves and
11458        // the failure surfaces at consumer parse time far from the
11459        // drift site. The `ALL`-iterating shape means a future arm
11460        // addition picks up the coverage by construction.
11461        //
11462        // Peer of the sibling
11463        // [`restart_strategy_from_wire_round_trips_through_as_str`]
11464        // (4eec29c) round-trip pin on
11465        // [`RestartStrategy::from_wire`] and the M3
11466        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11467        // (18c7342) round-trip pin on
11468        // [`crate::aplicacao::PlacementStrategy::from_wire`].
11469        for &variant in RestartPolicy::ALL {
11470            let wire = variant.as_str();
11471            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11472                panic!(
11473                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11474                     must be Some({variant:?}) — the two halves of the round-trip \
11475                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11476                     got None on wire byte-string {wire:?}"
11477                )
11478            });
11479            assert_eq!(
11480                parsed, variant,
11481                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11482                 must round-trip to the same variant; got {parsed:?}"
11483            );
11484        }
11485    }
11486
11487    #[test]
11488    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11489        // Fail-before-pass-after pin on the closed-set refusal
11490        // discipline of [`RestartPolicy::from_wire`]: every
11491        // byte-string outside the three-arm accept-set returns `None`
11492        // rather than silently collapsing onto the [`Default`]
11493        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11494        // exercised here sweeps the load-bearing drift shapes: the
11495        // empty string (a stripped serde-attribute drift), all-
11496        // whitespace strings (the canonical text-editor accidental
11497        // padding shape), the kebab-case dispatcher-catalog identities
11498        // (`"permanent"` / `"temporary"` / `"transient"` — the
11499        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11500        // accept-set, which parses the *other* axis of this enum's
11501        // two-axis split and must not leak into the `from_wire`
11502        // PascalCase-wire accept-set — a lowercase leak here would
11503        // silently accept the operator's kebab-case
11504        // dispatcher-catalog probe under the wire-axis parser and mis-
11505        // route a `:permanent` intent), the padded canonical scalar
11506        // (`" Permanent "`), the trailing-newline shapes
11507        // (`"Permanent\n"`), the uppercase-single-word forms
11508        // (`"PERMANENT"`), and neighboring-but-unknown arms
11509        // (`"Restart"` — the canonical typo direction toward the
11510        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11511        //
11512        // Peer of the sibling
11513        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11514        // (4eec29c) +
11515        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11516        // (2aa6d23) +
11517        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11518        // (18c7342) refusal pins on the peer closed-set typed-enum
11519        // axes.
11520        for bad in [
11521            "",
11522            " ",
11523            "\n",
11524            "\t",
11525            "permanent",
11526            "temporary",
11527            "transient",
11528            "PERMANENT",
11529            "TEMPORARY",
11530            "TRANSIENT",
11531            "Permanents",
11532            "Permanent ",
11533            " Permanent",
11534            " Transient ",
11535            "Permanent\n",
11536            "perma",
11537            "Trans",
11538            "OneForOne",
11539            "Restart",
11540            "?",
11541        ] {
11542            assert!(
11543                RestartPolicy::from_wire(bad).is_none(),
11544                "RestartPolicy::from_wire({bad:?}) must return None — the \
11545                 parser's accept-set is exactly the three RestartPolicy::as_str \
11546                 outputs (Permanent, Temporary, Transient), and this \
11547                 byte-string is outside that closed set"
11548            );
11549        }
11550    }
11551
11552    #[test]
11553    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11554        // Fail-before-pass-after pin on the fourth path of the four-path
11555        // convergence: `from_wire` (the reverse projection) inverts the
11556        // `Serialize` derive's wire byte-string on every variant.
11557        // Together with the pre-existing three-path convergence
11558        // (`Display` + `as_str` + `Serialize` all resolve to the same
11559        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11560        // pinned by
11561        // [`restart_policy_display_matches_serialized_wire_byte_string`])
11562        // this closes the round-trip: the wire byte-string the
11563        // `Serialize` derive emits parses back to the same variant
11564        // through `from_wire`, so any future serde-attribute or variant-
11565        // rename drift on the emit half now surfaces as a matched drift
11566        // on the parse half at caixa-core build time — the two halves
11567        // migrate as a unit through the lifted consts on any future
11568        // rename, and the round-trip cannot silently split.
11569        //
11570        // Peer of the sibling
11571        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11572        // (4eec29c) wire-format pin on
11573        // [`RestartStrategy::from_wire`] and the M3
11574        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11575        // (18c7342) wire-format pin on
11576        // [`crate::aplicacao::PlacementStrategy::from_wire`].
11577        for &variant in RestartPolicy::ALL {
11578            let wire = serde_json::to_string(&variant).unwrap();
11579            let unquoted = wire
11580                .strip_prefix('"')
11581                .and_then(|s| s.strip_suffix('"'))
11582                .expect("serialized RestartPolicy is a JSON string");
11583            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
11584                panic!(
11585                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
11586                     Serialize derive's wire byte-string for \
11587                     RestartPolicy::{variant:?} — the four-path convergence \
11588                     (Display + as_str + Serialize + from_wire) resolves through \
11589                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
11590                )
11591            });
11592            assert_eq!(
11593                parsed, variant,
11594                "RestartPolicy::from_wire of the Serialize derive's wire \
11595                 byte-string for RestartPolicy::{variant:?} must round-trip \
11596                 to the same variant; got {parsed:?}"
11597            );
11598        }
11599    }
11600
11601    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
11602    //
11603    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
11604    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
11605    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
11606    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
11607    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
11608    // the peer per-`:upgrade-from :from` axis. The three pins jointly
11609    // brace the accessor against every future silent detour that would
11610    // desynchronize it from the raw `.caixa` field access every consumer
11611    // previously open-coded.
11612
11613    #[test]
11614    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
11615        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
11616        // [`ChildSpec::nome`] must return the `:children :caixa` field
11617        // byte-for-byte across every DNS-1123-label value the upstream
11618        // [`crate::render::require_valid_dns_1123_label`] gate at
11619        // `SupervisorSpec::validate` admits. Peer of the sibling
11620        // `membro_nome_returns_caixa_byte_equal_across_permutations`
11621        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
11622        // substrate-primitive accessor must byte-equal the raw field
11623        // access verbatim across every author-declared value" discipline
11624        // extended to the M2 supervisor-tree per-`:children` arm. Pins
11625        // against a future silent detour that re-normalized the child
11626        // identity (an accidental `.to_lowercase()` — every `:children
11627        // :caixa` is validated as a DNS-1123 label upstream, so any
11628        // re-normalization is redundant + a drift surface between the
11629        // validator and the accessor), a namespace-prefix rewrite (an
11630        // accidental `format!("{namespace}/{caixa}")` per-CR
11631        // fully-qualified rewrite that didn't land on the peer axes), or
11632        // a per-cluster alias stamp the future wasm-operator's
11633        // hierarchical reconciliation scheduler authors on one consumer
11634        // without the others. Five values sweep the accept-set the
11635        // DNS-1123 gate upstream admits (short single-word / dashed /
11636        // v-suffixed / mixed-digit child names).
11637        for name in [
11638            "worker",
11639            "cache-server",
11640            "scratch-job",
11641            "orders-v2",
11642            "session-8080",
11643        ] {
11644            let c = ChildSpec {
11645                caixa: name.into(),
11646                versao: "^0.1".into(),
11647                restart: RestartPolicy::Permanent,
11648            };
11649            assert_eq!(
11650                c.nome(),
11651                name,
11652                "ChildSpec::nome must return :children :caixa verbatim \
11653                 (got {:?}, expected {name:?})",
11654                c.nome(),
11655            );
11656            assert_eq!(
11657                c.nome(),
11658                c.caixa.as_str(),
11659                "ChildSpec::nome must byte-equal the .caixa field access",
11660            );
11661        }
11662    }
11663
11664    #[test]
11665    fn child_spec_nome_borrows_from_caixa_storage() {
11666        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
11667        // `&str` slice that borrows from the typed slot's own [`String`]
11668        // storage — same-address invariant with `c.caixa.as_str()`. Pins
11669        // against a future silent detour that allocated a fresh `String`
11670        // (`self.caixa.clone()` in the body would type-check but silently
11671        // drop the borrow, and every downstream consumer that assumed
11672        // the returned slice outlives `&self` would break on a stale-
11673        // reference use-after-free — the [`crate::render::insert_first_seen`]
11674        // dedup key at [`SupervisorSpec::validate`], the
11675        // [`validate_no_self_supervision`] equality check against the
11676        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
11677        // borrow — each would silently misbehave if this accessor
11678        // produced a detached copy). Peer of the sibling
11679        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
11680        // M3 per-`:membros` axis and the
11681        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
11682        // first M2 slot scalar accessor.
11683        let c = ChildSpec {
11684            caixa: "worker".into(),
11685            versao: "^0.1".into(),
11686            restart: RestartPolicy::Permanent,
11687        };
11688        let name = c.nome();
11689        let caixa_slice = c.caixa.as_str();
11690        assert_eq!(
11691            name.as_ptr(),
11692            caixa_slice.as_ptr(),
11693            "ChildSpec::nome must borrow from the .caixa String's backing \
11694             storage — a fresh allocation here means the accessor no \
11695             longer names the substrate-primitive typed dispatch and \
11696             every downstream consumer would silently carry a detached \
11697             copy",
11698        );
11699        assert_eq!(
11700            name.len(),
11701            caixa_slice.len(),
11702            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
11703             as well as in address",
11704        );
11705    }
11706
11707    #[test]
11708    fn validate_gates_child_nome_through_lifted_accessor() {
11709        // Bilateral coherence pin: every `:children :caixa` that
11710        // [`SupervisorSpec::validate`] accepts is one
11711        // [`crate::render::require_valid_dns_1123_label`] accepts on the
11712        // accessor-projected value, and vice versa on the reject side.
11713        // This closes the "the validator reads through the accessor"
11714        // contract structurally — a future silent detour that made the
11715        // accessor return a different byte-string than the validator
11716        // gates against would surface here as a coverage mismatch, not
11717        // as an apply-time DNS-1123 rejection at
11718        // `metadata.name: Invalid value` far from the caixa.lisp source.
11719        // Peer of the M2 sibling
11720        // `validate_parses_prior_versao_through_lifted_accessor`
11721        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
11722        // `validate_membros` peer discipline.
11723        //
11724        // Accept-set sweep: five DNS-1123-label values the upstream gate
11725        // admits.
11726        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
11727            let s = SupervisorSpec {
11728                children: vec![ChildSpec {
11729                    caixa: ok_name.into(),
11730                    versao: "^0.1".into(),
11731                    restart: RestartPolicy::Permanent,
11732                }],
11733                ..SupervisorSpec::default()
11734            };
11735            s.validate().unwrap_or_else(|e| {
11736                panic!(
11737                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
11738                     (upstream DNS-1123 gate accepts it): got {e:?}",
11739                );
11740            });
11741            let c = ChildSpec {
11742                caixa: ok_name.into(),
11743                versao: "^0.1".into(),
11744                restart: RestartPolicy::Permanent,
11745            };
11746            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
11747                .unwrap_or_else(|()| {
11748                    panic!(
11749                        "require_valid_dns_1123_label must accept the accessor-projected \
11750                     :children :caixa {ok_name:?}",
11751                    );
11752                });
11753        }
11754        // Reject-set sweep: five DNS-1123-label-violating shapes the
11755        // upstream gate refuses (empty / uppercase / underscore / dot /
11756        // leading-hyphen). Every rejection at the validator must
11757        // correspond to a rejection when the accessor's projected value
11758        // is fed back through the shared gate.
11759        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
11760            let s = SupervisorSpec {
11761                children: vec![ChildSpec {
11762                    caixa: bad_name.into(),
11763                    versao: "^0.1".into(),
11764                    restart: RestartPolicy::Permanent,
11765                }],
11766                ..SupervisorSpec::default()
11767            };
11768            let err = s.validate().unwrap_err();
11769            assert!(
11770                matches!(
11771                    err,
11772                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
11773                ),
11774                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
11775                 via the DNS-1123 gate: got {err:?}",
11776            );
11777            let c = ChildSpec {
11778                caixa: bad_name.into(),
11779                versao: "^0.1".into(),
11780                restart: RestartPolicy::Permanent,
11781            };
11782            assert!(
11783                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
11784                    .is_err(),
11785                "require_valid_dns_1123_label must reject the accessor-projected \
11786                 :children :caixa {bad_name:?}",
11787            );
11788        }
11789    }
11790
11791    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
11792    //
11793    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
11794    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
11795    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
11796    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
11797    // trio on the peer per-`:children` `String`-carry axis. The three pins
11798    // jointly brace the accessor against every future silent detour that
11799    // would desynchronize it from the raw `.versao` field access the
11800    // requirement gate + error carrier previously open-coded.
11801    //
11802    // Closes the last unlifted per-`:children` `String`-carry axis: the
11803    // pair (`nome`, `versao_requirement`) now jointly projects the
11804    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
11805    // consumer that fans on per-child identity + version pin reads,
11806    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
11807    // pair discipline verbatim.
11808    #[test]
11809    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
11810        // The canonical per-`:children` child-`:versao`-scalar pin:
11811        // [`ChildSpec::versao_requirement`] must return the `:children
11812        // :versao` field byte-for-byte across every Cargo-shaped semver
11813        // requirement value the upstream
11814        // [`crate::render::require_valid_versao_requirement`] gate admits.
11815        // Peer of the sibling
11816        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
11817        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
11818        // substrate-primitive accessor must byte-equal the raw field
11819        // access verbatim across every author-declared value" discipline
11820        // extended to the M2 supervisor-tree per-`:children` arm. Pins
11821        // against a future silent detour that re-canonicalized the
11822        // requirement (an accidental `.to_string()` via
11823        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
11824        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
11825        // silently drifted the error carrier's quoted requirement away
11826        // from the source `caixa.lisp`, an accidental whitespace trim on
11827        // `"^ 0.1"` that no consumer ever produced from the field-access
11828        // side, an accidental per-cluster lacre-projected concrete-version
11829        // rewrite that didn't land on the peer requirement-gate call).
11830        // Five values sweep the accept-set the shared
11831        // [`crate::render::require_valid_versao_requirement`] gate admits
11832        // (caret / tilde / exact / wildcard / bare-major).
11833        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11834            let c = ChildSpec {
11835                caixa: "worker".into(),
11836                versao: req.into(),
11837                restart: RestartPolicy::Permanent,
11838            };
11839            assert_eq!(
11840                c.versao_requirement(),
11841                req,
11842                "ChildSpec::versao_requirement must return :children :versao \
11843                 verbatim (got {:?}, expected {req:?})",
11844                c.versao_requirement(),
11845            );
11846            assert_eq!(
11847                c.versao_requirement(),
11848                c.versao.as_str(),
11849                "ChildSpec::versao_requirement must byte-equal the .versao \
11850                 field access",
11851            );
11852        }
11853    }
11854
11855    #[test]
11856    fn child_spec_versao_requirement_borrows_from_versao_storage() {
11857        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
11858        // return a `&str` slice that borrows from the typed slot's own
11859        // [`String`] storage — same-address invariant with
11860        // `c.versao.as_str()`. Pins against a future silent detour that
11861        // allocated a fresh `String` (`self.versao.clone()` in the body
11862        // would type-check but silently drop the borrow, and every
11863        // downstream consumer that assumed the returned slice outlives
11864        // `&self` — the [`crate::render::require_valid_versao_requirement`]
11865        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
11866        // `.to_string()` carrier's byte-length assumption — would silently
11867        // misbehave if this accessor produced a detached copy). Peer of
11868        // the sibling `child_spec_nome_borrows_from_caixa_storage`
11869        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
11870        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
11871        // pin on the peer per-`:membros` `:versao` axis.
11872        let c = ChildSpec {
11873            caixa: "worker".into(),
11874            versao: "^0.1".into(),
11875            restart: RestartPolicy::Permanent,
11876        };
11877        let req = c.versao_requirement();
11878        let versao_slice = c.versao.as_str();
11879        assert_eq!(
11880            req.as_ptr(),
11881            versao_slice.as_ptr(),
11882            "ChildSpec::versao_requirement must borrow from the .versao \
11883             String's backing storage — a fresh allocation here means the \
11884             accessor no longer names the substrate-primitive typed \
11885             dispatch and every downstream consumer would silently carry \
11886             a detached copy",
11887        );
11888        assert_eq!(
11889            req.len(),
11890            versao_slice.len(),
11891            "ChildSpec::versao_requirement and .versao.as_str() must \
11892             byte-equal in length as well as in address",
11893        );
11894    }
11895
11896    #[test]
11897    fn validate_gates_child_versao_through_lifted_accessor() {
11898        // Bilateral coherence pin: every `:children :versao` that
11899        // [`SupervisorSpec::validate`] accepts is one
11900        // [`crate::render::require_valid_versao_requirement`] accepts on
11901        // the accessor-projected value, and vice versa on the reject side.
11902        // This closes the "the validator reads through the accessor"
11903        // contract structurally — a future silent detour that made the
11904        // accessor return a different byte-string than the validator gates
11905        // against would surface here as a coverage mismatch, not as a
11906        // resolver-time semver-parse rejection at lacre-closure time far
11907        // from the caixa.lisp source. Peer of the sibling
11908        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
11909        // the per-`:children :caixa` axis and the M2
11910        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
11911        // on the peer per-`:upgrade-from :from` axis.
11912        //
11913        // Accept-set sweep: five Cargo-shaped semver requirement values
11914        // the upstream gate admits (caret / tilde / exact / wildcard /
11915        // bare-major).
11916        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11917            let s = SupervisorSpec {
11918                children: vec![ChildSpec {
11919                    caixa: "worker".into(),
11920                    versao: ok_req.into(),
11921                    restart: RestartPolicy::Permanent,
11922                }],
11923                ..SupervisorSpec::default()
11924            };
11925            s.validate().unwrap_or_else(|e| {
11926                panic!(
11927                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
11928                     (upstream versao-requirement gate accepts it): got {e:?}",
11929                );
11930            });
11931            let c = ChildSpec {
11932                caixa: "worker".into(),
11933                versao: ok_req.into(),
11934                restart: RestartPolicy::Permanent,
11935            };
11936            crate::render::require_valid_versao_requirement(
11937                c.versao_requirement(),
11938                || (),
11939                |_reason| (),
11940            )
11941            .unwrap_or_else(|()| {
11942                panic!(
11943                    "require_valid_versao_requirement must accept the accessor-projected \
11944                     :children :versao {ok_req:?}",
11945                );
11946            });
11947        }
11948        // Reject-set sweep: five requirement-violating shapes the upstream
11949        // gate refuses. The empty string closes the empty-first arm of the
11950        // shared [`crate::render::require_valid_versao_requirement`]
11951        // cascade; the four non-empty arms exercise distinct semver-parse
11952        // failure modes the M3 peer per-`:membros` reject-set already pins
11953        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
11954        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
11955        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
11956        // shared parser routing means the same reject-set must fail
11957        // identically at the M2 supervisor-tree per-`:children` accessor
11958        // arm here. Every rejection at the validator must correspond to a
11959        // rejection when the accessor's projected value is fed back
11960        // through the shared gate.
11961        //
11962        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
11963        // `"not-a-semver"` are intentionally *not* in the reject-set: the
11964        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
11965        // and the identifier-tail arm's grammar admits some non-canonical
11966        // shapes — matching what the M3 peer test suite already documents
11967        // as the shared parser's accept-set edges.)
11968        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
11969            let s = SupervisorSpec {
11970                children: vec![ChildSpec {
11971                    caixa: "worker".into(),
11972                    versao: bad_req.into(),
11973                    restart: RestartPolicy::Permanent,
11974                }],
11975                ..SupervisorSpec::default()
11976            };
11977            let err = s.validate().unwrap_err();
11978            assert!(
11979                matches!(
11980                    err,
11981                    SupervisorError::EmptyChildVersion { .. }
11982                        | SupervisorError::ChildVersaoInvalid { .. }
11983                ),
11984                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
11985                 via the versao-requirement gate: got {err:?}",
11986            );
11987            let c = ChildSpec {
11988                caixa: "worker".into(),
11989                versao: bad_req.into(),
11990                restart: RestartPolicy::Permanent,
11991            };
11992            assert!(
11993                crate::render::require_valid_versao_requirement(
11994                    c.versao_requirement(),
11995                    || (),
11996                    |_reason| (),
11997                )
11998                .is_err(),
11999                "require_valid_versao_requirement must reject the accessor-projected \
12000                 :children :versao {bad_req:?}",
12001            );
12002        }
12003    }
12004
12005    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
12006    //
12007    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
12008    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
12009    // already project the `String`-carry `(caixa, versao)` fields; the
12010    // `Copy`-composite-enum `restart` field is the third and final axis).
12011    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
12012    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
12013    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
12014    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
12015    // strategy scalar accessor — same "one typed dispatch on the substrate
12016    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
12017    // extended onto the M2 supervisor-slot per-`:children` restart-decision
12018    // axis. The pin below covers the accessor's byte-equal projection
12019    // against the raw field access across every variant in the closed
12020    // accept-set (`Permanent`, `Transient`, `Temporary`).
12021
12022    #[test]
12023    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
12024        // The canonical per-`:children` restart-decision-policy-scalar
12025        // pin: [`ChildSpec::restart`] must return the `:children :restart`
12026        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
12027        // typed slot's own [`RestartPolicy`] storage across every variant
12028        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
12029        // Pins against a future silent detour that re-derived the policy
12030        // from a peer axis (an accidental fallback to
12031        // `if is_supervisor_child { Permanent } else { Temporary }` that
12032        // collapsed the child's kind axis into the restart discriminator),
12033        // a variant remap the operator authors on one consumer without the
12034        // other, or a stale-derive detour that substituted
12035        // [`RestartPolicy::default`] when the field held any explicit
12036        // variant (which would silently collapse the distinction between
12037        // "author explicitly declared `:restart Permanent`" and "author
12038        // omitted the slot and inherited the default" the future
12039        // per-cluster restart-decision override slot depends on).
12040        //
12041        // Peer of the sibling per-`:supervisor`
12042        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12043        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
12044        // axis and the M3
12045        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12046        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
12047        // — same "the substrate-primitive accessor must byte-equal the raw
12048        // field access verbatim across every author-declared value"
12049        // discipline extended onto the M2 supervisor-slot per-`:children`
12050        // restart-decision-policy axis, closing the last unlifted axis on
12051        // the per-`:children` [`ChildSpec`] type.
12052        for restart in [
12053            RestartPolicy::Permanent,
12054            RestartPolicy::Transient,
12055            RestartPolicy::Temporary,
12056        ] {
12057            let c = ChildSpec {
12058                caixa: "worker".into(),
12059                versao: "^0.1".into(),
12060                restart,
12061            };
12062            assert_eq!(
12063                c.restart(),
12064                restart,
12065                "ChildSpec::restart must return :children :restart \
12066                 verbatim (got {:?}, expected {restart:?})",
12067                c.restart(),
12068            );
12069            assert_eq!(
12070                c.restart(),
12071                c.restart,
12072                "ChildSpec::restart accessor and .restart field access \
12073                 must byte-equal — the accessor is the substrate-primitive \
12074                 typed dispatch every downstream per-child restart-\
12075                 decision consumer must route through",
12076            );
12077        }
12078    }
12079
12080    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
12081    //
12082    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
12083    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
12084    // distribution-strategy accessor discipline onto the M2 supervisor-slot
12085    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
12086    // scalar axis. The two pins below cover (1) the accessor's byte-equal
12087    // projection against the raw field access across every variant in the
12088    // closed accept-set, and (2) the two-consumer coherence between the
12089    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
12090    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
12091    // carrier's `estrategia:` field — peer of the sibling M3
12092    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12093    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
12094    // pair on the per-`:placement` distribution-strategy axis.
12095
12096    #[test]
12097    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
12098        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
12099        // pin: [`SupervisorSpec::estrategia`] must return the
12100        // `:supervisor :estrategia` field verbatim as a
12101        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
12102        // [`RestartStrategy`] storage across every variant in the closed
12103        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
12104        // `SimpleOneForOne`). Pins against a future silent detour that
12105        // re-derived the strategy from a peer axis (an accidental
12106        // fallback to `if children.is_empty() { SimpleOneForOne } else {
12107        // OneForOne }` collapse that read the children-count axis into
12108        // the strategy discriminator), a variant remap the operator
12109        // authors on one consumer without the other, or a stale-derive
12110        // detour that substituted [`RestartStrategy::default`] when the
12111        // field held any explicit variant (which would silently collapse
12112        // the distinction between "author explicitly declared
12113        // `:estrategia OneForOne`" and "author omitted the slot and
12114        // inherited the default" the future per-cluster strategy override
12115        // slot depends on). Peer of the sibling M3
12116        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12117        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
12118        // axis — same "the substrate-primitive accessor must byte-equal
12119        // the raw field access verbatim across every author-declared
12120        // value" discipline extended onto the M2 supervisor-slot
12121        // per-`:supervisor` sibling-restart-strategy axis.
12122        for &estrategia in RestartStrategy::ALL {
12123            // `SimpleOneForOne` requires `children.is_empty()`; the peer
12124            // three strategies require a non-empty static children list.
12125            // Build each shape coherently so the pin's fixture would
12126            // itself pass [`SupervisorSpec::validate`] once fed through
12127            // the sibling coherence pin below — the byte-equal projection
12128            // asserted here is a strictly weaker property (a `Copy` field
12129            // read) that does not depend on `validate` running, but
12130            // keeping the fixture validate-clean means a future extension
12131            // of the pin to exercise `validate` end-to-end does not have
12132            // to re-author the children shape.
12133            //
12134            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
12135            // shape partition through the [`gen_platform::IsVariant`]
12136            // derive-generated
12137            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
12138            // than the raw `matches!(estrategia, RestartStrategy::
12139            // SimpleOneForOne)` open-coded pattern-match — same closed-
12140            // set-typed-enum arm-discriminator dispatch discipline the
12141            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
12142            // convergence (915a934) extended onto its two paired positive
12143            // / negated `matches!` sites and the peer
12144            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
12145            // predicate convergence (766ec63) extended onto the M3 mesh-
12146            // slot per-`:placement` distribution-strategy discriminator
12147            // axis. See the sibling `round_trip_all_strategies` and the
12148            // peer `manifest::tests::
12149            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
12150            // fixture for the two peer sites the same lift closes on.
12151            let children = if estrategia.is_simple_one_for_one() {
12152                Vec::new()
12153            } else {
12154                vec![ChildSpec {
12155                    caixa: "worker".into(),
12156                    versao: "^0.1".into(),
12157                    restart: RestartPolicy::Permanent,
12158                }]
12159            };
12160            let s = SupervisorSpec {
12161                estrategia,
12162                children,
12163                ..SupervisorSpec::default()
12164            };
12165            assert_eq!(
12166                s.estrategia(),
12167                estrategia,
12168                "SupervisorSpec::estrategia must return :supervisor :estrategia \
12169                 verbatim (got {:?}, expected {estrategia:?})",
12170                s.estrategia(),
12171            );
12172            assert_eq!(
12173                s.estrategia(),
12174                s.estrategia,
12175                "SupervisorSpec::estrategia accessor and .estrategia field \
12176                 access must byte-equal — the accessor is the substrate-\
12177                 primitive typed dispatch every downstream sibling-restart-\
12178                 strategy consumer must route through",
12179            );
12180        }
12181    }
12182
12183    #[test]
12184    fn validate_reads_through_lifted_estrategia_accessor() {
12185        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
12186        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
12187        // dispatch (which reads through [`SupervisorSpec::estrategia`]
12188        // to fan across the strategy-arm shape-gate cascades) and the
12189        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
12190        // error carrier's `estrategia:` field (which reads through
12191        // [`SupervisorSpec::estrategia`] to name the strategy the empty
12192        // `:children` list was declared against) must both key off the
12193        // lifted accessor, so any future rebrand on the typed slot's
12194        // reader shape lands at exactly one place. Pins the two-site
12195        // coherence by exercising the `NoChildren` error surface end-to-
12196        // end across every non-`SimpleOneForOne` variant and asserting
12197        // the surfaced `estrategia:` field byte-equals the accessor's
12198        // return. Peer of the sibling M3
12199        // `validate_placement_reads_through_lifted_estrategia_accessor`
12200        // (921fe1b) three-consumer coherence pin on the per-`:placement`
12201        // distribution-strategy axis.
12202        for estrategia in [
12203            RestartStrategy::OneForOne,
12204            RestartStrategy::OneForAll,
12205            RestartStrategy::RestForOne,
12206        ] {
12207            let s = SupervisorSpec {
12208                estrategia,
12209                children: Vec::new(),
12210                ..SupervisorSpec::default()
12211            };
12212            let err = s.validate().unwrap_err();
12213            match err {
12214                SupervisorError::NoChildren { estrategia: e } => {
12215                    assert_eq!(
12216                        e,
12217                        s.estrategia(),
12218                        "NoChildren.estrategia must byte-equal \
12219                         SupervisorSpec::estrategia() — the empty-`:children` \
12220                         refusal reads through the lifted accessor",
12221                    );
12222                    assert_eq!(
12223                        e, estrategia,
12224                        "NoChildren.estrategia must carry the author-declared \
12225                         :supervisor :estrategia variant verbatim (got {e:?}, \
12226                         expected {estrategia:?})",
12227                    );
12228                }
12229                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
12230            }
12231        }
12232    }
12233
12234    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
12235    //
12236    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
12237    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
12238    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
12239    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
12240    // The two pins below cover (1) the accessor's byte-equal projection
12241    // against the raw field access across every representative value in
12242    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
12243    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
12244    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
12245    // zero-floor / cap composition — the validate gate and the accessor
12246    // must route through the same substrate-primitive typed dispatch, so
12247    // any future silent detour that had the accessor perform a
12248    // bounds-collapsing clamp would fail here at caixa-core build time.
12249    // Peer of the sibling M3
12250    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12251    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
12252
12253    #[test]
12254    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
12255        // The canonical per-`:supervisor` restart-budget-count scalar pin:
12256        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
12257        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
12258        // typed slot's own `u32` storage, byte-equal to the raw field
12259        // access across every representative value in the accept-set —
12260        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
12261        // accept-set the surrounding [`SupervisorSpec::validate`] gate
12262        // carves out on the sibling `ZeroMaxRestarts` refusal),
12263        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
12264        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
12265        // (a past-the-guard sentinel that pins the accessor doesn't
12266        // perform a silent bounds-collapse into `1` on the zero arm —
12267        // validate rejects zero but the accessor must ship the raw slot
12268        // verbatim so a validate-time gate regression surfaces at the
12269        // emit boundary rather than being silently absorbed), `u32::MAX`
12270        // (a past-the-guard sentinel that pins the accessor doesn't
12271        // perform a silent bounds-collapse through
12272        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
12273        //
12274        // Peer of the sibling M3
12275        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12276        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
12277        // required-scalar axis — same "the substrate-primitive accessor
12278        // must byte-equal the raw field access verbatim across every
12279        // value in the `u32` accept-set" discipline extended onto the M2
12280        // supervisor-slot per-`:supervisor` restart-budget-count axis.
12281        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
12282            let s = SupervisorSpec {
12283                max_restarts,
12284                ..SupervisorSpec::default()
12285            };
12286            assert_eq!(
12287                s.max_restarts(),
12288                max_restarts,
12289                "SupervisorSpec::max_restarts must return :supervisor \
12290                 :max-restarts verbatim (got {}, expected {max_restarts})",
12291                s.max_restarts(),
12292            );
12293            assert_eq!(
12294                s.max_restarts(),
12295                s.max_restarts,
12296                "SupervisorSpec::max_restarts accessor and .max_restarts \
12297                 field access must byte-equal — the accessor is the \
12298                 substrate-primitive typed dispatch every downstream \
12299                 restart-budget-count consumer must route through",
12300            );
12301        }
12302    }
12303
12304    #[test]
12305    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
12306        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
12307        // zero-floor + upper-cap bracket must key off
12308        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
12309        // field access. Structurally: a `SupervisorSpec { max_restarts:
12310        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
12311        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
12312        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
12313        // (with the offending count carried verbatim from the accessor
12314        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
12315        // lower boundary of the accept-set) plus a `SupervisorSpec {
12316        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
12317        // boundary) must pass validate. The four together jointly pin the
12318        // accessor + validate-gate composition: any future silent detour
12319        // that had the accessor return a fresh `1` on the zero arm (a
12320        // `.max_restarts().max(1)` collapse) would silently absorb the
12321        // `ZeroMaxRestarts` refusal at the accessor boundary and the
12322        // validate gate would accept a struct-literal `SupervisorSpec {
12323        // max_restarts: 0, .. }` — the composition pin catches that at
12324        // caixa-core build time.
12325        //
12326        // Peer of the sibling M3
12327        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
12328        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
12329        // composition axis — same "the validate / shape-gate predicate
12330        // must route through the substrate-primitive typed dispatch"
12331        // discipline extended onto the peer M2 supervisor-slot
12332        // required-`u32` composition axis.
12333        let child = ChildSpec {
12334            caixa: "worker".into(),
12335            versao: "^0.1".into(),
12336            restart: RestartPolicy::Permanent,
12337        };
12338        // Zero-floor arm.
12339        let s = SupervisorSpec {
12340            max_restarts: 0,
12341            children: vec![child.clone()],
12342            ..SupervisorSpec::default()
12343        };
12344        assert_eq!(
12345            s.validate().unwrap_err(),
12346            SupervisorError::ZeroMaxRestarts,
12347            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
12348             — the accessor and the validate gate must route through the \
12349             same substrate-primitive typed dispatch on the zero-floor arm",
12350        );
12351        // Cap arm — the surfaced `max_restarts:` field must byte-equal
12352        // the accessor's return so a future rebrand on the accessor
12353        // lands in the diagnostic without a coordinated rewrite.
12354        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12355        let s = SupervisorSpec {
12356            max_restarts: over_cap,
12357            children: vec![child.clone()],
12358            ..SupervisorSpec::default()
12359        };
12360        match s.validate().unwrap_err() {
12361            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
12362                assert_eq!(
12363                    max_restarts,
12364                    s.max_restarts(),
12365                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
12366                     SupervisorSpec::max_restarts() — the cap-arm refusal \
12367                     reads through the lifted accessor",
12368                );
12369                assert_eq!(
12370                    max_restarts, over_cap,
12371                    "MaxRestartsExceedsCap.max_restarts must carry the \
12372                     author-declared :supervisor :max-restarts value \
12373                     verbatim (got {max_restarts}, expected {over_cap})",
12374                );
12375            }
12376            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
12377        }
12378        // Lower + upper accept-set boundaries.
12379        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
12380            let s = SupervisorSpec {
12381                max_restarts,
12382                children: vec![child.clone()],
12383                ..SupervisorSpec::default()
12384            };
12385            assert!(
12386                s.validate().is_ok(),
12387                "validate must accept max_restarts == {max_restarts} \
12388                 (an accept-set boundary of \
12389                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
12390            );
12391        }
12392    }
12393
12394    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
12395    //
12396    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
12397    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
12398    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
12399    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
12400    // supervisor-slot per-`:supervisor` restart-intensity-denominator
12401    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
12402    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
12403    // per-`:supervisor` scalar-value axis. The three pins below cover
12404    // (1) the accessor's byte-equal projection against the raw field
12405    // access across every representative value in the `Option<Duration>`
12406    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
12407    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
12408    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
12409    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
12410    // `if let Some(w) = self.restart_window() { … }` bracket-arm
12411    // composition — the validate gate and the accessor must route through
12412    // the same substrate-primitive typed dispatch, so any future silent
12413    // detour that had the accessor perform a bounds-collapsing clamp
12414    // would fail here at caixa-core build time, and (3) the accessor's
12415    // by-copy idempotence pin — the returned `Option<Duration>` must
12416    // outlive `&self` and two successive calls must return byte-equal
12417    // values. Peer of the sibling M2
12418    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12419    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
12420    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12421    // (7073d0f) pin on the per-`:politicas :timeout` axis.
12422
12423    #[test]
12424    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
12425        // The canonical per-`:supervisor` restart-intensity-denominator
12426        // scalar pin: [`SupervisorSpec::restart_window`] must return the
12427        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
12428        // `Option<Duration>`, `Copy`-projected from the typed slot's own
12429        // `Option<Duration>` storage, byte-equal to the raw field access
12430        // across every representative value in the accept-set — `None`
12431        // (the "never reset — every restart across the supervisor's
12432        // lifetime counts against the sibling `:max-restarts` budget"
12433        // sentinel the field's own docstring names and the peer
12434        // `validate_accepts_none_restart_window` pin locks in on the
12435        // [`SupervisorSpec::validate`] entry-side),
12436        // `Some(Duration::from_millis(1))` (the structural minimum a
12437        // validated `:restart-window` may carry, the integer-millisecond
12438        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
12439        // everything sub-ms; `Duration::ZERO` is separately rejected by
12440        // [`SupervisorError::RestartWindowZero`]),
12441        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
12442        // surrounding [`SupervisorSpec::validate`] gate carves out on the
12443        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
12444        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
12445        // accessor doesn't perform a silent bounds-collapse into `None` on
12446        // the zero-Duration arm — validate rejects zero but the accessor
12447        // must ship the raw slot verbatim so a validate-time gate
12448        // regression surfaces at the emit boundary rather than being
12449        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12450        // sentinel that pins the accessor doesn't perform a silent
12451        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12452        // return path).
12453        //
12454        // Peer of the sibling M2
12455        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12456        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12457        // sibling M3
12458        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12459        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12460        // substrate-primitive accessor must byte-equal the raw field
12461        // access verbatim across every value in the `Option<Duration>`
12462        // accept-set" discipline extended onto the M2 supervisor-slot
12463        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12464        // silent detour that re-derived the restart-window from a peer
12465        // axis (an accidental `.max_restarts.into()` collapse that read
12466        // the restart-budget-count as a duration — the two axes serve
12467        // different halves of the `MaxIntensity / Period` restart-
12468        // intensity ratio, and confusing them silently inverts the
12469        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12470        // "zero means never reset" collapse (the canonical
12471        // `Option<Duration>` → `Duration` collapse footgun the
12472        // [`SupervisorError::RestartWindowZero`] validate arm guards on
12473        // the peer zero-floor axis; a zero period either trips on the
12474        // first failure or never trips depending on operator
12475        // interpretation, neither of which is the author's "never reset"
12476        // intent that `None` expresses structurally), or a per-arm
12477        // variant swap that landed on one consumer without the other.
12478        for restart_window in [
12479            None,
12480            Some(Duration::from_millis(1)),
12481            Some(SUPERVISOR_RESTART_WINDOW_MAX),
12482            Some(Duration::ZERO),
12483            Some(Duration::MAX),
12484        ] {
12485            let s = SupervisorSpec {
12486                restart_window,
12487                ..SupervisorSpec::default()
12488            };
12489            assert_eq!(
12490                s.restart_window(),
12491                restart_window,
12492                "SupervisorSpec::restart_window must return :supervisor \
12493                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12494                s.restart_window(),
12495            );
12496            assert_eq!(
12497                s.restart_window(),
12498                s.restart_window,
12499                "SupervisorSpec::restart_window accessor and \
12500                 .restart_window field access must byte-equal — the \
12501                 accessor is the substrate-primitive typed dispatch every \
12502                 downstream restart-intensity-denominator consumer must \
12503                 route through",
12504            );
12505        }
12506    }
12507
12508    #[test]
12509    fn validate_restart_window_bracket_arm_routes_through_accessor() {
12510        // Composition pin: [`SupervisorSpec::validate`]'s
12511        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12512        // zero-floor + integer-millisecond canonical-form + upper-cap
12513        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12514        // the raw `.restart_window` field access. Structurally: a
12515        // `SupervisorSpec { restart_window: None, .. }` must pass the
12516        // arm gate structurally (the `if let Some(_)` shape returns
12517        // early on the `None` arm — the accessor and the validate gate
12518        // must agree on `None → skip the bracket cascade` so an authored
12519        // `:restart-window ()` structurally routes through the "never
12520        // reset" sentinel path), a `SupervisorSpec { restart_window:
12521        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12522        // refusal exactly, a `SupervisorSpec { restart_window:
12523        // Some(Duration::from_micros(1500)), .. }` must surface the
12524        // `RestartWindowNotCanonical` refusal exactly (with the offending
12525        // duration carried verbatim from the accessor return), a
12526        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12527        // + Duration::from_millis(1)), .. }` must surface the
12528        // `RestartWindowExceedsCap` refusal exactly (with the offending
12529        // duration carried verbatim from the accessor return), and a
12530        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12531        // .. }` (the lower boundary of the accept-set) plus a
12532        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12533        // .. }` (the upper boundary) must pass validate. The six together
12534        // jointly pin the accessor + validate-gate composition: any future
12535        // silent detour that had the accessor return a fresh `None` on any
12536        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12537        // collapse) would silently absorb the `RestartWindowZero` refusal
12538        // at the accessor boundary and the validate gate would accept a
12539        // struct-literal `SupervisorSpec { restart_window:
12540        // Some(Duration::ZERO), .. }` — the composition pin catches that
12541        // at caixa-core build time.
12542        //
12543        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12544        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12545        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12546        // accessor-composition pin on the per-`:politicas :timeout` axis —
12547        // same "the validate / shape-gate predicate must route through
12548        // the substrate-primitive typed dispatch" discipline extended
12549        // onto the peer M2 supervisor-slot optional-`Duration` axis.
12550        let child = ChildSpec {
12551            caixa: "worker".into(),
12552            versao: "^0.1".into(),
12553            restart: RestartPolicy::Permanent,
12554        };
12555        // None arm — must not surface any :restart-window-shaped refusal;
12556        // the `if let Some(_)` bracket returns early on `None` structurally.
12557        let s = SupervisorSpec {
12558            restart_window: None,
12559            children: vec![child.clone()],
12560            ..SupervisorSpec::default()
12561        };
12562        assert!(
12563            s.validate().is_ok(),
12564            "validate must accept restart_window: None (the never-reset \
12565             sentinel) — the `if let Some(_)` bracket returns early on \
12566             the None arm and the accessor must agree",
12567        );
12568        // Zero-floor arm.
12569        let s = SupervisorSpec {
12570            restart_window: Some(Duration::ZERO),
12571            children: vec![child.clone()],
12572            ..SupervisorSpec::default()
12573        };
12574        assert_eq!(
12575            s.validate().unwrap_err(),
12576            SupervisorError::RestartWindowZero,
12577            "validate must reject restart_window == Some(Duration::ZERO) \
12578             with RestartWindowZero — the accessor and the validate gate \
12579             must route through the same substrate-primitive typed \
12580             dispatch on the zero-floor arm",
12581        );
12582        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
12583        // byte-equal the accessor's return so a future rebrand on the
12584        // accessor lands in the diagnostic without a coordinated rewrite.
12585        let sub_ms = Duration::from_micros(1500);
12586        let s = SupervisorSpec {
12587            restart_window: Some(sub_ms),
12588            children: vec![child.clone()],
12589            ..SupervisorSpec::default()
12590        };
12591        match s.validate().unwrap_err() {
12592            SupervisorError::RestartWindowNotCanonical { window } => {
12593                assert_eq!(
12594                    Some(window),
12595                    s.restart_window(),
12596                    "RestartWindowNotCanonical.window must byte-equal \
12597                     SupervisorSpec::restart_window().unwrap() — the \
12598                     non-canonical-arm refusal reads through the lifted \
12599                     accessor",
12600                );
12601                assert_eq!(
12602                    window, sub_ms,
12603                    "RestartWindowNotCanonical.window must carry the \
12604                     author-declared :supervisor :restart-window value \
12605                     verbatim (got {window:?}, expected {sub_ms:?})",
12606                );
12607            }
12608            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
12609        }
12610        // Cap arm — the surfaced `window:` field must byte-equal the
12611        // accessor's return.
12612        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12613        let s = SupervisorSpec {
12614            restart_window: Some(over_cap),
12615            children: vec![child.clone()],
12616            ..SupervisorSpec::default()
12617        };
12618        match s.validate().unwrap_err() {
12619            SupervisorError::RestartWindowExceedsCap { window } => {
12620                assert_eq!(
12621                    Some(window),
12622                    s.restart_window(),
12623                    "RestartWindowExceedsCap.window must byte-equal \
12624                     SupervisorSpec::restart_window().unwrap() — the \
12625                     cap-arm refusal reads through the lifted accessor",
12626                );
12627                assert_eq!(
12628                    window, over_cap,
12629                    "RestartWindowExceedsCap.window must carry the \
12630                     author-declared :supervisor :restart-window value \
12631                     verbatim (got {window:?}, expected {over_cap:?})",
12632                );
12633            }
12634            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
12635        }
12636        // Lower + upper accept-set boundaries.
12637        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
12638            let s = SupervisorSpec {
12639                restart_window: Some(restart_window),
12640                children: vec![child.clone()],
12641                ..SupervisorSpec::default()
12642            };
12643            assert!(
12644                s.validate().is_ok(),
12645                "validate must accept restart_window == Some({restart_window:?}) \
12646                 (an accept-set boundary of \
12647                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
12648            );
12649        }
12650    }
12651
12652    #[test]
12653    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
12654        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
12655        // `Option<Duration>` by copy — `Duration` is `Copy` (so
12656        // `Option<Duration>` is `Copy`) and the accessor must return by
12657        // value, not by reference. Peer of the sibling M2
12658        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
12659        // per-`:limits :wall-clock` axis and the sibling M3
12660        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
12661        // per-`:politicas :timeout` axis, extended onto the peer M2
12662        // supervisor-slot `Option<Duration>` copy-invariant shape — the
12663        // accessor's returned `Option<Duration>` must outlive `&self`
12664        // (multiple calls must return equal values from a dropped-`&self`
12665        // copy, since the returned Option carries no borrow), and calling
12666        // the accessor twice on the same SupervisorSpec must yield the
12667        // same `Option<Duration>` verbatim (idempotent, no side effects
12668        // on `&self`).
12669        //
12670        // Pins against a future silent detour that returned
12671        // `Option<&Duration>` (which would type-check but silently break
12672        // every downstream caller — the future wasm-operator's
12673        // per-supervisor restart-intensity counter consumes `Duration` by
12674        // value and `&Duration` would fold to a detached copy at the call
12675        // site), an accidental `Option::as_ref()` projection
12676        // (`self.restart_window.as_ref()` would also type-check but
12677        // return `Option<&Duration>`), or a one-arm-only accessor that
12678        // reads `Some(*w)` in the Some arm but reads a fresh
12679        // `Default::default()` (which would collapse to `Duration::ZERO`,
12680        // not `None`) in the None arm — a footgun the
12681        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
12682        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
12683        // requires `Period > 0` and `None` structurally expresses "never
12684        // reset" instead.
12685        for restart_window in [
12686            None,
12687            Some(Duration::from_millis(1)),
12688            Some(Duration::from_secs(60)),
12689            Some(SUPERVISOR_RESTART_WINDOW_MAX),
12690        ] {
12691            let s = SupervisorSpec {
12692                restart_window,
12693                ..SupervisorSpec::default()
12694            };
12695            let first = s.restart_window();
12696            let second = s.restart_window();
12697            assert_eq!(
12698                first, second,
12699                "SupervisorSpec::restart_window must be idempotent — two \
12700                 successive calls on the same &self must return the \
12701                 same Option<Duration>",
12702            );
12703            assert_eq!(
12704                first, restart_window,
12705                "SupervisorSpec::restart_window must return :supervisor \
12706                 :restart-window verbatim by copy — got {first:?}, \
12707                 expected {restart_window:?}",
12708            );
12709        }
12710    }
12711
12712    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
12713    //
12714    // The [`SupervisorSpec::children`] accessor lift is the seed of the
12715    // slice-return (`&[T]`) accessor discipline on the substrate — the four
12716    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
12717    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
12718    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
12719    // access at the time of this seed, and inherit this pin family's
12720    // discipline as future compounding runs migrate their consumers. The
12721    // three pins below cover (1) the accessor's byte-equal projection
12722    // against the raw field access across the empty / singleton / cohort
12723    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
12724    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
12725    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
12726    // consumer routing through the accessor on both arms, and (3) the
12727    // per-child validate loop's traversal reading the same slice-view the
12728    // accessor projects. Peer of the sibling M2
12729    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12730    // two-consumer coherence pin on the per-`:supervisor`
12731    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
12732    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
12733
12734    #[test]
12735    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
12736        // The canonical per-`:supervisor` static-child-list scalar-shape
12737        // pin: [`SupervisorSpec::children`] must return the `:supervisor
12738        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
12739        // slice-view over the same backing buffer the raw
12740        // `self.children.as_slice()` field access borrows from, byte-
12741        // equal across every representative fixture in the accept-set —
12742        // the empty slice (the `SimpleOneForOne`-arm sentinel),
12743        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
12744        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
12745        // with the peer three restart-policy variants in play).
12746        //
12747        // Pins against a future silent detour that returned
12748        // `&Vec<ChildSpec>` (which would type-check but leak the
12749        // storage-side `Vec`'s grow/push/reserve surface no consumer of
12750        // the typed view reaches for), a fresh-allocated
12751        // `Vec<ChildSpec>` copy (which would type-check via a coercion
12752        // but silently break every downstream caller that relied on the
12753        // slice sharing the backing buffer's identity), or an
12754        // out-of-order or length-drifted projection (which would silently
12755        // split the per-child validate loop's traversal input from the
12756        // paired partition-dispatch `.is_empty()` probe's input).
12757        //
12758        // Peer of the sibling
12759        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12760        // (eafb619) `Copy`-composite-enum byte-equal pin on the
12761        // per-`:supervisor` sibling-restart-strategy axis, extended onto
12762        // the per-`:supervisor` static-child-list `Vec`-carry axis.
12763        let fixtures: Vec<Vec<ChildSpec>> = vec![
12764            Vec::new(),
12765            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12766            vec![
12767                child("worker", "^0.1", RestartPolicy::Permanent),
12768                child("cache-server", "^0.1", RestartPolicy::Transient),
12769            ],
12770            vec![
12771                child("worker", "^0.1", RestartPolicy::Permanent),
12772                child("cache-server", "^0.1", RestartPolicy::Transient),
12773                child("scratch-job", "^0.1", RestartPolicy::Temporary),
12774            ],
12775        ];
12776        for children in fixtures {
12777            let s = SupervisorSpec {
12778                children: children.clone(),
12779                ..SupervisorSpec::default()
12780            };
12781            assert_eq!(
12782                s.children(),
12783                children.as_slice(),
12784                "SupervisorSpec::children must return :supervisor \
12785                 :children verbatim (got {:?}, expected {:?})",
12786                s.children(),
12787                children.as_slice(),
12788            );
12789            assert_eq!(
12790                s.children(),
12791                s.children.as_slice(),
12792                "SupervisorSpec::children accessor and \
12793                 .children.as_slice() field access must byte-equal — \
12794                 the accessor is the substrate-primitive typed \
12795                 dispatch every downstream static-child-list consumer \
12796                 must route through",
12797            );
12798            assert_eq!(
12799                s.children().len(),
12800                s.children.len(),
12801                "SupervisorSpec::children().len() must byte-equal \
12802                 self.children.len() — a length-drift would silently \
12803                 split the paired partition-dispatch `.is_empty()` \
12804                 probe input from the per-child validate loop's \
12805                 traversal input",
12806            );
12807        }
12808    }
12809
12810    #[test]
12811    fn validate_reads_through_lifted_children_accessor() {
12812        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
12813        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
12814        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
12815        // when the accessor projects a non-empty slice under a
12816        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
12817        // `self.children().is_empty()` refusal probe (which must trip
12818        // [`SupervisorError::NoChildren`] when the accessor projects the
12819        // empty slice under any peer estrategia), and the per-child
12820        // validate loop's `for child in self.children()` traversal
12821        // (which must reach every entry in the same order the accessor
12822        // projects) must all key off the lifted accessor, so any future
12823        // rebrand on the typed slot's reader shape lands at exactly one
12824        // place. Pins the three-site coherence by exercising each
12825        // production consumer end-to-end: (1) the
12826        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
12827        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
12828        // refusal under the empty slice + non-`SimpleOneForOne`
12829        // estrategia across every peer variant, and (3) the per-child
12830        // duplicate-detection surface fires on the second entry of a
12831        // two-child cohort that shares a `:caixa` name (which requires
12832        // the loop to reach both entries — a first-entry-only projection
12833        // would silently pass since the dedup HashSet has room for the
12834        // first insert).
12835        //
12836        // Peer of the sibling M2
12837        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12838        // two-consumer coherence pin on the per-`:supervisor`
12839        // sibling-restart-strategy axis, extended onto the
12840        // per-`:supervisor` static-child-list `Vec`-carry axis.
12841
12842        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
12843        // `SimpleOneForOne` estrategia must trip
12844        // `SimpleOneForOneWithStaticChildren`.
12845        let s = SupervisorSpec {
12846            estrategia: RestartStrategy::SimpleOneForOne,
12847            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12848            ..SupervisorSpec::default()
12849        };
12850        assert_eq!(
12851            s.validate().unwrap_err(),
12852            SupervisorError::SimpleOneForOneWithStaticChildren,
12853            "SimpleOneForOne + non-empty children must trip \
12854             SimpleOneForOneWithStaticChildren — the accessor projects \
12855             a non-empty slice, and the SimpleOneForOne-arm refusal \
12856             probe reads through the lifted accessor",
12857        );
12858        assert!(
12859            !s.children().is_empty(),
12860            "the SimpleOneForOne-arm refusal input must be a non-empty \
12861             slice per the accessor's projection",
12862        );
12863
12864        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
12865        // under any peer estrategia must trip `NoChildren`.
12866        for estrategia in [
12867            RestartStrategy::OneForOne,
12868            RestartStrategy::OneForAll,
12869            RestartStrategy::RestForOne,
12870        ] {
12871            let s = SupervisorSpec {
12872                estrategia,
12873                children: Vec::new(),
12874                ..SupervisorSpec::default()
12875            };
12876            match s.validate().unwrap_err() {
12877                SupervisorError::NoChildren { estrategia: e } => {
12878                    assert_eq!(
12879                        e, estrategia,
12880                        "NoChildren.estrategia must carry the author-\
12881                         declared :supervisor :estrategia variant \
12882                         verbatim (got {e:?}, expected {estrategia:?})",
12883                    );
12884                }
12885                other => panic!(
12886                    "expected NoChildren, got {other:?} for \
12887                     estrategia={estrategia:?}"
12888                ),
12889            }
12890            assert!(
12891                s.children().is_empty(),
12892                "the non-SimpleOneForOne-arm refusal input must be the \
12893                 empty slice per the accessor's projection",
12894            );
12895        }
12896
12897        // (3) Per-child validate loop: a two-child cohort that shares a
12898        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
12899        // reach both entries through the accessor.
12900        let s = SupervisorSpec {
12901            estrategia: RestartStrategy::OneForOne,
12902            children: vec![
12903                child("worker", "^0.1", RestartPolicy::Permanent),
12904                child("worker", "^0.2", RestartPolicy::Transient),
12905            ],
12906            ..SupervisorSpec::default()
12907        };
12908        match s.validate().unwrap_err() {
12909            SupervisorError::DuplicateChildCaixa { caixa } => {
12910                assert_eq!(
12911                    caixa, "worker",
12912                    "DuplicateChildCaixa.caixa must carry the shared \
12913                     child `:caixa` name verbatim",
12914                );
12915            }
12916            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
12917        }
12918        assert_eq!(
12919            s.children().len(),
12920            2,
12921            "the per-child validate loop's traversal input must be a \
12922             two-element slice per the accessor's projection",
12923        );
12924    }
12925
12926    // Shared helper for the M2 per-`:children` per-slot-gate ≡
12927    // `validate` equivalence pins: builds an `OneForOne`-estrategia
12928    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
12929    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
12930    // bracket all pass cleanly so the sole failing surface is the
12931    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
12932    // pins the two-altitude equivalence on the paired probe.
12933    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
12934        let s = SupervisorSpec {
12935            estrategia: RestartStrategy::OneForOne,
12936            children,
12937            ..SupervisorSpec::default()
12938        };
12939        let via_gate = s.validate_children().unwrap_err();
12940        let via_validate = s.validate().unwrap_err();
12941        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
12942        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
12943        assert_eq!(
12944            via_gate, via_validate,
12945            "per-slot gate ≡ validate() must discriminate the same \
12946             refusal shape",
12947        );
12948    }
12949
12950    #[test]
12951    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
12952        // Fail-before-pass-after equivalence pin on the M2
12953        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
12954        // convergence — sibling of the M3 mesh-slot
12955        // `validate_membros_*` / `validate_contratos_*` /
12956        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
12957        // peer per-entry axes. Sweeps four of the five refusal shapes
12958        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
12959        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
12960        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
12961        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
12962        // duplicate-`:caixa` fan-out. Companion pin
12963        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
12964        // covers `ChildVersaoInvalid` (whose parser-owned reason string
12965        // needs pattern-matching, not equality) and the clean-pass
12966        // canonical fixture; together the two pins guarantee the
12967        // per-slot gate and `validate` discriminate the same set on
12968        // every per-child-covered input.
12969        assert_validate_children_matches_gate(
12970            vec![child("", "^0.1", RestartPolicy::Permanent)],
12971            &SupervisorError::EmptyChildName,
12972        );
12973        assert_validate_children_matches_gate(
12974            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
12975            &SupervisorError::ChildCaixaInvalid {
12976                caixa: "Worker".into(),
12977                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
12978            },
12979        );
12980        assert_validate_children_matches_gate(
12981            vec![child("worker", "", RestartPolicy::Permanent)],
12982            &SupervisorError::EmptyChildVersion {
12983                caixa: "worker".into(),
12984            },
12985        );
12986        assert_validate_children_matches_gate(
12987            vec![
12988                child("worker", "^0.1", RestartPolicy::Permanent),
12989                child("worker", "^0.2", RestartPolicy::Transient),
12990            ],
12991            &SupervisorError::DuplicateChildCaixa {
12992                caixa: "worker".into(),
12993            },
12994        );
12995    }
12996
12997    #[test]
12998    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
12999        // Second half of the two-altitude equivalence pin — covers the
13000        // one refusal shape whose reason string is parser-owned
13001        // (`ChildVersaoInvalid`, whose reason comes from the shared
13002        // [`crate::version::parse_requirement`] impl and may drift) and
13003        // the clean-pass canonical fixture. Sibling pin
13004        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
13005        // covers the four equality-comparable refusal shapes.
13006        let s_bad_versao = SupervisorSpec {
13007            estrategia: RestartStrategy::OneForOne,
13008            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
13009            ..SupervisorSpec::default()
13010        };
13011        let via_gate = s_bad_versao.validate_children().unwrap_err();
13012        let via_validate = s_bad_versao.validate().unwrap_err();
13013        match (&via_gate, &via_validate) {
13014            (
13015                SupervisorError::ChildVersaoInvalid {
13016                    caixa: cg,
13017                    versao: vg,
13018                    ..
13019                },
13020                SupervisorError::ChildVersaoInvalid {
13021                    caixa: cv,
13022                    versao: vv,
13023                    ..
13024                },
13025            ) => {
13026                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
13027                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
13028                assert_eq!(cv, "worker", "validate() :caixa carrier");
13029                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
13030            }
13031            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
13032        }
13033        assert_eq!(
13034            via_gate, via_validate,
13035            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
13036        );
13037
13038        let s_ok = SupervisorSpec {
13039            estrategia: RestartStrategy::OneForOne,
13040            children: vec![
13041                child("worker-a", "^0.1", RestartPolicy::Permanent),
13042                child("worker-b", "~0.2.3", RestartPolicy::Transient),
13043                child("collector", "*", RestartPolicy::Temporary),
13044            ],
13045            ..SupervisorSpec::default()
13046        };
13047        s_ok.validate_children()
13048            .expect("per-slot gate must accept the clean-pass fixture");
13049        s_ok.validate()
13050            .expect("validate() must accept the clean-pass fixture");
13051    }
13052
13053    #[test]
13054    fn validate_children_is_self_contained_on_children_slot() {
13055        // Self-containment pin: [`SupervisorSpec::validate_children`]
13056        // resolves the per-child cascade against `&self` alone, without
13057        // depending on the peer `:estrategia`/`:max-restarts`/
13058        // `:restart-window` gates having run first — same posture the M3
13059        // peer per-slot gates carry (`validate_membros`,
13060        // `validate_contratos`, `validate_entrada`, `validate_placement`,
13061        // routing through their own oracles rather than borrowing state
13062        // threaded down from `validate`). A future consumer that reaches
13063        // the per-slot gate directly on a spec whose peer slots would
13064        // fail `validate` still surfaces the per-child refusal, not the
13065        // peer refusal.
13066        //
13067        // Construct a spec whose `:max-restarts` is `0` (which would
13068        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
13069        // the partition-dispatch) and whose `:children` carries a
13070        // `DuplicateChildCaixa` shape: the per-slot gate called directly
13071        // must surface `DuplicateChildCaixa`, proving it does not depend
13072        // on the peer `:max-restarts` gate running first.
13073        let s = SupervisorSpec {
13074            estrategia: RestartStrategy::OneForOne,
13075            max_restarts: 0,
13076            restart_window: Some(Duration::from_secs(60)),
13077            children: vec![
13078                child("worker", "^0.1", RestartPolicy::Permanent),
13079                child("worker", "^0.2", RestartPolicy::Transient),
13080            ],
13081        };
13082        assert_eq!(
13083            s.validate_children().unwrap_err(),
13084            SupervisorError::DuplicateChildCaixa {
13085                caixa: "worker".into(),
13086            },
13087            "per-slot gate must resolve per-child refusal directly against \
13088             `&self` — a dependency on the peer `:max-restarts` gate \
13089             running first would surface ZeroMaxRestarts here instead",
13090        );
13091        // The peer gate is still the surface `validate` reaches — pin
13092        // the ordering to establish that `validate_children` truly runs
13093        // last in `validate`'s dispatch, so a direct call bypasses the
13094        // peer gates on any spec whose per-child cascade would fail.
13095        assert_eq!(
13096            s.validate().unwrap_err(),
13097            SupervisorError::ZeroMaxRestarts,
13098            "validate() must surface the peer `:max-restarts` gate before \
13099             reaching the per-child cascade — this pins the dispatch \
13100             ordering the per-slot gate's self-containment complements",
13101        );
13102    }
13103
13104    #[test]
13105    fn child_spec_restart_accessor_is_const_fn() {
13106        // The [`ChildSpec::restart`] per-`:children` restart-decision-
13107        // policy `Copy`-return scalar accessor is declared
13108        // `#[must_use] pub const fn` — matching the sibling M2
13109        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
13110        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
13111        // both converted in this commit), the sibling M2
13112        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
13113        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
13114        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
13115        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
13116        // `Copy`-return `pub const fn` scalar accessors on the sibling
13117        // M3 surface. Pin the `const`-eval posture here so a future
13118        // accidental downgrade to non-`const` (an added runtime helper
13119        // reachable only from a non-`const` context, an
13120        // `Option<RestartPolicy>`-shape migration on the per-child
13121        // restart-decision axis once heterogeneous per-cluster
13122        // restart-policy overlays land that would silently drop the
13123        // `const` qualifier, a manual hand-rolled shadow) trips at
13124        // caixa-core build time rather than surfacing as a downstream
13125        // `const`-context regression far from the declaration.
13126        //
13127        // Same shape as the sibling M3
13128        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
13129        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
13130        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
13131        // accessor axis — the load-bearing witness lives in the
13132        // module-scope `const fn` wrapper `restart_via_const_fn` below:
13133        // a body that calls [`ChildSpec::restart`] under a `const fn`
13134        // signature is well-formed only when the callee is itself
13135        // `const fn`, so any future accidental downgrade of
13136        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
13137        // build time (const-eval E0015 `cannot call non-const method`),
13138        // strictly stronger than a runtime `assert!(CONST)` and
13139        // side-stepping the destructor-in-const restriction that
13140        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
13141        // items on `ChildSpec`'s `String` carriers.
13142        //
13143        // The runtime body sweeps every closed-set [`RestartPolicy`]
13144        // arm and asserts the wrapped and direct dispatches agree.
13145        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
13146            c.restart()
13147        }
13148        for restart in [
13149            RestartPolicy::Permanent,
13150            RestartPolicy::Transient,
13151            RestartPolicy::Temporary,
13152        ] {
13153            let c = ChildSpec {
13154                caixa: "worker".into(),
13155                versao: "^0.1".into(),
13156                restart,
13157            };
13158            assert_eq!(
13159                restart_via_const_fn(&c),
13160                c.restart(),
13161                "const-fn-wrapped and direct dispatch on \
13162                 ChildSpec::restart must agree for {restart:?}",
13163            );
13164            assert_eq!(
13165                c.restart(),
13166                restart,
13167                "ChildSpec::restart must return the storage-side \
13168                 RestartPolicy verbatim for {restart:?} (a violation \
13169                 means the accessor stopped being a raw field-return \
13170                 copy)",
13171            );
13172        }
13173    }
13174
13175    #[test]
13176    fn supervisor_spec_estrategia_accessor_is_const_fn() {
13177        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
13178        // sibling-restart-strategy `Copy`-return scalar accessor is
13179        // declared `#[must_use] pub const fn` — matching the sibling M2
13180        // per-`:children` [`ChildSpec::restart`] (pinned by
13181        // [`child_spec_restart_accessor_is_const_fn`] above, both
13182        // converted in this commit), the sibling M2 per-`:supervisor`
13183        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
13184        // accessor already `pub const fn`, and mirroring the peer M3
13185        // mesh-slot per-`:placement`
13186        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
13187        // `pub const fn` scalar accessor whose method-name discipline
13188        // the [`SupervisorSpec::estrategia`] method was authored to
13189        // match. Pin the `const`-eval posture here so a future
13190        // accidental downgrade to non-`const` (an added runtime helper
13191        // reachable only from a non-`const` context, an
13192        // `Option<RestartStrategy>`-shape migration once the substrate
13193        // grows per-cluster strategy overlays that would silently drop
13194        // the `const` qualifier, a manual hand-rolled shadow) trips at
13195        // caixa-core build time rather than surfacing as a downstream
13196        // `const`-context regression far from the declaration.
13197        //
13198        // Same shape as the sibling
13199        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
13200        // load-bearing witness lives in the module-scope `const fn`
13201        // wrapper `estrategia_via_const_fn` below: a body that calls
13202        // [`SupervisorSpec::estrategia`] under a `const fn` signature
13203        // is well-formed only when the callee is itself `const fn`,
13204        // side-stepping the destructor-in-const restriction that would
13205        // otherwise block a direct
13206        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
13207        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
13208        // carriers.
13209        //
13210        // The runtime body sweeps every closed-set [`RestartStrategy`]
13211        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
13212        // direct dispatches agree.
13213        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
13214            s.estrategia()
13215        }
13216        for &estrategia in RestartStrategy::ALL {
13217            let s = SupervisorSpec {
13218                estrategia,
13219                max_restarts: 5,
13220                restart_window: Some(Duration::from_secs(60)),
13221                children: Vec::new(),
13222            };
13223            assert_eq!(
13224                estrategia_via_const_fn(&s),
13225                s.estrategia(),
13226                "const-fn-wrapped and direct dispatch on \
13227                 SupervisorSpec::estrategia must agree for {estrategia:?}",
13228            );
13229            assert_eq!(
13230                s.estrategia(),
13231                estrategia,
13232                "SupervisorSpec::estrategia must return the storage-side \
13233                 RestartStrategy verbatim for {estrategia:?} (a violation \
13234                 means the accessor stopped being a raw field-return \
13235                 copy)",
13236            );
13237        }
13238    }
13239
13240    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
13241    // macro definition (see the paired doc-block above the macro
13242    // definition) — every generated `<ctor>(caixa: &str) -> Self`
13243    // constructor folds the uniform `Self::<Variant> { caixa:
13244    // caixa.to_string() }` one-field struct-literal onto one substrate
13245    // primitive. The three per-variant equivalence pins below
13246    // (fail-before-pass-after by construction — a byte-mismatched macro
13247    // arm would trip its equivalence pin first) lock each generated
13248    // constructor to its struct-literal peer under `PartialEq`, so
13249    // every wire-up in [`SupervisorSpec::validate_children`] and
13250    // [`validate_no_self_supervision`] on that variant produces a
13251    // byte-equal `SupervisorError` to the pre-lift open-coded
13252    // struct-literal. The cross-axis pin that follows (non-default
13253    // caixa name) routes the sole constructor input axis through
13254    // `.to_string()`, so the fold does not silently collapse onto a
13255    // fixed name.
13256    //
13257    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
13258    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
13259    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
13260    // `missing_entry_ctor_matches_struct_literal_wrap` /
13261    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
13262    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
13263    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
13264    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
13265    // on the six sibling ctor families the recent trajectory closed
13266    // on the peer `LayoutError` / `AplicacaoError` envelopes.
13267
13268    #[test]
13269    fn empty_child_version_ctor_matches_struct_literal_wrap() {
13270        assert_eq!(
13271            SupervisorError::empty_child_version("worker"),
13272            SupervisorError::EmptyChildVersion {
13273                caixa: "worker".to_string(),
13274            },
13275            "generated empty_child_version ctor must produce byte-equal \
13276             SupervisorError to the open-coded struct-literal wrap on the \
13277             same &str fixture",
13278        );
13279    }
13280
13281    #[test]
13282    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
13283        assert_eq!(
13284            SupervisorError::duplicate_child_caixa("worker"),
13285            SupervisorError::DuplicateChildCaixa {
13286                caixa: "worker".to_string(),
13287            },
13288            "generated duplicate_child_caixa ctor must produce byte-equal \
13289             SupervisorError to the open-coded struct-literal wrap on the \
13290             same &str fixture",
13291        );
13292    }
13293
13294    #[test]
13295    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
13296        assert_eq!(
13297            SupervisorError::child_supervises_self("orquestra"),
13298            SupervisorError::ChildSupervisesSelf {
13299                caixa: "orquestra".to_string(),
13300            },
13301            "generated child_supervises_self ctor must produce byte-equal \
13302             SupervisorError to the open-coded struct-literal wrap on the \
13303             same &str fixture",
13304        );
13305    }
13306
13307    // Per-variant equivalence pins for the two lifted
13308    // [`SupervisorError::child_caixa_invalid`] /
13309    // [`SupervisorError::child_versao_invalid`] inherent constructors
13310    // (fail-before-pass-after by construction — a byte-mismatched ctor body
13311    // would trip its equivalence pin first). Each pins the ctor output to
13312    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
13313    // in [`SupervisorSpec::validate_children`] on the two variants
13314    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
13315    // struct-literal on the same scalar fixtures. Peers of the sibling
13316    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
13317    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
13318    // the peer `AplicacaoError` envelope's
13319    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
13320
13321    #[test]
13322    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
13323        let caixa = "Worker";
13324        let reason = "sample reason text";
13325        assert_eq!(
13326            SupervisorError::child_caixa_invalid(caixa, reason),
13327            SupervisorError::ChildCaixaInvalid {
13328                caixa: caixa.to_string(),
13329                reason: reason.to_string(),
13330            },
13331            "lifted child_caixa_invalid ctor must produce byte-equal \
13332             SupervisorError to the open-coded struct-literal wrap on the \
13333             same (&str, reason) fixture",
13334        );
13335    }
13336
13337    #[test]
13338    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
13339        let caixa = "worker";
13340        let versao = "not-a-req";
13341        let reason = "sample reason text";
13342        assert_eq!(
13343            SupervisorError::child_versao_invalid(caixa, versao, reason),
13344            SupervisorError::ChildVersaoInvalid {
13345                caixa: caixa.to_string(),
13346                versao: versao.to_string(),
13347                reason: reason.to_string(),
13348            },
13349            "lifted child_versao_invalid ctor must produce byte-equal \
13350             SupervisorError to the open-coded struct-literal wrap on the \
13351             same (&str, &str, reason) fixture",
13352        );
13353    }
13354
13355    #[test]
13356    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
13357        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
13358        // against a `&str`-literal vs. `format!(…)` reason input to pin
13359        // both constructors accept the `impl Into<String>` bound
13360        // uniformly, so neither wire-up site drifts under a per-arm
13361        // wrapper transformation on the caller-side `reason` axis. Peer
13362        // of the sibling
13363        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
13364        // sweep on the peer `AplicacaoError` envelope.
13365        let via_literal = "literal reason text";
13366        let via_format = format!("{} reason text", "literal");
13367        assert_eq!(
13368            SupervisorError::child_caixa_invalid("Worker", via_literal),
13369            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
13370        );
13371        assert_eq!(
13372            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
13373            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
13374        );
13375    }
13376
13377    #[test]
13378    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
13379        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
13380        // &str`) through a non-default fixture name against every
13381        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
13382        // so any wrapper-side lowercase / trim / truncate / re-order on
13383        // the `caixa.to_string()` sole-field construction surfaces
13384        // here rather than at a downstream diagnostic-shape mismatch.
13385        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
13386        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
13387        // through_to_string` / `contrato_target_ctors_route_edge_
13388        // triple_through_verbatim` / `contrato_empty_pair_ctors_
13389        // route_edge_pair_through_verbatim` cross-axis routing pins on
13390        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
13391        // here onto the `SupervisorError` `{ caixa: String }` envelope
13392        // so every substrate-primitive ctor family in caixa-core
13393        // guarantees the sole-field construction routes the caller's
13394        // `&str` through `.to_string()` verbatim.
13395        let name = "cache-v2";
13396        assert_eq!(
13397            SupervisorError::empty_child_version(name),
13398            SupervisorError::EmptyChildVersion {
13399                caixa: name.to_string(),
13400            },
13401        );
13402        assert_eq!(
13403            SupervisorError::duplicate_child_caixa(name),
13404            SupervisorError::DuplicateChildCaixa {
13405                caixa: name.to_string(),
13406            },
13407        );
13408        assert_eq!(
13409            SupervisorError::child_supervises_self(name),
13410            SupervisorError::ChildSupervisesSelf {
13411                caixa: name.to_string(),
13412            },
13413        );
13414    }
13415
13416    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
13417    //
13418    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
13419    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
13420    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
13421    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
13422    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
13423    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
13424    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
13425    // / silent constant-substitution on any one variant surfaces here rather
13426    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
13427    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
13428    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
13429    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
13430    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
13431    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
13432    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
13433    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
13434    #[test]
13435    fn no_children_ctor_matches_struct_literal_wrap() {
13436        let estrategia = RestartStrategy::OneForAll;
13437        assert_eq!(
13438            SupervisorError::no_children(estrategia),
13439            SupervisorError::NoChildren { estrategia },
13440            "generated no_children ctor must produce byte-equal \
13441             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
13442             on the same `Copy`-`RestartStrategy` fixture",
13443        );
13444    }
13445
13446    #[test]
13447    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13448        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13449        assert_eq!(
13450            SupervisorError::max_restarts_exceeds_cap(max_restarts),
13451            SupervisorError::MaxRestartsExceedsCap { max_restarts },
13452            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13453             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13454             struct-literal wrap on the same `Copy`-`u32` fixture",
13455        );
13456    }
13457
13458    #[test]
13459    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13460        let window = Duration::from_micros(1_500);
13461        assert_eq!(
13462            SupervisorError::restart_window_not_canonical(window),
13463            SupervisorError::RestartWindowNotCanonical { window },
13464            "generated restart_window_not_canonical ctor must produce \
13465             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13466             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13467        );
13468    }
13469
13470    #[test]
13471    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13472        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13473        assert_eq!(
13474            SupervisorError::restart_window_exceeds_cap(window),
13475            SupervisorError::RestartWindowExceedsCap { window },
13476            "generated restart_window_exceeds_cap ctor must produce \
13477             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13478             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13479        );
13480    }
13481
13482    #[test]
13483    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13484        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13485        // constructor input axis through a non-default `Copy` fixture against
13486        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13487        // side silent `.into()` / silent constant-substitution / silent field
13488        // re-name away from the canonical `estrategia | max_restarts | window`
13489        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13490        // axis silently rerouted through some other `Copy` coercion, surfaces
13491        // here rather than at a downstream per-`:supervisor` diagnostic-shape
13492        // drift. Peer of the sibling
13493        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13494        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13495        // envelope's per-`:politicas` per-axis ctor family, extended here onto
13496        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13497        // variant family folded onto a substrate primitive.
13498        //
13499        // Fixtures picked out of each variant's accept-set boundary rather
13500        // than the default value so a silent constant-substitution to a per-
13501        // variant sentinel surfaces here on the structural-equality assertion.
13502        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13503        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13504        // isn't the `SimpleOneForOne` arm the sibling
13505        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13506        // `max_restarts` fixture picks an above-cap magnitude the cap arm
13507        // rejects; the two `Duration` fixtures pick the sub-millisecond and
13508        // above-cap ends of the `:restart-window` canonical-form + cap
13509        // bracket respectively.
13510        let estrategia = RestartStrategy::RestForOne;
13511        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13512        let sub_ms = Duration::from_micros(1_500);
13513        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13514        assert_eq!(
13515            SupervisorError::no_children(estrategia),
13516            SupervisorError::NoChildren { estrategia },
13517        );
13518        assert_eq!(
13519            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13520            SupervisorError::MaxRestartsExceedsCap {
13521                max_restarts: above_cap_restarts,
13522            },
13523        );
13524        assert_eq!(
13525            SupervisorError::restart_window_not_canonical(sub_ms),
13526            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13527        );
13528        assert_eq!(
13529            SupervisorError::restart_window_exceeds_cap(above_hour),
13530            SupervisorError::RestartWindowExceedsCap { window: above_hour },
13531        );
13532    }
13533
13534    #[test]
13535    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13536        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13537        // generated ctor `const fn` so a caller can pin a `SupervisorError`
13538        // at compile time — the same zero-runtime-work property the pre-lift
13539        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13540        // its `Copy`-pass-through construction path (no `.to_string()` /
13541        // `.into()` allocation, no branching). If any future edit silently
13542        // drops the `const` qualifier from the macro body the per-arm `const`
13543        // bindings below fail to compile, which surfaces the regression at
13544        // the substrate-primitive definition rather than at some downstream
13545        // consumer that had come to rely on the `const`-constructibility.
13546        // Peer of the sibling
13547        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13548        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13549        // per-`:politicas` per-axis ctor family.
13550        const NO_CHILDREN: SupervisorError =
13551            SupervisorError::no_children(RestartStrategy::OneForAll);
13552        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13553        const WINDOW_NC: SupervisorError =
13554            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13555        const WINDOW_CAP: SupervisorError =
13556            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13557        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13558        assert!(matches!(
13559            MAX_RESTARTS_CAP,
13560            SupervisorError::MaxRestartsExceedsCap { .. }
13561        ));
13562        assert!(matches!(
13563            WINDOW_NC,
13564            SupervisorError::RestartWindowNotCanonical { .. }
13565        ));
13566        assert!(matches!(
13567            WINDOW_CAP,
13568            SupervisorError::RestartWindowExceedsCap { .. }
13569        ));
13570    }
13571}