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/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2326/// forward projection on the M2 OTP-shape per-child-restart
2327/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2328/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2329/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2330/// returned `&'static str`, so every consumer that binds a
2331/// [`RestartPolicy`] through the standard-library `.into()` /
2332/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2333/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2334/// per-request `Sync` + `Send`-safe structured-log field composed
2335/// across an `.await` boundary through a
2336/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2337/// a future wasm-operator's per-child post-exit restart-decision
2338/// pipeline holding a shared-ownership per-arm cache key, a
2339/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2340/// collector recording a per-child-policy field onto the parent
2341/// span's shared-ownership context — reaches the same three-arm
2342/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2343/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2344/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2345/// sibling
2346/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2347/// forward-projection corner already returns.
2348///
2349/// Second peer on the substrate-wide trait-idiomatic
2350/// [`std::sync::Arc<str>`] forward-projection family opened one
2351/// projection tier prior (bca2ec8) on the paired sibling-restart
2352/// [`RestartStrategy`] owned-input first-mover — extends the tier
2353/// onto the second (and third-and-final) M2 OTP-shape closed-set
2354/// fieldless typed enum peer on the caixa surface
2355/// (`:children :restart`), immediately after the paired [`Box<str>`]
2356/// axis (0a1b313 / cb1d068) closed the whole
2357/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2358/// 2×4 corner on this enum. Rust's standard library carries
2359/// `impl From<&str> for std::sync::Arc<str>` and
2360/// `impl From<String> for std::sync::Arc<str>` but no blanket
2361/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2362/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2363/// axis is a distinct trait-idiomatic surface that a
2364/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2365/// reaches through this impl and no other — a paired
2366/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2367/// compile-time link back to the substrate primitive, and a two-step
2368/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2369/// through the owned-`String` axis allocates twice (once into the
2370/// intermediate `String`, once into the [`Arc<str>`] on the
2371/// `From<String>` conversion) where the single-step trait impl
2372/// allocates once.
2373///
2374/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2375/// same "extends the substrate-wide projection tier onto the next
2376/// M2 OTP-shape peer" discipline, extended onto the
2377/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2378/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2379/// owned-move return-shape cannot provide.
2380///
2381/// Pinned load-bearing by
2382/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2383/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2384/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2385/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2386/// axis byte-parity pins against the sibling owned-input
2387/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2388/// axes).
2389impl From<RestartPolicy> for std::sync::Arc<str> {
2390    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2391        std::sync::Arc::<str>::from(policy.as_str())
2392    }
2393}
2394
2395// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2396// supervisor surface — two more typed shadows over Erlang/OTP
2397// primitives the substrate now mechanically tracks (see
2398// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2399// theory/TYPED-ABSORPTION.md for the absorption arc).
2400gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2401gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2402
2403/// One child entry in the supervisor's `:children` list.
2404///
2405/// Every child references another caixa by `:caixa <nome>` + version
2406/// constraint. The supervisor materializes one ComputeUnit per entry.
2407#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2408#[serde(rename_all = "camelCase")]
2409pub struct ChildSpec {
2410    /// The child caixa's `:nome`. Must resolve via the same dependency
2411    /// resolution path as `:deps` (caixa-resolver).
2412    pub caixa: String,
2413
2414    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2415    /// [`crate::dep::Dep::versao`].
2416    pub versao: String,
2417
2418    /// Restart policy — an author-omitted slot degrades onto the
2419    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2420    /// (`permanent`, the Erlang/OTP worker-child default) through the
2421    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2422    /// to.
2423    #[serde(default)]
2424    pub restart: RestartPolicy,
2425}
2426
2427impl ChildSpec {
2428    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2429    /// accessor every consumer that reads the OTP-shape supervised
2430    /// child's identity keys off — returns the author-declared
2431    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2432    /// from the typed slot's own [`String`] storage.
2433    ///
2434    /// The `:children :caixa` slot carries the DNS-1123 label — the
2435    /// child caixa's `:nome` — that every emitted cluster artifact
2436    /// derives its `metadata.name` from verbatim: the rendered
2437    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2438    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2439    /// identity, and the per-child K8s Service `metadata.name` the
2440    /// future wasm-operator (M3) provisions for inter-child supervision-
2441    /// tree wiring. Every downstream consumer that fans on the child's
2442    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2443    /// per-child DNS-1123 gate at
2444    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2445    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2446    /// [`validate_no_self_supervision`] cross-slot equality check
2447    /// against the parent's `:nome`, every `SupervisorError` variant
2448    /// carrying the offending child caixa verbatim for `feira lint`
2449    /// rendering, the future wasm-operator's hierarchical reconciliation
2450    /// scheduler's per-child ComputeUnit-name projection, the future M4
2451    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2452    /// admission webhook).
2453    ///
2454    /// Prior to this lift the `.caixa` byte-string was accessed inline
2455    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2456    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2457    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2458    /// carriers' `child.caixa.clone()`, the dedup key's
2459    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2460    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2461    /// field-accesses that expressed no compile-time link back to the
2462    /// typed slot. A future extension of the `:children :caixa` axis to
2463    /// a richer author surface (a per-cluster alias table the operator
2464    /// pins through a future `:placement`-scoped slot on the supervisor
2465    /// tree, a namespace-qualified rewrite the M4 CR materializer
2466    /// applies per-CR, a per-child overlay from the future `:children
2467    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2468    /// acknowledges) would have had to be threaded through every
2469    /// open-coded copy in lockstep or one consumer would silently
2470    /// disagree with the peers on which caixa a given child resolves to
2471    /// — a child-set lookup that treated the name as `"cart-worker"`
2472    /// while the peer duplicate-detector treated it as
2473    /// `"tenant-a/cart-worker"` would silently split the
2474    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2475    /// self-supervision detector's parent-equality check, a two-consumer
2476    /// split at the validator far from the source `caixa.lisp` with no
2477    /// field naming the identity-drift root cause. Lifting the resolution
2478    /// rule to a typed method on the substrate primitive means every
2479    /// downstream consumer of the Supervisor's per-`:children` identity
2480    /// surface reaches for exactly one typed dispatch — the resolver's
2481    /// accept-set migrates as a unit on any future axis addition.
2482    ///
2483    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2484    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2485    /// mesh-slot surface — same "one typed dispatch on the substrate
2486    /// primitive, thin projections at each consumer" discipline extended
2487    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2488    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2489    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2490    /// accessor discipline for the shared substrate concept "another
2491    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2492    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2493    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2494    /// slot family's typed-accessor discipline now spans both the
2495    /// upgrade axis (`:upgrade-from`) and the supervision axis
2496    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2497    /// shape. Named `nome()` to match the tatara-lisp author-surface
2498    /// term the field's docstring already reaches for ("The child
2499    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2500    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2501    /// discipline the substrate already carries — the accessor's name
2502    /// maps directly onto the canonical caixa-identity vocabulary rather
2503    /// than shadowing the field's storage-side `caixa` label.
2504    #[must_use]
2505    pub const fn nome(&self) -> &str {
2506        self.caixa.as_str()
2507    }
2508
2509    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2510    /// requirement scalar accessor every consumer that reads the OTP-shape
2511    /// supervised child's version pin keys off — returns the author-declared
2512    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2513    /// the typed slot's own [`String`] storage.
2514    ///
2515    /// The `:children :versao` slot carries the Cargo-shaped semver
2516    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2517    /// which release of the supervised child caixa the OTP-shape supervisor
2518    /// tree materializes against — the same requirement grammar the peer
2519    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2520    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2521    /// and the shared [`crate::version::parse_requirement`] parser. Every
2522    /// downstream consumer that fans on the child's version pin keys off
2523    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2524    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2525    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2526    /// for `feira lint` rendering, every future per-cluster version-lock
2527    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2528    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2529    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2530    /// per-child version resolver, the future wasm-operator's per-child
2531    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2532    ///
2533    /// Prior to this lift the `.versao` byte-string was accessed inline at
2534    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2535    /// [`SupervisorSpec::validate`] requirement-gate call
2536    /// `require_valid_versao_requirement(&child.versao, …)` and the
2537    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2538    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2539    /// expressed no compile-time link back to the typed slot. A future
2540    /// extension of the `:children :versao` axis to a richer author surface
2541    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2542    /// flow, a lacre-projected concrete-version rewrite the operator
2543    /// materializes at CR-admission time, a future `:children :versao-lock`
2544    /// per-cluster override slot the wasm-operator's hierarchical
2545    /// reconciliation scheduler authors per-CR) would have had to be
2546    /// threaded through both open-coded copies in lockstep or one consumer
2547    /// would silently disagree with the peer on which release constraint a
2548    /// given child resolves to — the requirement-gate call reading
2549    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2550    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2551    /// the actual gate rejection input, a two-consumer split at the
2552    /// validator far from the source `caixa.lisp` with no field naming the
2553    /// version-pin drift root cause. Lifting the resolution rule to a typed
2554    /// method on the substrate primitive means every downstream
2555    /// requirement-facing consumer of the Supervisor's per-`:children`
2556    /// version-pin surface reaches for exactly one typed dispatch — the
2557    /// resolver's accept-set migrates as a unit on any future axis addition.
2558    ///
2559    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2560    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2561    /// surface — same "one typed dispatch on the substrate primitive, thin
2562    /// projections at each consumer" discipline extended onto the M2
2563    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2564    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2565    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2566    /// one accessor discipline for the shared substrate concept "another
2567    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2568    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2569    /// `:nome` scalar accessor — the pair
2570    /// `(nome(), versao_requirement())` jointly projects the
2571    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2572    /// that fans on per-child identity + version pin keys off, closing the
2573    /// last unlifted per-`:children` `String`-carry axis so every downstream
2574    /// per-`:children` reader now routes through a typed dispatch on the
2575    /// substrate primitive. Named `versao_requirement()` rather than
2576    /// `versao()` because the field's storage-side `.versao` label is
2577    /// already the author-surface term (`:versao`); the accessor's name
2578    /// carries the semantic role — the semver *requirement* string the
2579    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2580    /// so a raw field access and a typed dispatch read differently at every
2581    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2582    /// naming discipline verbatim.
2583    #[must_use]
2584    pub const fn versao_requirement(&self) -> &str {
2585        self.versao.as_str()
2586    }
2587
2588    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2589    /// per-child post-exit restart-decision policy scalar accessor every
2590    /// consumer that dispatches on the supervised child's post-exit
2591    /// reconcile posture keys off — returns the author-declared
2592    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2593    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2594    /// storage.
2595    ///
2596    /// The `:children :restart` slot carries the closed-set OTP-shaped
2597    /// per-child restart-decision policy discriminator
2598    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2599    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2600    /// on abnormal exit, the OTP `transient` clean-completion-aware
2601    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2602    /// `temporary` one-shot default) that every downstream consumer of
2603    /// the Supervisor's per-child post-exit reconcile branch keys off.
2604    /// Every future downstream consumer that fans on the per-child
2605    /// restart-decision keys off this scalar (the future `feira app
2606    /// graph` per-child restart column, the future wasm-operator's
2607    /// per-child post-exit restart-decision branch, the future M4
2608    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2609    /// admission webhook, the `caixa-operator`'s hierarchical
2610    /// reconciliation scheduler's per-child post-exit reconcile branch,
2611    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2612    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2613    /// pin threads through).
2614    ///
2615    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2616    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2617    /// scalar accessor and the M3 mesh-slot
2618    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2619    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2620    /// — same "one typed dispatch on the substrate primitive,
2621    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2622    /// the downstream renderer's per-arm fan-out" discipline extended
2623    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2624    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2625    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2626    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2627    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2628    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2629    /// on the sibling `String`-carry axes. The triple
2630    /// `(nome(), versao_requirement(), restart())` jointly projects the
2631    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2632    /// tree consumer that fans on per-child identity + version pin +
2633    /// restart-decision keys off, closing the last unlifted per-`:children`
2634    /// axis so every downstream per-`:children` reader now routes through
2635    /// a typed dispatch on the substrate primitive. Named `restart()` to
2636    /// match the storage field's name and the author-surface
2637    /// `:children :restart` slot term verbatim; the accessor's identity
2638    /// name maps onto the canonical OTP-shape per-child restart-decision-
2639    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2640    /// carries.
2641    ///
2642    /// Declared `pub const fn` to close the last non-`const`
2643    /// `Copy`-return raw-field-getter posture on the M2
2644    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2645    /// of the sibling M2 per-`:supervisor`
2646    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2647    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2648    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2649    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2650    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2651    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2652    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2653    /// downstream substrate-side `const`-context consumer of the
2654    /// per-`:children` restart-decision-policy scalar (a future
2655    /// module-scope `const _:() = assert!(matches!(child.restart(),
2656    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2657    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2658    /// admission-webhook `const fn` per-child restart-decision floor
2659    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2660    /// composer over the substrate primitive that fans on the per-child
2661    /// restart-decision policy at compile time) now reaches through the
2662    /// same typed dispatch on the substrate primitive at const-eval
2663    /// time as at runtime. A future non-`Copy`-return promotion of the
2664    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2665    /// per-child restart-decision axis once heterogeneous per-cluster
2666    /// restart-policy overlays land, a per-tenant restart-policy-alias
2667    /// table the M4 CR materializer resolves per-CR) that would drop
2668    /// the `const` qualifier fails the fail-before-pass-after pin
2669    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2670    /// build time rather than surfacing as a downstream consumer
2671    /// regression.
2672    #[must_use]
2673    pub const fn restart(&self) -> RestartPolicy {
2674        self.restart
2675    }
2676}
2677
2678/// Supervisor-typed slots that live alongside the standard Caixa
2679/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2680/// the manifest stays a single typed form; this struct exists for
2681/// validation + conversion.
2682#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2683#[serde(rename_all = "camelCase")]
2684pub struct SupervisorSpec {
2685    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2686    #[serde(default)]
2687    pub estrategia: RestartStrategy,
2688
2689    /// Max restarts within [`Self::restart_window`] before the
2690    /// supervisor itself terminates (and its parent supervisor decides
2691    /// what to do). Default 5.
2692    #[serde(default = "default_max_restarts")]
2693    pub max_restarts: u32,
2694
2695    /// Sliding window for `max_restarts`. Authored as a duration
2696    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2697    /// is rejected by [`Self::validate`] — Erlang/OTP's
2698    /// `MaxIntensity / Period` invariant requires a positive window
2699    /// (a zero-period supervisor either trips on the first failure or
2700    /// never trips, depending on operator interpretation, neither of
2701    /// which is the author's intent). Omit the slot to express "no
2702    /// reset"; carry a positive duration to express the sliding window.
2703    #[serde(
2704        default,
2705        skip_serializing_if = "Option::is_none",
2706        with = "duration_codec"
2707    )]
2708    pub restart_window: Option<Duration>,
2709
2710    /// Static children. Empty for `SimpleOneForOne` (children added
2711    /// dynamically); required for the other three strategies.
2712    #[serde(default)]
2713    pub children: Vec<ChildSpec>,
2714}
2715
2716const fn default_max_restarts() -> u32 {
2717    // Route the private serde-`#[serde(default = "…")]` helper through
2718    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2719    // `pub const` rather than the raw `5` literal — one source of truth
2720    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2721    // default across the two production consumers that currently
2722    // dispatch on it (this helper via `#[serde(default = "…")]` on
2723    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2724    // impl at line 962). Pinned by
2725    // `default_max_restarts_helper_routes_through_lifted_default` +
2726    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2727    // in the tests module; peer of the sibling caixa-core
2728    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2729    // that now routes its author-omitted `:max-restarts` arm through
2730    // the same lifted constant.
2731    SUPERVISOR_MAX_RESTARTS_DEFAULT
2732}
2733
2734/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2735/// count default for the `:supervisor :max-restarts` axis — the
2736/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2737/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2738/// so every substrate-side consumer that resolves "what
2739/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2740/// `:max-restarts` slot degrade onto?" reaches for exactly one
2741/// substrate-primitive `u32`.
2742///
2743/// The `:max-restarts` default axis has two production consumers on the
2744/// substrate side today (both prior to this lift folded onto raw `5`
2745/// literals with no compile-time link back to a shared truth): the
2746/// serde-`#[serde(default = "default_max_restarts")]` helper on
2747/// [`SupervisorSpec::max_restarts`] that every author-omitted
2748/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2749/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2750/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2751/// the composed [`SupervisorSpec`] altitude reaches through
2752/// (`feira app graph`, the future wasm-operator's per-supervisor
2753/// restart-intensity counter, the future M4
2754/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2755/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2756/// A pair of open-coded `5`s across two files that expressed no
2757/// compile-time link back to the shared OTP-canonical default — a
2758/// future rebrand of the default (a tightening to Elixir's
2759/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2760/// the operator pins through a future
2761/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2762/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2763/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2764/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2765/// per-child-cohort roadmap lands) would have had to be threaded
2766/// through both open-coded copies in lockstep or the wire-format
2767/// author-omitted arm and the view-construction author-omitted arm
2768/// would silently disagree on which restart-budget an omitted
2769/// `:max-restarts` resolves to (an author writing `:supervisor
2770/// (:max-restarts ())` would round-trip through serde with the new
2771/// default while `supervisor_view` silently continued to compose the
2772/// stale `5`, or vice versa), a two-consumer split at the composition
2773/// boundary far from the source `caixa.lisp` with no field naming the
2774/// default-drift root cause. Lifting the resolution rule to a typed
2775/// `pub const` on the substrate primitive means every downstream
2776/// consumer of the per-Supervisor default-restart-budget-count surface
2777/// reaches for exactly one substrate-primitive `u32` — the resolver's
2778/// accepted value migrates as a unit on any future axis change.
2779///
2780/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2781/// worker-supervisor default (the closest canonical OTP-shape
2782/// production reference the substrate carries, matching the sibling
2783/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2784/// this constant with on the paired sliding-window axis). Two orders of
2785/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2786/// (the upper bracket on the same axis, sibling of this lower default;
2787/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2788/// axis and now share one accessor discipline on the substrate) and
2789/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2790/// restart floor — the "one restart, then escalate" default is
2791/// deliberately loose enough to absorb a short burst of transient
2792/// child failures without escalating past the supervisor's parent
2793/// while remaining tight enough to trip the `MaxIntensity / Period`
2794/// ratio's escalation on a genuinely-stuck child within the sibling
2795/// `60s` sliding window.
2796///
2797/// Lifted as a typed `pub const` so the bound has exactly one source
2798/// of truth — the serde-side wire-format author-omitted arm at
2799/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2800/// struct-literal default field, and the caixa-core
2801/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2802/// arm all read from one place. Same shape every other typed default
2803/// in this crate carries (the sibling
2804/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2805/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2806/// sibling `:restart-window` axis, and the peer
2807/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2808/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2809/// axes).
2810pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2811
2812/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2813/// validated [`SupervisorSpec::max_restarts`] past
2814/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2815///
2816/// The typed field is `u32` (the zero-floor arm
2817/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2818/// so a programmatic struct literal
2819/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2820/// author-surface form (`:max-restarts 4294967295` or any
2821/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2822/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2823/// runtime substrate consuming the value (Erlang/OTP's
2824/// `MaxIntensity / Period` ratio, the future wasm-operator's
2825/// per-supervisor restart-intensity counter, the M4
2826/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2827/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2828/// escalation threshold is structurally so high that no realistic
2829/// restarts-per-`:restart-window` traffic shape can reach it, the
2830/// supervisor never escalates to its parent, and a bad child can loop
2831/// inside the window indefinitely with the parent supervisor structurally
2832/// never receiving the "this subtree has exceeded its restart budget"
2833/// signal the typed slot is meant to express — the canonical
2834/// "supervisor intensity declared, no escalation" footgun, exactly the
2835/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2836/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2837/// "trip the next-higher protection layer after N events in a rolling
2838/// window" counters with identical degenerate-at-the-high-end shape).
2839///
2840/// The `1000` ceiling matches the sibling
2841/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2842/// peer — same "events-per-window trip threshold" semantics, same `u32`
2843/// type, same no-op-at-the-high-end failure mode) so the M4
2844/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2845/// and the future wasm-operator's per-supervisor restart-intensity
2846/// counter reach for either field knowing the value is in `1..=1000`
2847/// without re-validating at the reconciler layer. The cap sits two
2848/// orders of magnitude above every documented Erlang/OTP production
2849/// playbook recommendation (Learn You Some Erlang's
2850/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2851/// `max_restarts: 3` default, OTP's `supervisor` callback module
2852/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2853/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2854/// default) and below the clearly-pathological "effectively no
2855/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2856/// author can plausibly want at hyperscale (a long-running supervisor
2857/// over a very-flaky pool tolerating thousands of transient restarts
2858/// before escalating), but a hard wall above which the typed policy is
2859/// structurally a no-op carried verbatim on every emitted child-restart
2860/// reconciliation contract.
2861///
2862/// Lifted as a typed `pub const` so the bound has exactly one source of
2863/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2864/// materializer's admission webhook and the wasm-operator-side
2865/// per-supervisor restart-intensity reconciler read from one place. Same
2866/// shape every other typed upper bound in this crate carries
2867/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2868/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2869/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2870/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2871/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2872/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2873pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2874
2875/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2876/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2877/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2878/// (inclusive on both ends, integer-millisecond magnitudes by the
2879/// canonical-form gate immediately preceding).
2880///
2881/// The typed field is `Option<Duration>` (the zero-floor arm
2882/// [`SupervisorError::RestartWindowZero`] already rejects
2883/// `Some(Duration::ZERO)`, and the canonical-form arm
2884/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2885/// sub-millisecond residue), so a programmatic struct literal
2886/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2887/// .. }` — 24h) and the equivalent author-surface form
2888/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2889/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2890/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2891/// A `:restart-window` value far above the documented Erlang/OTP
2892/// `MaxIntensity / Period` production-playbook band (Learn You Some
2893/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2894/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2895/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2896/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2897/// degenerates the supervisor's restart-intensity counter into a
2898/// lifetime counter: the rolling failure-counting window is structurally
2899/// so long that transient restarts are never forgotten, so the
2900/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2901/// supervisor when the child has exceeded its restart budget *within
2902/// the recent window*" to "trip the parent when the child has exceeded
2903/// its restart budget *over its lifetime*" — every transient restart
2904/// counts against the budget forever, the supervisor's reset semantic
2905/// never reaches the child, and the typed `:restart-window` slot
2906/// becomes a no-op rolling window carried on every emitted hierarchical
2907/// reconciliation contract. The canonical
2908/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2909/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2910/// `:politicas :circuit-breaker :window` axis with identical shape (both
2911/// are "rolling failure-counting window with a per-`Period` reset" Duration
2912/// axes whose lifetime-counter degenerate at the high end is the same
2913/// "the reset semantic never fires" CSE invariant violation).
2914///
2915/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2916/// the shared duration codec emits (`"<n>h"` for any integer-hour
2917/// magnitude) — every value in the canonical authoring form's
2918/// `<integer><unit>` grammar at or below this cap renders to a clean
2919/// canonical string — and matches the three sibling typed-`Duration`
2920/// caps already lifted to this surface
2921/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2922/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2923/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2924/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2925/// per-supervisor `:supervisor :restart-window` — now share a single
2926/// uniform top edge at the codec's largest emitted unit so the next
2927/// typed-slot wiring (the future wasm-operator's per-supervisor
2928/// `MaxIntensity / Period` reconciler, the M4
2929/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2930/// webhook, the `caixa-operator`'s hierarchical reconciliation
2931/// scheduler) reaches for any of the four knowing the value is in
2932/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2933/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2934/// Riak Core / RabbitMQ production-playbook recommendation band
2935/// (`5s..=300s`) and below the clearly-pathological "rolling window
2936/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2937/// a value the author can plausibly want for a very-low-traffic
2938/// long-tail failure-restart window over a hyperscale-flaky child pool,
2939/// but a hard wall above which the rolling-window contract is
2940/// structurally a lifetime-counter contract.
2941///
2942/// Lifted as a typed `pub const` so the bound has exactly one source
2943/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2944/// materializer's admission webhook, the wasm-operator-side
2945/// per-supervisor `MaxIntensity / Period` reconciler, and the
2946/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2947/// from one place. Same shape every other typed upper bound in this
2948/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2949/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2950/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2951/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2952/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2953/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2954/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2955/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2956/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2957pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2958
2959/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2960/// default for the `:supervisor :restart-window` axis — the canonical
2961/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2962/// worker-supervisor default, extracted as a typed `pub const` so every
2963/// substrate-side consumer that resolves "what
2964/// [`SupervisorSpec::restart_window`] value does an author-omitted
2965/// `:restart-window` slot degrade onto?" reaches for exactly one
2966/// substrate-primitive [`Duration`].
2967///
2968/// The `:restart-window` default axis has one production consumer on the
2969/// substrate side today: the [`Default for SupervisorSpec`] impl's
2970/// struct-literal `restart_window` field, which prior to this lift folded
2971/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2972/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2973/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2974/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2975/// *not* fall back to this default on the sibling `:restart-window` axis
2976/// — an author-omitted `:supervisor :restart-window` composes to
2977/// `restart_window: None` (the shared codec's soft-swallow shape),
2978/// keeping author-declared intent ("no reset — never escalate on rolling
2979/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2980/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2981/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2982/// default was split across two files with no compile-time link between
2983/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2984/// `MaxIntensity` half at the substrate primitive while the `Period`
2985/// half rode as an open-coded literal at the composition site, so a
2986/// future coherent rebrand of the paired canonical (a tightening to
2987/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2988/// per-cluster overlay the operator pins through a future
2989/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2990/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2991/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2992/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2993/// roadmap lands) would have had to migrate the `MaxIntensity` half
2994/// through the lifted constant and the `Period` half through a raw
2995/// literal in lockstep or the two halves of the same OTP-canonical
2996/// default would silently drift out of pairing. Lifting the resolution
2997/// rule to a typed `pub const` on the substrate primitive means the
2998/// paired OTP-canonical default migrates as one unit on any future
2999/// axis change.
3000///
3001/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3002/// worker-supervisor default (the closest canonical OTP-shape
3003/// production reference the substrate carries, matching the paired
3004/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3005/// constant is the `Period` denominator of on the same
3006/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3007/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3008/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3009/// this lower default; both are typed [`Duration`] const bounds on the
3010/// `:supervisor :restart-window` axis and now share one accessor
3011/// discipline on the substrate) and above the OTP-`supervisor`
3012/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3013/// rolling window" default is deliberately loose enough to absorb a
3014/// short burst of transient child failures without escalating past the
3015/// supervisor's parent while remaining tight enough for the paired
3016/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3017/// stuck child within a human-scale observation window.
3018///
3019/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3020/// exactly one source of truth on each half — the sibling
3021/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3022/// `Period` `60s` half now share the same substrate-primitive lift
3023/// discipline. Same shape every other typed default in this crate
3024/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3025/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3026/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3027/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3028/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3029/// caixa-flux / caixa-helm rendering axes).
3030pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3031
3032/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3033/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3034/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3035/// worker-supervisor default, extracted as a typed `pub const` so every
3036/// substrate-side consumer that resolves "what
3037/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3038/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3039/// primitive [`RestartStrategy`].
3040///
3041/// The `:estrategia` default axis has three production consumers on the
3042/// substrate side today: the [`Default for RestartStrategy`] impl's
3043/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3044/// `estrategia` field, and the
3045/// [`crate::manifest::Caixa::supervisor_view`] fold's
3046/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3047/// collapse arm — three entry points onto the same OTP-canonical
3048/// `one_for_one` value that prior to this lift folded onto a raw
3049/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3050/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3051/// with no compile-time link back to the paired
3052/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3053/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3054/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3055/// triple was split across three altitudes with no compile-time link
3056/// between the halves: the `MaxIntensity` half rode through the lifted
3057/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3058/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3059/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3060/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3061/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3062/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3063/// intensity/period; an OTP `rest_for_one` widening once the substrate
3064/// discovers startup-order-coupled child cohorts as the more common
3065/// worker-supervisor default; a per-cluster overlay the operator pins
3066/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3067/// §III.2 supervision-canary roadmap acknowledges) would have had to
3068/// migrate the `MaxIntensity` + `Period` halves through the lifted
3069/// constants and the `one_for_one` half through an open-coded arm in
3070/// lockstep or the three halves of the same OTP-canonical default would
3071/// silently drift out of pairing. Lifting the resolution rule to a typed
3072/// `pub const` on the substrate primitive means the paired OTP-canonical
3073/// worker-supervisor default migrates as one unit on any future axis
3074/// change.
3075///
3076/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3077/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3078/// closest canonical OTP-shape production reference the substrate
3079/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3080/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3081/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3082/// failed child, leaving siblings untouched — is the default for tree-of-
3083/// independent-workers use cases the substrate's [`RestartStrategy`]
3084/// discriminator's own docstring already carries as the default arm; it
3085/// composes with the `{5, 60}` restart-intensity ratio to name the same
3086/// substrate-canonical "canonical worker-supervisor" shape the paired
3087/// halves close on their respective axes.
3088///
3089/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3090/// exactly one source of truth on each of its three halves — the sibling
3091/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3092/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3093/// this `one_for_one` strategy half now share the same substrate-
3094/// primitive lift discipline. Same shape every other typed default in
3095/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3096/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3097/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3098/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3099/// upper caps on the paired sibling axes, and the peer
3100/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3101/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3102pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3103
3104/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3105/// default for the `:children :restart` axis — the OTP `permanent`
3106/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3107/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3108/// `pub const` so every substrate-side consumer that resolves "what
3109/// [`ChildSpec::restart`] variant does an author-omitted `:children
3110/// :restart` slot degrade onto?" reaches for exactly one substrate-
3111/// primitive [`RestartPolicy`].
3112///
3113/// Completes the OTP-shape supervisor-tree default set at the substrate
3114/// primitive. The per-`:supervisor` axis already carries all three of its
3115/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3116/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3117/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3118/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3119/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3120/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3121/// the M2 `:supervisor` slot family. The split mattered because the two
3122/// axes resolve *together* on every author-omitted supervisor: a
3123/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3124/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3125/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3126/// `permanent` through an open-coded enum arm, so a future coherent
3127/// rebrand of the OTP-shape default set (an Elixir-shaped
3128/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3129/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3130/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3131/// once the substrate discovers clean-completion-aware children as the
3132/// more common child shape) would have had to migrate three halves
3133/// through typed constants and the fourth through a raw enum arm in
3134/// lockstep or the supervisor-level and child-level defaults would
3135/// silently drift apart.
3136///
3137/// The `:children :restart` default axis has two production consumers on
3138/// the substrate side today: the [`Default for RestartPolicy`] impl's
3139/// return arm, and the serde-side `#[serde(default)]` on
3140/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3141/// :restart` slot through that same impl. Both now key off this one
3142/// substrate primitive, so the future wasm-operator's per-child post-exit
3143/// restart-decision branch, the future M4
3144/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3145/// admission webhook, and the `caixa-operator`'s hierarchical
3146/// reconciliation scheduler's per-child fan-out all reach for one typed
3147/// identifier when they resolve an omitted per-child restart posture.
3148///
3149/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3150/// worker-child restart type — always restart the child regardless of how
3151/// it died, the canonical posture for long-running services that must
3152/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3153/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3154/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3155/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3156/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3157/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3158/// one-shot / clean-completion-aware postures an author declares
3159/// explicitly, never a posture an omitted slot should silently assume.
3160pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3161
3162/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3163/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3164/// `pub const fn` constructor rather than a struct-literal cascade over
3165/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3166/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3167/// lifted consts — one source of truth for the Erlang/OTP-canonical
3168/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3169/// paths every downstream consumer already reaches through (the
3170/// hand-authored-until-now [`Default::default`] the
3171/// `..SupervisorSpec::default()` struct-update-syntax on every
3172/// one-axis-under-test fixture in this crate's test module rests on,
3173/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3174/// every `const`-context consumer reaches through).
3175///
3176/// Extends the [`Default`]-through-const-ctor fold discipline the
3177/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3178/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3179/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3180/// and [`crate::BehaviorSpec`]
3181/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3182/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3183/// typed-slot spec family — extended here onto the M2 supervisor-slot
3184/// [`SupervisorSpec`] whose canonical baseline is not "everything
3185/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3186/// supervisor triple. The `empty()` peer's naming did not fit
3187/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3188/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3189/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3190/// the sibling `Option`-only slots fold to), so this peer is named
3191/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3192/// existing per-arm pin tests
3193/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3194/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3195/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3196/// already reach for. Pinned load-bearing by
3197/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3198/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3199/// [`PartialEq`], sharpening the sibling
3200/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3201/// pins from a per-field lift into a whole-struct one-source-of-truth
3202/// pin — the derived-until-now [`Default::default`] and the
3203/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3204/// construction, not by coincidence).
3205impl Default for SupervisorSpec {
3206    #[inline]
3207    fn default() -> Self {
3208        Self::otp_canonical()
3209    }
3210}
3211
3212impl SupervisorSpec {
3213    /// `const`-context peer of the [`Default for SupervisorSpec`]
3214    /// impl (which routes through this constructor) — returns the
3215    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3216    /// baseline this crate reaches for in every fixture-builder
3217    /// `..SupervisorSpec::default()` struct-update expression and
3218    /// every downstream `SupervisorSpec::default()` seed.
3219    ///
3220    /// Each field routes through the same substrate-canonical
3221    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3222    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3223    /// per-arm pin tests
3224    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3225    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3226    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3227    /// already assert, so a future coherent rebrand of the OTP-canonical
3228    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3229    /// cluster overlay via a future `:restart-window-overrides` slot, a
3230    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3231    /// absorption roadmap acknowledges) migrates through three typed
3232    /// constants in lockstep, and the paired [`Default`] impl inherits
3233    /// every future extension by construction.
3234    ///
3235    /// `pub const fn` rather than the derived-style `Default::default`
3236    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3237    /// [`Default::default`] is not `const` on stable Rust, and
3238    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3239    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3240    /// discipline lets `const`-context callers construct the OTP-
3241    /// canonical baseline at compile time without runtime dispatch on
3242    /// the derived [`Default::default`], the same posture the sibling
3243    /// [`crate::LimitsSpec::empty`] (9739971) /
3244    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3245    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3246    /// spec `pub const fn` constructors carry on the sibling
3247    /// "everything `None`" baseline axis.
3248    ///
3249    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3250    /// of the derived-style [`Default`]" family — sibling of the
3251    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3252    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3253    /// baseline" trio, extended here onto the M2 supervisor-slot
3254    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3255    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3256    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3257    /// than `empty()` to name the actual invariant the return value
3258    /// pins — the same phrasing already used in the per-arm pin tests
3259    /// on this file. Pinned load-bearing by
3260    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3261    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3262    #[must_use]
3263    pub const fn otp_canonical() -> Self {
3264        Self {
3265            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3266            max_restarts: default_max_restarts(),
3267            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3268            children: Vec::new(),
3269        }
3270    }
3271
3272    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3273    /// sibling-restart-strategy scalar accessor every consumer that
3274    /// dispatches on the supervisor's per-sibling restart-decision shape
3275    /// keys off — returns the author-declared `:supervisor :estrategia`
3276    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3277    /// the typed slot's own [`RestartStrategy`] storage.
3278    ///
3279    /// The `:supervisor :estrategia` slot carries the closed-set
3280    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3281    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3282    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3283    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3284    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3285    /// every child started after it, the Erlang/OTP `rest_for_one`
3286    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3287    /// dynamic children of the same shape, the Erlang/OTP
3288    /// `simple_one_for_one` per-session default) that every downstream
3289    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3290    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3291    /// paired coherently with the sibling `:children` axis
3292    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3293    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3294    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3295    /// downstream consumer that reads the strategy keys off this scalar
3296    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3297    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3298    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3299    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3300    /// strategy print line, the future wasm-operator's per-supervisor
3301    /// sibling-restart-strategy branch, the future M4
3302    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3303    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3304    /// reconciliation scheduler's per-strategy fan-out).
3305    ///
3306    /// Prior to this lift the `.estrategia` field was accessed inline at
3307    /// two production sites in `caixa-core/src/supervisor.rs` — the
3308    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3309    /// `match self.estrategia { … }` partition dispatch, and the
3310    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3311    /// carrier at `estrategia: self.estrategia` — two open-coded
3312    /// field-accesses that expressed no compile-time link back to the
3313    /// typed slot. A future extension of the `:supervisor :estrategia`
3314    /// axis to a richer author surface (a per-cluster strategy override
3315    /// the operator pins through a future `:supervisor :estrategia-overrides`
3316    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3317    /// acknowledges, a per-tenant strategy-alias table the M4 CR
3318    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3319    /// derivation the future adaptive-supervision engine computes from
3320    /// child-failure-history topology, a per-child-cohort strategy split
3321    /// the future `RestForCohort` extension acknowledged by the
3322    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3323    /// would have had to be threaded through every open-coded copy in
3324    /// lockstep — one consumer reading the raw variant while a peer read
3325    /// the operator-resolved variant would silently split the
3326    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3327    /// the actual partition-dispatch input the empty-children refusal
3328    /// arm reached under, a two-consumer split at the validator far from
3329    /// the source `caixa.lisp` with no field naming the strategy-drift
3330    /// root cause. Lifting the resolution rule to a typed method on the
3331    /// substrate primitive means every downstream consumer of the
3332    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3333    /// reaches for exactly one typed dispatch — the resolver's accept-set
3334    /// migrates as a unit on any future axis addition.
3335    ///
3336    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3337    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3338    /// per-`:placement` distribution-strategy axis — same "one typed
3339    /// dispatch on the substrate primitive, thin projections at each
3340    /// consumer" discipline extended onto the M2 supervisor-slot
3341    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3342    /// scalar axis. The two typed axes (`Placement::estrategia` on the
3343    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3344    /// Supervisor side) now share one accessor discipline for the shared
3345    /// substrate concept "a `Copy`-projected closed-set enum-arm
3346    /// discriminator that partitions the downstream renderer's per-arm
3347    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3348    /// `SupervisorSpec` type — companion to the sibling per-`:children`
3349    /// [`crate::ChildSpec::nome`] (57c61d0) /
3350    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3351    /// scalar accessors on the sibling per-`:children` `String`-carry
3352    /// axes. Named `estrategia()` to match the storage field's name and
3353    /// the peer [`crate::Placement::estrategia`] method-name discipline
3354    /// verbatim; the accessor's identity name maps onto the canonical
3355    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3356    /// docstring already carries.
3357    ///
3358    /// Declared `pub const fn` to close the M2 supervisor-slot
3359    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3360    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3361    /// (converted in this commit) `Copy`-composite-enum accessor, peer
3362    /// of the sibling M2 per-`:supervisor`
3363    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3364    /// already lifted, and mirror of the peer M3 mesh-slot
3365    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3366    /// `Copy`-return `pub const fn` scalar accessor whose method-name
3367    /// discipline this accessor was authored to match. Every downstream
3368    /// substrate-side `const`-context consumer of the per-`:supervisor`
3369    /// sibling-restart-strategy scalar (a future module-scope `const
3370    /// _:() = assert!(matches!(sup.estrategia(),
3371    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3372    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3373    /// admission-webhook `const fn` per-supervisor strategy-arm floor
3374    /// over a typed [`SupervisorSpec`], any future `const fn`
3375    /// supervisor-tree composer over the substrate primitive that fans
3376    /// on the sibling-restart-strategy at compile time) now reaches
3377    /// through the same typed dispatch on the substrate primitive at
3378    /// const-eval time as at runtime. A future non-`Copy`-return
3379    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3380    /// migration once the substrate grows per-cluster strategy overlays
3381    /// the [`SupervisorSpec`] docstring already anticipates, a
3382    /// per-tenant strategy-alias table the M4 CR materializer resolves
3383    /// per-CR) that would drop the `const` qualifier fails the
3384    /// fail-before-pass-after pin
3385    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3386    /// caixa-core build time rather than surfacing as a downstream
3387    /// consumer regression.
3388    #[must_use]
3389    pub const fn estrategia(&self) -> RestartStrategy {
3390        self.estrategia
3391    }
3392
3393    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3394    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3395    /// reads the supervisor's per-`:restart-window` restart-budget count
3396    /// keys off — returns the author-declared `:supervisor :max-restarts`
3397    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3398    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3399    /// borrow of `&self` past the call). Non-optional (the `u32` field
3400    /// carries the restart-budget count as a required axis with a
3401    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3402    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3403    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3404    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3405    ///
3406    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3407    /// `MaxIntensity` restart-budget count that pairs with the sibling
3408    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3409    /// restart-intensity ratio the supervisor trips its own escalation on
3410    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3411    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3412    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3413    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3414    /// upper-cap bracket at
3415    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3416    /// wasm-operator's per-supervisor restart-intensity counter's
3417    /// budget-vs-count comparator, the future M4
3418    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3419    /// webhook, the `caixa-operator`'s hierarchical reconciliation
3420    /// scheduler's per-supervisor escalation-decision branch, every
3421    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3422    /// offending count verbatim for `feira lint` rendering).
3423    ///
3424    /// Prior to this lift the `.max_restarts` field was accessed inline at
3425    /// one production site in `caixa-core/src/supervisor.rs` — the
3426    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3427    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3428    /// that expressed no compile-time link back to the typed slot. A
3429    /// future extension of the `:max-restarts` axis to a richer author
3430    /// surface (a per-cluster restart-budget override the operator pins
3431    /// through a future `:supervisor :max-restarts-overrides` slot the
3432    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3433    /// a per-tenant restart-budget-alias table the M4 CR materializer
3434    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3435    /// the future adaptive-supervision engine computes from child-failure-
3436    /// history topology, a promotion of the plain `u32` count to a richer
3437    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3438    /// budget-partition slot comes into scope) would have had to be
3439    /// threaded through every open-coded copy in lockstep or the validate
3440    /// gate and the future M4 emit path would silently disagree on which
3441    /// restart-budget count a given supervisor resolves to — an author's
3442    /// `:max-restarts 5` would satisfy validate while the emit path
3443    /// silently read a drifted other value (a `:max-restarts 10000`
3444    /// no-op supervisor at the emit boundary would carry the author's
3445    /// declared `5` verbatim in `feira lint` output while the future
3446    /// wasm-operator's restart-intensity counter operated under the
3447    /// drifted count), a two-consumer split at the validator far from the
3448    /// source `caixa.lisp` with no field naming the restart-budget-drift
3449    /// root cause. Lifting the resolution rule to a typed method on the
3450    /// substrate primitive means every downstream consumer of the
3451    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3452    /// for exactly one typed dispatch — the resolver's accept-set migrates
3453    /// as a unit on any future axis addition.
3454    ///
3455    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3456    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3457    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3458    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3459    /// the substrate primitive, thin projections at each consumer"
3460    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3461    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3462    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3463    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3464    /// one accessor discipline for the shared substrate concept "a
3465    /// `Copy`-projected required `u32` count that trips the next-higher
3466    /// protection layer after N events in a rolling window" — both are
3467    /// counters with identical degenerate-at-the-high-end shape and share
3468    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3469    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3470    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3471    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3472    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3473    /// the storage field's name verbatim and the peer
3474    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3475    /// accessor's identity maps onto the canonical OTP-shape supervision
3476    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3477    /// already carries.
3478    #[must_use]
3479    pub const fn max_restarts(&self) -> u32 {
3480        self.max_restarts
3481    }
3482
3483    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3484    /// `Period` sliding-window scalar accessor every consumer of the
3485    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3486    /// keys off — returns the author-declared `:supervisor :restart-window`
3487    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3488    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3489    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3490    /// value; no borrow of `&self` past the call). `None` when the slot is
3491    /// absent (the canonical "never reset — every restart across the
3492    /// supervisor's lifetime counts against the sibling `:max-restarts`
3493    /// budget" sentinel the field's own docstring names and the peer
3494    /// `validate_accepts_none_restart_window` pin locks in on the
3495    /// [`SupervisorSpec::validate`] entry-side).
3496    ///
3497    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3498    /// `Period` sliding-observation-interval that pairs with the sibling
3499    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3500    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3501    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3502    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3503    /// default). The typed slot's `Option<Duration>` accept-set —
3504    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3505    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3506    /// `Period > 0`; a zero period either trips on the first failure or
3507    /// never trips depending on operator interpretation, neither of which
3508    /// is the author's intent — omit the slot to express "no reset";
3509    /// carry a positive duration to express the sliding window),
3510    /// integer-millisecond canonical form enforced through
3511    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3512    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3513    /// future wasm-operator's per-supervisor restart-intensity counter
3514    /// quantizes at milliseconds), upper-bounded by
3515    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3516    /// supervisor rolling window any operationally-reachable supervisor
3517    /// can honor without spanning multiple scheduler epochs the
3518    /// hierarchical-reconciliation scheduler treats as independent) —
3519    /// maps onto the future wasm-operator (M3) per-supervisor
3520    /// restart-intensity counter's rolling-observation-interval, the
3521    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3522    /// per-`spec.restartWindow` admission webhook, and the sibling
3523    /// `duration_codec`-serialized wire scalar every downstream consumer
3524    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3525    /// keys off.
3526    ///
3527    /// Prior to this lift the `.restart_window` field was accessed inline
3528    /// at one production site in `caixa-core/src/supervisor.rs` — the
3529    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3530    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3531    /// open-coded field-access that expressed no compile-time link back to
3532    /// the typed slot. A future extension of the `:restart-window` axis to
3533    /// a richer author surface (a per-cluster restart-window override the
3534    /// operator pins through a future `:supervisor :restart-window-overrides`
3535    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3536    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3537    /// materializer resolves per-CR, a per-supervisor dynamic
3538    /// restart-window derivation the future adaptive-supervision engine
3539    /// computes from child-failure-history topology, a promotion of the
3540    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3541    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3542    /// partition slot comes into scope) would have had to be threaded
3543    /// through every open-coded copy in lockstep or the validate gate and
3544    /// the future M4 emit path would silently disagree on which
3545    /// restart-window a given supervisor resolves to — an author's
3546    /// `:restart-window "60s"` would satisfy validate while the emit path
3547    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3548    /// authored slot at the emit boundary would carry the author's
3549    /// declared window verbatim in `feira lint` output while the future
3550    /// wasm-operator's restart-intensity counter operated under a
3551    /// drifted window, or vice versa: an author's `:restart-window ()`
3552    /// would carry the "never reset" sentinel through validate while the
3553    /// emit path silently substituted a default sliding window), a
3554    /// two-consumer split at the validator far from the source
3555    /// `caixa.lisp` with no field naming the restart-window-drift root
3556    /// cause. Lifting the resolution rule to a typed method on the
3557    /// substrate primitive means every downstream consumer of the
3558    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3559    /// surface reaches for exactly one typed dispatch — the resolver's
3560    /// accept-set migrates as a unit on any future axis addition.
3561    ///
3562    /// Third `Copy`-return accessor on the M2 supervisor-slot
3563    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3564    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3565    /// payload rather than a `Copy`-scalar, and the per-`:children`
3566    /// [`crate::ChildSpec::nome`] (57c61d0) /
3567    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3568    /// scalar accessors already close the per-element `String`-carry
3569    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3570    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3571    /// per-outermost-call wall-clock-deadline axis and the peer M3
3572    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3573    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3574    /// three share the shared substrate concept "a `Copy`-projected
3575    /// optional `Duration` that carries a positive integer-millisecond
3576    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3577    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3578    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3579    /// bracket-helper the three axes each route through. Named
3580    /// `restart_window()` to match the storage field's name verbatim and
3581    /// the peer [`crate::LimitsSpec::wall_clock`] /
3582    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3583    /// accessor's identity maps onto the canonical OTP-shape supervision
3584    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3585    /// already carries.
3586    #[must_use]
3587    pub const fn restart_window(&self) -> Option<Duration> {
3588        self.restart_window
3589    }
3590
3591    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3592    /// static-child-list slice accessor every consumer that walks the
3593    /// supervisor's declared child set keys off — returns the author-
3594    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3595    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3596    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3597    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3598    /// through). Non-optional: an empty slice is the load-bearing
3599    /// "author declared `:children ()`" sentinel every consumer of the
3600    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3601    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3602    /// three strategies require a non-empty slice — the paired
3603    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3604    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3605    /// partition on both arms).
3606    ///
3607    /// The `:supervisor :children` slot carries the OTP-shaped static
3608    /// child list the supervisor materializes one ComputeUnit per
3609    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3610    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3611    /// through the tatara-lisp `:children` author surface onto a typed
3612    /// `Vec<ChildSpec>` whose per-element `(nome(),
3613    /// versao_requirement(), restart)` triple the per-child
3614    /// [`SupervisorSpec::validate`] loop already gates through the
3615    /// lifted [`ChildSpec::nome`] (57c61d0) /
3616    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3617    /// Every downstream consumer that fans on the static child list
3618    /// keys off this slice (the [`SupervisorSpec::validate`]
3619    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3620    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3621    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3622    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3623    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3624    /// materialization loop, the future M4
3625    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3626    /// admission-webhook fan-out, the future `feira app graph`
3627    /// per-supervisor tree-print traversal).
3628    ///
3629    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3630    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3631    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3632    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3633    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3634    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3635    /// validate loop's `for child in &self.children` traversal head —
3636    /// three open-coded field-accesses that expressed no compile-time
3637    /// link back to the typed slot. A future extension of the
3638    /// `:supervisor :children` axis to a richer author surface (a
3639    /// per-cluster child-set overlay the operator pins through a future
3640    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3641    /// supervision-canary roadmap acknowledges, a per-tenant
3642    /// child-set-alias table the M4 CR materializer resolves per-CR,
3643    /// a per-supervisor dynamic-child derivation the future adaptive-
3644    /// supervision engine computes from child-failure-history topology,
3645    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3646    /// `{static, dynamic}` partition once Erlang/OTP's
3647    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3648    /// would have had to be threaded through all three open-coded copies
3649    /// in lockstep or one consumer would silently disagree with the
3650    /// peers on which child-set a given supervisor resolves to — the
3651    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3652    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3653    /// would silently split the partition-dispatch's two-arm coherence
3654    /// (a supervisor that satisfies neither arm's precondition, or that
3655    /// satisfies both, at the cost of the paired
3656    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3657    /// silently drifting from the per-child validate loop's actual
3658    /// traversal input), a three-consumer split at the validator far
3659    /// from the source `caixa.lisp` with no field naming the
3660    /// child-set-drift root cause. Lifting the resolution rule to a
3661    /// typed method on the substrate primitive means every downstream
3662    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3663    /// surface reaches for exactly one typed dispatch — the resolver's
3664    /// accept-set migrates as a unit on any future axis addition.
3665    ///
3666    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3667    /// — the seed for the same "one typed dispatch on the substrate
3668    /// primitive, thin projections at each consumer" discipline the
3669    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3670    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3671    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3672    /// onto the first `Vec`-carry axis on the substrate. The four peer
3673    /// `Vec`-carry axes still unlifted at the time of this seed —
3674    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3675    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3676    /// (`Vec<Membro>` per-Aplicacao member list),
3677    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3678    /// per-Aplicacao WIT-typed edge list),
3679    /// [`crate::UpgradeFromEntry::instructions`]
3680    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3681    /// — inherit this accessor's discipline as future compounding runs
3682    /// migrate their consumers onto the shared slice-return shape.
3683    /// Fourth (and final) accessor on the M2 supervisor-slot
3684    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3685    /// [`SupervisorSpec::estrategia`] (eafb619) /
3686    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3687    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3688    /// the last unlifted per-`:supervisor` field axis (the
3689    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3690    /// per-`:supervisor` reader now routes through a typed dispatch on
3691    /// the substrate primitive. Named `children()` to match the storage
3692    /// field's name verbatim and the tatara-lisp author-surface term
3693    /// (`:children`) the field's own docstring already carries; the
3694    /// accessor's identity maps onto the canonical OTP-shape
3695    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3696    /// docstring already reaches for ("Static children ..."). Returns
3697    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3698    /// consumer of the child list treats it as a read-only sequence —
3699    /// the slice-view is the narrowest borrow that supports every
3700    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3701    /// index, `.len()`) without leaking the backing `Vec`'s
3702    /// grow/push/reserve surface that no consumer of the typed view
3703    /// reaches for (the storage-side `Vec` remains reachable through
3704    /// the `pub children` field for the mutation-carrying
3705    /// `Caixa::supervisor_view` fold-in path in
3706    /// `manifest.rs:supervisor_view`).
3707    #[must_use]
3708    pub const fn children(&self) -> &[ChildSpec] {
3709        self.children.as_slice()
3710    }
3711
3712    /// Validate the supervisor's typed shape — strategy ↔ children
3713    /// invariants, max_restarts > 0, restart_window > 0 when set,
3714    /// per-child non-empty + duplicate-free names.
3715    ///
3716    /// Mirrors the value-shape discipline applied to every other
3717    /// typed slot:
3718    ///
3719    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3720    ///     same "0 means the opposite of what you think" footgun
3721    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3722    ///     timeout as `infinite`), `:politicas :circuit-breaker
3723    ///     :window`, and `:limits :wall-clock`. The
3724    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3725    ///     `supervisor` requires `Period > 0`; a zero period either
3726    ///     trips on the first failure or never trips depending on
3727    ///     operator interpretation, neither of which is the
3728    ///     author's intent. Omit `:restart-window` to express "no
3729    ///     reset"; carry a positive duration to express the window.
3730    ///   - duplicate `:children` `:caixa` names are the same
3731    ///     graph-node-set / multiset distinction closed for
3732    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3733    ///     and `:entrada :paths` (eb3456d). Two children with the
3734    ///     same `:caixa` materialize as two ComputeUnits with the
3735    ///     same name in the cluster's HelmRelease values, one
3736    ///     silently overwriting the other. Erlang/OTP's
3737    ///     `child_spec.id` is required-unique per supervisor;
3738    ///     pleme-io enforces the same set-not-multiset shape on
3739    ///     `:caixa` (the load-bearing identity in our renderer).
3740    pub fn validate(&self) -> Result<(), SupervisorError> {
3741        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3742        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3743        // error carrier's `estrategia:` field through the lifted
3744        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3745        // `self.estrategia` field access — the two production consumers
3746        // of the per-`:supervisor` sibling-restart-strategy scalar now
3747        // key off exactly one typed dispatch on the substrate primitive,
3748        // so any future rebrand on the axis (a per-cluster strategy
3749        // override the operator pins through a future `:supervisor
3750        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3751        // the M4 CR materializer resolves per-CR) migrates as a single
3752        // caixa-core edit rather than a coordinated rewrite of the two
3753        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3754        // (921fe1b) four-consumer migration on the per-`:placement`
3755        // distribution-strategy axis.
3756        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3757        // dispatch's paired `.is_empty()` cross-slot refusal probes
3758        // (the `SimpleOneForOne`-arm
3759        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3760        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3761        // refusal) through the lifted [`SupervisorSpec::children`]
3762        // slice-return accessor rather than the raw `self.children`
3763        // field access — the two paired production consumers of the
3764        // per-`:supervisor` static-child-list scalar-shape now key off
3765        // exactly one typed dispatch on the substrate primitive, so any
3766        // future rebrand on the axis (a per-cluster child-set overlay
3767        // the operator pins through a future `:supervisor
3768        // :children-overrides` slot, a per-tenant child-set-alias table
3769        // the M4 CR materializer resolves per-CR) migrates as a single
3770        // caixa-core edit rather than a coordinated rewrite of the
3771        // paired arms — first slice-return migration on any typed slot,
3772        // seed for the peer per-`:placement :clusters`,
3773        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3774        // :instructions` `Vec`-carry axes.
3775        match self.estrategia() {
3776            RestartStrategy::SimpleOneForOne => {
3777                // SimpleOneForOne: children added at runtime. Static
3778                // list must be empty (one shape declared elsewhere).
3779                if !self.children().is_empty() {
3780                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3781                }
3782            }
3783            _ => {
3784                if self.children().is_empty() {
3785                    return Err(SupervisorError::no_children(self.estrategia()));
3786                }
3787            }
3788        }
3789        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3790        // axis. See [`crate::render::require_positive_bounded_u32`] for
3791        // the ordering discipline (zero-floor arm strictly precedes cap
3792        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3793        // diagnostic with its counter-axis remediation directly named,
3794        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3795        // cap-arm miss). Until this bracket landed the top edge ran all
3796        // the way to `u32::MAX` and a struct-literal
3797        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3798        // equivalent author-surface `:max-restarts 100000` /
3799        // `:max-restarts 4294967295` typo landing in the slot) silently
3800        // passed validate. The runtime substrate consuming the value
3801        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3802        // wasm-operator's per-supervisor restart-intensity counter, the
3803        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3804        // admission webhook) then turned a typed `:max-restarts`
3805        // policy into a no-op supervisor: the escalation threshold is
3806        // structurally so high that no realistic
3807        // restarts-per-`:restart-window` traffic shape can reach it,
3808        // the supervisor never escalates to its parent, and a bad
3809        // child can loop inside the window indefinitely with the
3810        // parent supervisor structurally never receiving the "this
3811        // subtree has exceeded its restart budget" signal the typed
3812        // slot is meant to express. The bracket set is
3813        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3814        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3815        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3816        // both are "trip the next-higher protection layer after N
3817        // events in a rolling window" counters with identical
3818        // degenerate-at-the-high-end shape and now share one canonical
3819        // bracket helper. The bracket precedes the sibling
3820        // `:restart-window` zero-floor / canonical-millisecond arms so
3821        // an over-cap `max_restarts` paired with a structurally invalid
3822        // window surfaces the bracket diagnostic first, mirroring the
3823        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3824        // ordering on the peer `:politicas :circuit-breaker` slot.
3825        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3826        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3827        // accessor rather than the raw `self.max_restarts` field access —
3828        // the one production consumer of the per-`:supervisor`
3829        // restart-budget-count scalar now keys off exactly one typed
3830        // dispatch on the substrate primitive, so any future rebrand on
3831        // the axis (a per-cluster restart-budget override the operator
3832        // pins through a future `:supervisor :max-restarts-overrides`
3833        // slot, a per-tenant restart-budget-alias table the M4 CR
3834        // materializer resolves per-CR) migrates as a single caixa-core
3835        // edit rather than a coordinated rewrite — sibling of the peer M3
3836        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3837        // the per-`:politicas :circuit-breaker :max-failures` axis.
3838        crate::render::require_positive_bounded_u32(
3839            self.max_restarts(),
3840            SUPERVISOR_MAX_RESTARTS_MAX,
3841            || SupervisorError::ZeroMaxRestarts,
3842            SupervisorError::max_restarts_exceeds_cap,
3843        )?;
3844        // Route the [`SupervisorSpec::validate`] `:restart-window`
3845        // zero-floor + integer-millisecond canonical-form + upper-cap
3846        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3847        // accessor rather than the raw `self.restart_window` field access —
3848        // the one production consumer of the per-`:supervisor`
3849        // restart-intensity-denominator scalar now keys off exactly one
3850        // typed dispatch on the substrate primitive, so any future rebrand
3851        // on the axis (a per-cluster restart-window override the operator
3852        // pins through a future `:supervisor :restart-window-overrides`
3853        // slot, a per-tenant restart-window-alias table the M4 CR
3854        // materializer resolves per-CR) migrates as a single caixa-core
3855        // edit rather than a coordinated rewrite — sibling of the peer M2
3856        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3857        // on the per-`:limits :wall-clock` axis and the peer M3
3858        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3859        // per-`:politicas :timeout` axis.
3860        if let Some(w) = self.restart_window() {
3861            // Zero-floor + integer-millisecond canonical-form +
3862            // upper-cap bracket on the typed `:restart-window` axis.
3863            // See
3864            // [`crate::render::require_positive_canonical_bounded_duration`]
3865            // for the full three-arm ordering discipline (zero-floor
3866            // strictly precedes canonical-form so `Duration::ZERO`
3867            // surfaces the self-locating `RestartWindowZero`
3868            // diagnostic; canonical-form strictly precedes the cap arm
3869            // so a sub-millisecond above-cap value surfaces the more
3870            // fundamental round-trip-shape diagnostic first) and the
3871            // three peer typed-`Duration` sites that share this
3872            // canonical bracket ([`crate::MeshPolicy::timeout`],
3873            // [`crate::CircuitBreaker::window`],
3874            // [`crate::LimitsSpec::wall_clock`]). Every validated
3875            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3876            // (1ms..=1h), integer-millisecond granularity.
3877            crate::render::require_positive_canonical_bounded_duration(
3878                w,
3879                SUPERVISOR_RESTART_WINDOW_MAX,
3880                || SupervisorError::RestartWindowZero,
3881                SupervisorError::restart_window_not_canonical,
3882                SupervisorError::restart_window_exceeds_cap,
3883            )?;
3884        }
3885        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3886        // detection fan-out loop through the lifted named per-slot gate
3887        // [`SupervisorSpec::validate_children`] rather than an inline
3888        // three-per-child cascade — every future consumer that wants to
3889        // re-check only the `:children` slot's per-entry axes (the M4
3890        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3891        // admission webhook re-validating one added/renamed child, the
3892        // future wasm-operator's per-child dynamic-add re-validator on
3893        // the `SimpleOneForOne` runtime-add path once dynamic-children
3894        // graduate to a typed slot, a future partial re-validator on a
3895        // per-`:children`-entry patch) reaches every per-entry axis
3896        // through one dispatch rather than re-inlining the three-arm
3897        // cascade in lockstep with `validate` or paying the peer
3898        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3899        // reach one entry check. Sibling of the peer M3 mesh-slot
3900        // per-slot gate family (`validate_membros` — the exact peer on
3901        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3902        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3903        // `validate_placement`; `validate_politicas` routing through
3904        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3905        // per-slot gate discipline now spans both the M3 mesh-slot
3906        // family and the M2 `:children` per-child-cascade axis on one
3907        // shape: one named per-slot gate per typed per-entry loop.
3908        self.validate_children()?;
3909        Ok(())
3910    }
3911
3912    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3913    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3914    /// gate, and duplicate-`:caixa` dedup arm into one call every
3915    /// consumer that wants to re-validate one `:children` entry (or the
3916    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3917    /// admits reaches through.
3918    ///
3919    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3920    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3921    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3922    /// duplicate-`:caixa` dedup), lifted to one named substrate
3923    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3924    /// materializer's admission webhook re-checking one added or renamed
3925    /// child, the future wasm-operator's per-child dynamic-add
3926    /// re-validator on the `SimpleOneForOne` runtime-add path once
3927    /// dynamic-children graduate to a typed slot, a future partial
3928    /// re-validator on a per-`:children`-entry patch — each reaches the
3929    /// three per-entry axes through this one dispatch rather than
3930    /// re-inlining the three-arm cascade in lockstep with `validate`
3931    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3932    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3933    /// reach one entry check.
3934    ///
3935    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3936    /// through [`SupervisorSpec::children`] rather than borrowing one
3937    /// threaded down from `validate`, the same posture the peer M3
3938    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3939    /// [`crate::AplicacaoSpec::validate_contratos`],
3940    /// [`crate::AplicacaoSpec::validate_entrada`],
3941    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3942    /// consumer that reaches this gate directly (without first calling
3943    /// `validate`) still runs the full per-child cascade — pinned by
3944    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3945    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3946    /// + `validate_children_is_self_contained_on_children_slot`.
3947    ///
3948    /// The three per-entry arms run in the same canonical order the
3949    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3950    /// the diagnostic every author-declared per-`:children` entry surfaces
3951    /// through `validate` is byte-equal to the diagnostic this gate
3952    /// surfaces when called directly — the equivalence-pin pair
3953    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3954    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3955    /// asserts the two altitudes discriminate the same set on every
3956    /// per-entry-covered input.
3957    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3958        let mut seen = std::collections::HashSet::new();
3959        for child in self.children() {
3960            // Every emitted cluster artifact's `metadata.name` for a
3961            // supervised child derives from this `:children :caixa` value
3962            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3963            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3964            // label value on every child's pod identity, and the per-
3965            // child K8s [`Service`][svc] `metadata.name` the future
3966            // wasm-operator (M3) provisions for inter-child supervision
3967            // tree wiring. Each apiserver-side schema on each landing
3968            // site enforces the DNS-1123 label rule on admission; a
3969            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3970            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3971            // UUID-shaped mistaken-identity slug) silently passes the
3972            // prior empty-/duplicate-only gate and the failure surfaces
3973            // at `kubectl apply` time as a `metadata.name: Invalid value`
3974            // rejection, far from the source caixa.lisp, with no field
3975            // naming the offending `:children` entry. Lifting the gate
3976            // to caixa-build time mirrors the `:membros :caixa` value-
3977            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3978            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3979            // identifier axis — the supervisor tree's child names —
3980            // through the lifted
3981            // [`crate::render::require_valid_dns_1123_label`] gate the
3982            // seven peer name axes (`:membros :caixa`, `:placement
3983            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3984            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3985            // route through, so drift between the eight axes' accepted
3986            // DNS-1123-label sets is structurally impossible.
3987            //
3988            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3989            crate::render::require_valid_dns_1123_label(
3990                child.nome(),
3991                || SupervisorError::EmptyChildName,
3992                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3993            )?;
3994            // The author surface for `:children :versao` is the same
3995            // Cargo-shaped semver requirement string `:deps :versao` and
3996            // `:membros :versao` carry — and the lacre pipeline resolves
3997            // all three axes through the same
3998            // [`crate::version::parse_requirement`] entry-point. The
3999            // shared [`crate::render::require_valid_versao_requirement`]
4000            // helper brackets the empty-first + parse cascade both peer
4001            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4002            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4003            // :versao`) route through, so drift between the three axes'
4004            // accepted requirement sets is structurally impossible and
4005            // the parse-side no-op the empty-first arm closes (semver's
4006            // empty parse yields an implicit `*`) lives in exactly one
4007            // predicate. Every `ChildSpec::versao` past validate is
4008            // round-trippable through [`crate::parse_requirement`]
4009            // without re-checking at the resolver layer, and the three
4010            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4011            // are now structurally equivalent by construction.
4012            crate::render::require_valid_versao_requirement(
4013                child.versao_requirement(),
4014                || SupervisorError::empty_child_version(child.nome()),
4015                |reason| {
4016                    SupervisorError::child_versao_invalid(
4017                        child.nome(),
4018                        child.versao_requirement(),
4019                        reason,
4020                    )
4021                },
4022            )?;
4023            crate::render::insert_first_seen(&mut seen, child.nome(), || {
4024                SupervisorError::duplicate_child_caixa(child.nome())
4025            })?;
4026        }
4027        Ok(())
4028    }
4029}
4030
4031/// Cross-slot coherence gate on the supervision tree: no
4032/// `:children :caixa` entry may name the supervisor's own `:nome`.
4033///
4034/// A supervisor that lists itself as a child is a degenerate self-parent
4035/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4036/// specs reference *distinct* child processes; a supervisor is never its
4037/// own child), and the wasm-operator's hierarchical reconciliation would
4038/// otherwise be handed a node that is its own parent: a one-node cycle it
4039/// either rejects far from the source `caixa.lisp` or recurses on. Because
4040/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4041/// lacre closure root), a child whose `:caixa` equals the supervisor's
4042/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4043///
4044/// Lives outside [`SupervisorSpec::validate`] because the typed view
4045/// carries the children but not the parent `:nome`; mirrors the
4046/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4047/// (which likewise reads one slot against another at the
4048/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4049/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4050/// node to itself is structurally not a tree/mesh edge" discipline, here
4051/// on the supervision-tree axis.
4052pub fn validate_no_self_supervision(
4053    children: &[ChildSpec],
4054    parent_nome: &str,
4055) -> Result<(), SupervisorError> {
4056    for child in children {
4057        if child.nome() == parent_nome {
4058            return Err(SupervisorError::child_supervises_self(parent_nome));
4059        }
4060    }
4061    Ok(())
4062}
4063
4064#[derive(Debug, Error, PartialEq, Eq)]
4065pub enum SupervisorError {
4066    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4067    NoChildren { estrategia: RestartStrategy },
4068    #[error(
4069        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4070    )]
4071    SimpleOneForOneWithStaticChildren,
4072    #[error(":max-restarts must be > 0")]
4073    ZeroMaxRestarts,
4074    #[error(
4075        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4076         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4077         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4078         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4079         can reach it, so the supervisor never escalates to its parent and a bad child can \
4080         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4081         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4082         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4083         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4084         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4085         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4086         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4087         band) or restructure the supervision tree (split the flaky child into its own \
4088         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4089    )]
4090    MaxRestartsExceedsCap { max_restarts: u32 },
4091    #[error(
4092        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4093         requires Period > 0; a zero window either trips on the first failure or \
4094         never trips depending on operator interpretation. Omit :restart-window to \
4095         express `never reset`; carry a positive duration to express the window."
4096    )]
4097    RestartWindowZero,
4098    #[error(
4099        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4100         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4101         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4102         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4103         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4104    )]
4105    RestartWindowNotCanonical { window: Duration },
4106    #[error(
4107        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4108         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4109         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4110         failure-counting window is structurally so long that transient restarts are never \
4111         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4112         when the child has exceeded its restart budget within the recent window` to `trip the \
4113         parent when the child has exceeded its restart budget over its lifetime`, and the \
4114         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4115         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4116         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4117         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4118         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4119         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4120         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4121         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4122         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4123         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4124         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4125         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4126         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4127         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4128         hiding it behind a rolling-window declaration the cap arm rejects)"
4129    )]
4130    RestartWindowExceedsCap { window: Duration },
4131    #[error("child entry has empty :caixa name")]
4132    EmptyChildName,
4133    #[error(
4134        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4135         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4136         name / label value the child name lands in — the per-child \
4137         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4138         label value, and the future wasm-operator per-child Service `metadata.name` \
4139         — each apiserver-side schema rejects names that don't match; use a \
4140         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4141    )]
4142    ChildCaixaInvalid { caixa: String, reason: String },
4143    #[error("child {caixa:?} has empty :versao constraint")]
4144    EmptyChildVersion { caixa: String },
4145    #[error(
4146        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4147         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4148         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4149         `:membros :versao` carry; the lacre pipeline resolves all three \
4150         through the same parser)"
4151    )]
4152    ChildVersaoInvalid {
4153        caixa: String,
4154        versao: String,
4155        reason: String,
4156    },
4157    #[error(
4158        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4159         child_spec.id per supervisor; duplicate children materialize as duplicate \
4160         ComputeUnits in the rendered chart, one silently overwriting the other)"
4161    )]
4162    DuplicateChildCaixa { caixa: String },
4163    #[error(
4164        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4165         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4166         OTP child specs reference distinct child processes). Since every :nome is a \
4167         globally-unique substrate identity, a child naming the supervisor's own :nome \
4168         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4169         self-referential :children entry or rename it to the actual child caixa."
4170    )]
4171    ChildSupervisesSelf { caixa: String },
4172}
4173
4174// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4175// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4176// and [`validate_no_self_supervision`] onto one substrate primitive per
4177// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4178// `LayoutError`-envelope constructor families the peer
4179// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4180// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4181// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4182// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4183// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4184// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4185// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4186// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4187// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4188// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4189// variants on `{ de, para }`) already at that discipline on the peer
4190// `AplicacaoError` envelopes.
4191//
4192// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4193// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4194// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4195// self-supervision arm) opened the identical
4196// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4197// the exact "same block re-inlined at every consumer" shape the PRIME
4198// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4199// `AplicacaoError` families each closed on their sibling envelopes. The
4200// three variants share one `{ caixa: String }` shape, so the fold routes
4201// each wire-up site through one dispatch per typed variant.
4202//
4203// The macro below generates one static constructor per variant of shape
4204// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4205// collapses onto one dispatch:
4206// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4207// struct-literal on the same `&str` fixture. The uniform one-field
4208// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4209// macro — rather than at every wire-up site. Every constructor is
4210// `#[must_use]` so a caller who mistakenly discards the constructed error
4211// trips a compile warning at the wire-up site.
4212//
4213// Every future consumer that wants to construct one of these three
4214// variants outside `SupervisorSpec::validate_children` /
4215// `validate_no_self_supervision` — a deferred
4216// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4217// webhook re-checking one added/renamed child, a future
4218// `feira validate --supervisor` per-caixa admission verb, a per-child
4219// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4220// once dynamic-children graduate to a typed slot, a per-Supervisor
4221// overlay resolver rejecting a duplicate/self-supervising child against
4222// a cluster-local snapshot — now reaches each variant through one call
4223// rather than re-inlining the three-line struct-literal in lockstep
4224// with the three in-crate wire-up sites.
4225macro_rules! supervisor_caixa_only_ctors {
4226    ($($ctor:ident => $variant:ident),* $(,)?) => {
4227        impl SupervisorError {
4228            $(
4229                #[doc = concat!(
4230                    "Construct a [`SupervisorError::",
4231                    stringify!($variant),
4232                    "`] naming the offending `:children :caixa` (or ",
4233                    "supervisor `:nome`, on the self-supervision arm). ",
4234                    "Folds the uniform `Self::",
4235                    stringify!($variant),
4236                    " { caixa: caixa.to_string() }` one-field ",
4237                    "struct-literal onto one substrate primitive so ",
4238                    "every [`SupervisorSpec::validate_children`] / ",
4239                    "[`validate_no_self_supervision`] wire-up on this ",
4240                    "variant reads through one dispatch rather than the ",
4241                    "pre-lift open-coded struct-literal block."
4242                )]
4243                #[must_use]
4244                pub fn $ctor(caixa: &str) -> Self {
4245                    Self::$variant { caixa: caixa.to_string() }
4246                }
4247            )*
4248        }
4249    };
4250}
4251
4252supervisor_caixa_only_ctors! {
4253    empty_child_version => EmptyChildVersion,
4254    duplicate_child_caixa => DuplicateChildCaixa,
4255    child_supervises_self => ChildSupervisesSelf,
4256}
4257
4258// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4259// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4260// one substrate primitive per typed variant — the M2 supervisor-side siblings
4261// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4262// already lifted through the sibling
4263// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4264// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4265// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4266// String }` two-slot shape the peer seven-variant
4267// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4268// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4269// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4270// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4271// variant carries the `{ caixa: String, versao: String, reason: String }`
4272// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4273// carries on the same `:versao` value-shape.
4274//
4275// Each of the two wire-up sites opened the same closure-shaped
4276// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4277// [versao: child.versao_requirement().to_string(),] reason }` block inside
4278// the paired [`crate::render::require_valid_dns_1123_label`] and
4279// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4280// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4281// as a bug, on the same altitude the peer `AplicacaoError` /
4282// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4283// families already closed on their sibling envelopes.
4284//
4285// The two `#[must_use]` inherent constructors below fold each wire-up onto
4286// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4287// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4288// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4289// The uniform per-field `.to_string()` / `.into()` construction is spelled
4290// once — inside each ctor body — rather than at every wire-up site. The
4291// `reason: impl Into<String>` bound accepts both `&str` literals and
4292// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4293// diagnostic shape at the lift, matching the peer
4294// [`aplicacao_field_reason_ctors!`] and
4295// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4296// sibling envelopes.
4297//
4298// Every future consumer that wants to construct one of these two variants
4299// outside `SupervisorSpec::validate_children` — a deferred
4300// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4301// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4302// `feira validate --supervisor` per-caixa admission verb, a per-child
4303// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4304// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4305// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4306// cluster-local snapshot — now reaches each variant through one call rather
4307// than re-inlining the per-shape struct-literal block in lockstep with the
4308// two in-crate wire-up sites.
4309impl SupervisorError {
4310    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4311    /// offending `:children :caixa` value under the given `reason`. Folds
4312    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4313    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4314    /// primitive so every wire-up on this variant reads through one
4315    /// dispatch, matching the peer
4316    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4317    /// sibling `AplicacaoError { caixa: String, reason: String }`
4318    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4319    /// outputs through the `impl Into<String>` bound.
4320    #[must_use]
4321    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4322        Self::ChildCaixaInvalid {
4323            caixa: caixa.to_string(),
4324            reason: reason.into(),
4325        }
4326    }
4327
4328    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4329    /// offending `:children :caixa` and its `:versao` requirement under
4330    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4331    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4332    /// reason.into() }` three-slot struct-literal onto one substrate
4333    /// primitive so every wire-up on this variant reads through one
4334    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4335    /// { caixa, versao, reason }` three-slot axis on the peer
4336    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4337    /// and `format!(…)` outputs through the `impl Into<String>` bound.
4338    #[must_use]
4339    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4340        Self::ChildVersaoInvalid {
4341            caixa: caixa.to_string(),
4342            versao: versao.to_string(),
4343            reason: reason.into(),
4344        }
4345    }
4346}
4347
4348// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4349// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4350// three bracket-arms — one struct-literal at the `:children`-empty
4351// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4352// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4353// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4354// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4355// [`crate::render::require_positive_canonical_bounded_duration`]
4356// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4357// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4358// primitive per typed variant, matching the sibling
4359// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4360// variants on the same `{ <field>: Duration | u32 }` shape) at that
4361// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4362// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4363// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4364// wire-up site through one dispatch per typed variant without a runtime-
4365// work delta.
4366//
4367// Each of the four wire-up sites opened the identical
4368// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4369// exact "same block re-inlined at every consumer" shape the PRIME
4370// DIRECTIVE names as a bug, on the same altitude the peer
4371// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4372// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4373// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4374// the fold routes each wire-up site through one dispatch per typed
4375// variant.
4376//
4377// The macro below generates one static constructor per variant of shape
4378// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4379// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4380// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4381// fixture — as a direct call at the [`SupervisorSpec::validate`]
4382// `:children`-empty refusal, or as a bare function pointer in the
4383// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4384// [`crate::render::require_positive_bounded_u32`] /
4385// [`crate::render::require_positive_canonical_bounded_duration`] gate
4386// carries — rather than the pre-lift open-coded one-line closure over
4387// the same one-field struct-literal. `const fn` preserves the `Copy`-
4388// pass-through's zero-runtime-work property verbatim. Every constructor
4389// is `#[must_use]` so a caller who mistakenly discards the constructed
4390// error trips a compile warning at the wire-up site.
4391//
4392// Every future consumer that wants to construct one of these four
4393// variants outside `SupervisorSpec::validate` — a deferred
4394// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4395// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4396// `:restart-window` slot against the cap + canonical-form cascade, a
4397// future `feira validate --supervisor` per-caixa admission verb re-
4398// running the shape gates on demand, a per-Supervisor overlay resolver
4399// rejecting an author-supplied slot against a cluster-local snapshot —
4400// now reaches each variant through one call rather than re-inlining the
4401// per-shape struct-literal block in lockstep with the four in-crate
4402// wire-up sites.
4403macro_rules! supervisor_scalar_ctors {
4404    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4405        impl SupervisorError {
4406            $(
4407                #[doc = concat!(
4408                    "Construct a [`SupervisorError::",
4409                    stringify!($variant),
4410                    "`] naming the offending per-`:supervisor` `",
4411                    stringify!($field),
4412                    "` scalar. Folds the uniform `Self::",
4413                    stringify!($variant),
4414                    " { ",
4415                    stringify!($field),
4416                    " }` one-field `Copy`-pass-through struct-literal onto ",
4417                    "one substrate primitive so every per-axis wire-up on ",
4418                    "this variant reads through one dispatch — as a direct ",
4419                    "call (`SupervisorError::",
4420                    stringify!($ctor),
4421                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4422                    "the same `Copy`-`",
4423                    stringify!($ty),
4424                    "` fixture) or as a bare function pointer in the ",
4425                    "`impl FnOnce(",
4426                    stringify!($ty),
4427                    ") -> SupervisorError` bracket-closure slot every ",
4428                    "`crate::render::require_positive_bounded_*` / ",
4429                    "`crate::render::require_positive_canonical_bounded_*` ",
4430                    "gate carries — rather than the pre-lift open-coded ",
4431                    "one-line closure over the same one-field struct-",
4432                    "literal. `const fn` preserves the `Copy`-pass-through's ",
4433                    "zero-runtime-work property verbatim."
4434                )]
4435                #[must_use]
4436                pub const fn $ctor($field: $ty) -> Self {
4437                    Self::$variant { $field }
4438                }
4439            )*
4440        }
4441    };
4442}
4443
4444supervisor_scalar_ctors! {
4445    no_children => NoChildren { estrategia: RestartStrategy },
4446    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4447    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4448    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4449}
4450
4451/// Shared duration string codec for the typed slots that take a
4452/// duration (`restart_window`, `MeshPolicy::timeout`,
4453/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4454/// reuse it without duplicating the parser.
4455pub mod duration_codec {
4456    use super::Duration;
4457    use serde::{Deserializer, Serializer};
4458
4459    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4460        // Route through the canonical [`crate::render::serialize_option_via_str`]
4461        // — the substrate-side single-owner primitive for the forward
4462        // arm of the typed-magnitude codec family. See its docstring
4463        // for the full sibling roster.
4464        crate::render::serialize_option_via_str(v, s, render)
4465    }
4466
4467    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4468        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4469        // — the substrate-side single-owner primitive for the reverse
4470        // arm of the typed-magnitude codec family. See its docstring
4471        // for the full sibling roster.
4472        crate::render::deserialize_option_via_str(d, parse)
4473    }
4474
4475    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4476        // Paired whitespace-rejection arm — same canonical-form
4477        // render-determinism discipline as the peer
4478        // `limits::parse_byte_size` / `limits::parse_duration` /
4479        // `limits::parse_millicores` /
4480        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4481        // byte-scan closes the WhatWG-conformant whitespace bytes
4482        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4483        // `char::is_whitespace` scan closes the strictly-complementary
4484        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4485        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4486        // codepoints) that `str::trim` at parse entry silently strips.
4487        // Either drift class would round-trip through `render` to a
4488        // *different* canonical form on next emit — breaking the
4489        // THEORY.md Part V render-determinism contract on three typed-
4490        // duration slots at once (`:supervisor :restart-window`,
4491        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4492        // via the shared codec.
4493        //
4494        // Routed through the lifted [`crate::render::reject_whitespace`]
4495        // primitive — the substrate-side single-owner paired-arm gate
4496        // every typed-magnitude codec in caixa-core shares.
4497        crate::render::reject_whitespace::<String, _, _>(
4498            s,
4499            |b| {
4500                format!(
4501                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4502                 authoring form for the typed duration slots routed through this shared codec \
4503                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4504                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4505                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4506                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4507                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4508                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4509                 Part V render-determinism contract every typed slot carries. Strip every \
4510                 whitespace byte (write `\"30s\"` verbatim)"
4511                )
4512            },
4513            |ch| {
4514                format!(
4515                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4516                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4517                 duration slots routed through this shared codec (`:supervisor \
4518                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4519                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4520                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4521                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4522                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4523                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4524                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4525                 strips it at parse entry, and the value round-trips through `render` to \
4526                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4527                 the THEORY.md Part V render-determinism contract every typed slot \
4528                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4529                 verbatim with only ASCII bytes)",
4530                    cp = ch as u32
4531                )
4532            },
4533        )?;
4534        let s = s.trim();
4535        // Routed through the lifted
4536        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4537        // the single-owner split every ASCII-alphabetic-unit typed-
4538        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4539        // `limits::parse_duration` / this shared duration codec) shares.
4540        // See its docstring for the full sibling roster on the same
4541        // primitive altitude.
4542        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4543        let num_trim = num_part.trim();
4544        // The canonical authoring form for every typed slot routed
4545        // through this shared codec — `:supervisor :restart-window`,
4546        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4547        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4548        // non-negative integer with no decimal point and no leading
4549        // sign, so the parser's accepted set must match for
4550        // serialize/deserialize to round-trip without canonical-form
4551        // drift. Until this gate landed the parser accepted any
4552        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4553        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4554        // tripped the value to a *different* canonical string on the
4555        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4556        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4557        // — breaking the THEORY.md Part V render-determinism contract
4558        // on three typed slots at once. Same canonical-form discipline
4559        // `crate::limits::parse_duration` (818dd38, the immediate
4560        // predecessor on the peer `:limits :wall-clock` codec) applies;
4561        // this gate lifts the discipline onto the shared codec that
4562        // backs the remaining three typed-duration slots in caixa-core.
4563        //
4564        // Strict canonical form: every byte of the magnitude is an
4565        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4566        // inputs the gate distinguishes "non-canonical-but-numeric"
4567        // (parses as f64 or i64 — surfaced with a self-locating
4568        // diagnostic naming the canonical authoring form, the
4569        // round-trip drift each rejected shape would produce on first
4570        // serialize, and the canonical-form remediation) from
4571        // "garbage" (parses as neither — surfaced with the existing
4572        // narrower "bad duration magnitude" wording so its diagnostic
4573        // shape remains stable for the parser-shape footgun case).
4574        // The pre-existing `num < 0.0` arm is now unreachable — the
4575        // digit-only gate strictly precedes magnitude parsing, and a
4576        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4577        // non-canonical-but-numeric branch with the `-30` named
4578        // verbatim in the diagnostic rather than the prior
4579        // value-laundered "negative duration in \"-30s\"" wording.
4580        //
4581        // Routed through the lifted
4582        // [`crate::render::is_digit_only_magnitude`] predicate — the
4583        // same source of truth the four peer typed-magnitude codec
4584        // sites share.
4585        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4586        if !digit_only {
4587            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4588            if numeric {
4589                return Err(format!(
4590                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4591                     canonical authoring form for the typed duration slots routed through \
4592                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4593                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4594                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4595                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4596                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4597                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4598                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4599                     THEORY.md Part V render-determinism contract every typed slot carries. \
4600                     Pick an integer magnitude in the unit that divides cleanly (write \
4601                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4602                ));
4603            }
4604            return Err(format!("bad duration magnitude in {s:?}"));
4605        }
4606        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4607        // zero arm (4f46830) on the same canonical-form render-
4608        // determinism axis. The digit-only gate accepts `"030s"`,
4609        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4610        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4611        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4612        // *different* canonical string on the next emit, breaking the
4613        // THEORY.md Part V render-determinism contract the same way
4614        // `"+30s"` did before the leading-`+` arm landed. The single-
4615        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4616        // losslessly through `render` (`render(Duration::ZERO)` emits
4617        // `"0s"`) — the downstream semantic-zero gates (e.g.
4618        // `SupervisorError::ZeroRestartWindow` on
4619        // `:supervisor :restart-window`,
4620        // `AplicacaoError::PolicyTimeoutZero` /
4621        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4622        // duration slots) refuse zero-magnitude authoring at the typed-
4623        // validate layer above, so the single-byte `"0"` stays in the
4624        // accepted set at this codec layer and the diagnostic
4625        // partitioning between canonical-form drift (this arm) and
4626        // semantic-zero (the downstream gates) remains stable.
4627        // Peer with the future leading-zero arms on the two remaining
4628        // typed-magnitude codecs the trajectory acknowledges:
4629        // `limits::parse_duration` backing `:limits :wall-clock`,
4630        // `limits::parse_byte_size` backing `:limits :memory` — each
4631        // carries the same canonical-form-drift class today; this
4632        // gate lands the discipline on the shared duration codec
4633        // first because the `rate_limit_codec` predecessor on the
4634        // same canonical-form-drift axis is the closest peer on the
4635        // trajectory.
4636        //
4637        // Routed through the lifted
4638        // [`crate::render::is_leading_zero_padded_magnitude`]
4639        // predicate — the same source of truth the four peer
4640        // typed-magnitude codec sites share.
4641        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4642            return Err(format!(
4643                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4644                 canonical authoring form for the typed duration slots routed through \
4645                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4646                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4647                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4648                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4649                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4650                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4651                 serialize — breaking the THEORY.md Part V render-determinism contract \
4652                 every typed slot carries. Strip the leading zeros (write \
4653                 `\"30s\"` instead of `\"030s\"`)"
4654            ));
4655        }
4656        // The digit-only gate guarantees every byte is `[0-9]`, and
4657        // the leading-zero arm above guarantees the magnitude is
4658        // either the single byte `"0"` or starts with `[1-9]`, so
4659        // the only way `u64::from_str` can fail here is overflow (the
4660        // magnitude exceeds `u64::MAX`). Surface that with an
4661        // overflow-shaped wording so the diagnostic names the offending
4662        // magnitude verbatim rather than collapsing onto the
4663        // non-canonical arm. The codec now operates on `u64` end-to-end
4664        // — every accepted magnitude is integer-exact; no f64 mantissa
4665        // drift between author-supplied magnitude and the consumer's
4666        // `Duration` value. Same shape `crate::limits::parse_duration`
4667        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4668        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4669            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4670        })?;
4671        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4672        // unit-arm dispatch through the canonical
4673        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4674        // primitive — the substrate-side single-owner unit-dispatch
4675        // table every typed-duration codec in caixa-core routes
4676        // through (peer: `crate::limits::parse_duration` backing
4677        // `:limits :wall-clock`). Every unit conversion is integer-
4678        // exact for an integer magnitude; overflow surfaces via the
4679        // typed `DurationUnitError::Overflow { multiplier }`
4680        // discriminant so this arm reconstructs the pre-lift
4681        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4682        // wording verbatim from `num` / `unit_trim` / the returned
4683        // `multiplier`, and the unknown-unit arm reconstructs the
4684        // pre-lift `"unknown duration unit \"<other>\""` wording from
4685        // the caller-scoped `unit_trim`. Load-bearing pinned by
4686        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4687        let unit_trim = unit.trim();
4688        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4689            |e| match e {
4690                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4691                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4692                ),
4693                crate::render::DurationUnitError::UnknownUnit => {
4694                    format!("unknown duration unit {unit_trim:?}")
4695                }
4696            },
4697        )?;
4698        Ok(dur)
4699    }
4700
4701    /// Render a [`Duration`] in the canonical pleme-io duration string
4702    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4703    /// caixa typed-duration slot serializes to and the same form K8s
4704    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4705    /// EnvoyConfig per-route timeouts both expect (an integer
4706    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4707    /// `+`). Lifted to `pub` so caixa-side renderers
4708    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4709    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4710    /// emitter, the future caixa-otel collector pipeline emitter) can
4711    /// consume the same canonical formatter without re-inlining the
4712    /// magnitude/unit decision tree (and inheriting the same drift
4713    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4714    /// downstream apply-time parsing in non-obvious ways).
4715    pub fn render(d: Duration) -> String {
4716        let total_ms = d.as_millis();
4717        if total_ms == 0 {
4718            return "0s".into();
4719        }
4720        if total_ms.is_multiple_of(3600 * 1000) {
4721            return format!("{}h", total_ms / (3600 * 1000));
4722        }
4723        if total_ms.is_multiple_of(60 * 1000) {
4724            return format!("{}m", total_ms / (60 * 1000));
4725        }
4726        if total_ms.is_multiple_of(1000) {
4727            return format!("{}s", total_ms / 1000);
4728        }
4729        format!("{total_ms}ms")
4730    }
4731
4732    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4733    ///
4734    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4735    /// largest divisor unit, so any sub-millisecond residue
4736    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4737    /// §V.2.7 render-determinism contract:
4738    ///
4739    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4740    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4741    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4742    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4743    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4744    ///     on every typed-`Duration` slot then rejects on re-validate.
4745    ///
4746    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4747    /// the codec's round-trippable accepted set lives in exactly one place —
4748    /// every typed-`Duration` slot that routes through this shared codec
4749    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4750    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4751    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4752    /// every typed-`Duration` slot whose own codec shares the same
4753    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4754    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4755    /// pair) calls this predicate from its `validate()` to bracket the
4756    /// accepted set against the codec's accepted set, structurally. Drift
4757    /// between the codec's granularity and any typed slot's accepted set is
4758    /// then a single-source-of-truth edit at this predicate rather than a
4759    /// silent round-trip break the next consumer discovers at apply time.
4760    ///
4761    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4762    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4763    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4764    /// family — same "typed-slot's valid set matches its codec's accepted
4765    /// set, structurally" discipline carried at the codec layer.
4766    #[must_use]
4767    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4768        d.subsec_nanos().is_multiple_of(1_000_000)
4769    }
4770}
4771
4772/// Required-Duration variant for fields that aren't Option<Duration>.
4773pub mod duration_codec_required {
4774    use super::Duration;
4775    use serde::{Deserialize, Deserializer, Serializer};
4776
4777    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4778        s.serialize_str(&super::duration_codec::render(*v))
4779    }
4780
4781    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4782        let s = String::deserialize(d)?;
4783        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4784    }
4785}
4786
4787#[cfg(test)]
4788mod tests {
4789    use super::*;
4790
4791    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4792        ChildSpec {
4793            caixa: name.into(),
4794            versao: ver.into(),
4795            restart,
4796        }
4797    }
4798
4799    #[test]
4800    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4801        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4802        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4803        // posture. Each accessor projects the per-`:children :caixa`
4804        // / per-`:children :versao` [`String`] storage through the
4805        // `pub const fn` [`String::as_str`] (const-stable since Rust
4806        // 1.87, well within the workspace MSRV) — any future
4807        // accidental downgrade to non-`const` fails the corresponding
4808        // `<name>_via_const_fn` wrapper at caixa-core build time with
4809        // E0015 (`cannot call non-const method`), strictly stronger
4810        // than a runtime `assert!`. Sibling of the peer
4811        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4812        // family pins on the sibling `const`-eval-surface passes
4813        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4814        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4815        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4816        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4817        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4818        // [`crate::aplicacao::Entrada::destination`] at the M3
4819        // ingress axis,
4820        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4821        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4822        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4823        // axis, and the per-`:contratos`
4824        // [`crate::aplicacao::WitContract::source`] /
4825        // [`crate::aplicacao::WitContract::destination`] /
4826        // [`crate::aplicacao::WitContract::world_ref`] trio the
4827        // sibling pin at 279823b already anchors).
4828        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4829            c.nome()
4830        }
4831        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4832            c.versao_requirement()
4833        }
4834        for (caixa, versao) in [
4835            ("worker-a", "^0.1"),
4836            ("worker-b", "~0.2.3"),
4837            ("collector", "*"),
4838        ] {
4839            let c = child(caixa, versao, RestartPolicy::Permanent);
4840            assert_eq!(nome_via_const_fn(&c), c.nome());
4841            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4842            assert_eq!(c.nome(), caixa);
4843            assert_eq!(c.versao_requirement(), versao);
4844        }
4845    }
4846
4847    #[test]
4848    fn supervisor_children_slice_return_accessor_is_const_fn() {
4849        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4850        // `const`-eval-surface posture. The accessor destructures the
4851        // per-`:children` `Vec<ChildSpec>` storage through the
4852        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4853        // 1.66, well within the workspace MSRV) — any future
4854        // accidental downgrade to non-`const` fails
4855        // `children_via_const_fn` at caixa-core build time with E0015
4856        // (`cannot call non-const method`), strictly stronger than a
4857        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4858        // `Vec → &[T]` slice-return accessor family pin
4859        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4860        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4861        // per-`:membros` / per-`:contratos` slice-return axes, and of
4862        // the peer M2 upgrade-appup axis pin
4863        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4864        // on the per-`:upgrade-from :instructions` slice-return axis.
4865        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4866            s.children()
4867        }
4868        // Sweep both the empty-children (leaf-supervisor with no
4869        // static children — the `SimpleOneForOne` dynamic-child
4870        // arm's canonical shape) and the populated-children
4871        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4872        // arm's canonical shape) axes so the accessor carries a
4873        // const-dispatch pin on both arms.
4874        let s_empty = SupervisorSpec {
4875            estrategia: RestartStrategy::SimpleOneForOne,
4876            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4877            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4878            children: vec![],
4879        };
4880        assert!(children_via_const_fn(&s_empty).is_empty());
4881        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4882        let s_full = SupervisorSpec {
4883            estrategia: RestartStrategy::OneForOne,
4884            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4885            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4886            children: vec![
4887                child("worker-a", "^0.1", RestartPolicy::Permanent),
4888                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4889                child("collector", "*", RestartPolicy::Temporary),
4890            ],
4891        };
4892        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4893        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4894    }
4895
4896    #[test]
4897    fn default_has_one_for_one_and_5_restarts_in_60s() {
4898        let s = SupervisorSpec::default();
4899        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4900        assert_eq!(s.max_restarts, 5);
4901        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4902        assert!(s.children.is_empty());
4903    }
4904
4905    #[test]
4906    fn validate_one_for_one_requires_children() {
4907        let mut s = SupervisorSpec::default();
4908        s.children = vec![];
4909        assert!(matches!(
4910            s.validate().unwrap_err(),
4911            SupervisorError::NoChildren { .. }
4912        ));
4913        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4914        s.validate().unwrap();
4915    }
4916
4917    #[test]
4918    fn validate_simple_one_for_one_forbids_static_children() {
4919        let mut s = SupervisorSpec {
4920            estrategia: RestartStrategy::SimpleOneForOne,
4921            ..SupervisorSpec::default()
4922        };
4923        s.children
4924            .push(child("w", "^0.1", RestartPolicy::Permanent));
4925        assert_eq!(
4926            s.validate().unwrap_err(),
4927            SupervisorError::SimpleOneForOneWithStaticChildren
4928        );
4929        s.children.clear();
4930        s.validate().unwrap();
4931    }
4932
4933    #[test]
4934    fn validate_rejects_zero_max_restarts() {
4935        let s = SupervisorSpec {
4936            max_restarts: 0,
4937            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4938            ..SupervisorSpec::default()
4939        };
4940        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4941    }
4942
4943    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4944    //
4945    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4946    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4947    // `:supervisor :max-restarts` axis — both fields are "trip the
4948    // next-higher protection layer after N events in a rolling window"
4949    // counters with identical degenerate-at-the-high-end shape, so the
4950    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4951    // exactly as it lies in `1..=1000` on the breaker side.
4952
4953    #[test]
4954    fn validate_rejects_max_restarts_above_cap() {
4955        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4956        // 1` is structurally one past the cap and silently passed
4957        // validate on every pre-gate codebase because the typed slot's
4958        // only check was the zero-floor arm. The no-op-supervisor vector
4959        // only surfaced at the runtime substrate (Erlang/OTP
4960        // MaxIntensity/Period ratio, the future wasm-operator's
4961        // per-supervisor restart-intensity counter) far from the source
4962        // caixa.lisp with no field naming the offending supervisor.
4963        let s = SupervisorSpec {
4964            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4965            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4966            ..SupervisorSpec::default()
4967        };
4968        assert_eq!(
4969            s.validate().unwrap_err(),
4970            SupervisorError::MaxRestartsExceedsCap {
4971                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4972            }
4973        );
4974    }
4975
4976    #[test]
4977    fn validate_rejects_max_restarts_far_above_cap() {
4978        // The `u32::MAX` worst case — the four-billion-restart
4979        // threshold a typo (`:max-restarts 4294967295`) or a
4980        // struct-literal copy-paste lands in the slot. Pin the cap
4981        // arm's coverage explicitly across the full `u32` overflow so
4982        // a future relaxation that drops the upper bound surfaces
4983        // here. Same shape every other typed-cap arm on this surface
4984        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4985        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4986        let s = SupervisorSpec {
4987            max_restarts: u32::MAX,
4988            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4989            ..SupervisorSpec::default()
4990        };
4991        assert_eq!(
4992            s.validate().unwrap_err(),
4993            SupervisorError::MaxRestartsExceedsCap {
4994                max_restarts: u32::MAX,
4995            }
4996        );
4997    }
4998
4999    #[test]
5000    fn validate_accepts_max_restarts_at_cap() {
5001        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5002        // must validate. The cap is inclusive on the top edge,
5003        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5004        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5005        // discipline on the sibling capped axes. Pin the boundary
5006        // explicitly so a future off-by-one tightening
5007        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5008        // here as a test failure rather than a silent contract
5009        // narrowing.
5010        let s = SupervisorSpec {
5011            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5012            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5013            ..SupervisorSpec::default()
5014        };
5015        s.validate()
5016            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5017    }
5018
5019    #[test]
5020    fn validate_accepts_max_restarts_typical_values() {
5021        // The documented production-playbook band positive-control
5022        // sweep — every value Erlang/OTP / Elixir / Riak Core /
5023        // RabbitMQ recommend (1..=100) must pass, plus a sweep
5024        // through the hyperscale band (200, 500, 1000) the cap
5025        // accepts. Pin the inclusive validated set explicitly so a
5026        // future tightening of the ceiling surfaces here.
5027        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5028            let s = SupervisorSpec {
5029                max_restarts: n,
5030                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5031                ..SupervisorSpec::default()
5032            };
5033            s.validate()
5034                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5035        }
5036    }
5037
5038    #[test]
5039    fn zero_max_restarts_takes_precedence_over_cap() {
5040        // The cross-arm ordering pin: `0` is structurally outside
5041        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5042        // (cap), but the zero-floor diagnostic is the more
5043        // self-locating one (it directly names the counter-axis
5044        // remediation), so the validate gate must fire on zero first.
5045        // Same shape every other zero-then-shape ordering on this
5046        // surface uses (PolicyRetriesZero then
5047        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5048        // PolicyBreakerMaxFailuresExceedsCap).
5049        let s = SupervisorSpec {
5050            max_restarts: 0,
5051            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5052            ..SupervisorSpec::default()
5053        };
5054        assert_eq!(
5055            s.validate().unwrap_err(),
5056            SupervisorError::ZeroMaxRestarts,
5057            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5058        );
5059    }
5060
5061    #[test]
5062    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5063        // The cross-arm ordering pin between the cap and the sibling
5064        // `:restart-window` gates (zero-window, canonical-window). A
5065        // supervisor carrying both an over-cap `max_restarts` AND a
5066        // structurally invalid window (zero, sub-ms) must surface the
5067        // cap diagnostic first — the cap arm is wired immediately
5068        // after the zero-restart arm and strictly before the window
5069        // arms, so the offending value the diagnostic names matches
5070        // the order the author would discover the gates by reading
5071        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5072        // order so a future refactor that reorders the arms surfaces
5073        // here as a test failure rather than a silent diagnostic
5074        // regression. Peer of
5075        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5076        // on the sibling `:politicas :circuit-breaker` slot.
5077        let s = SupervisorSpec {
5078            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5079            restart_window: Some(Duration::ZERO),
5080            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5081            ..SupervisorSpec::default()
5082        };
5083        assert_eq!(
5084            s.validate().unwrap_err(),
5085            SupervisorError::MaxRestartsExceedsCap {
5086                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5087            },
5088            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5089        );
5090    }
5091
5092    #[test]
5093    fn max_restarts_cap_diagnostic_carries_offending_value() {
5094        // The diagnostic-shape pin: the offending `u32` is carried
5095        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5096        // variant so the surfaced error message names the value the
5097        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5098        // supervisor-policy ceiling …"`), not just the cap. Same
5099        // self-locating diagnostic shape every other typed-cap arm on
5100        // this surface carries
5101        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5102        // the offending failure count verbatim,
5103        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5104        // retries count verbatim).
5105        let s = SupervisorSpec {
5106            max_restarts: 50_000,
5107            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5108            ..SupervisorSpec::default()
5109        };
5110        let err = s.validate().unwrap_err();
5111        assert!(
5112            matches!(
5113                err,
5114                SupervisorError::MaxRestartsExceedsCap {
5115                    max_restarts: 50_000
5116                }
5117            ),
5118            "got {err:?}"
5119        );
5120        let msg = err.to_string();
5121        assert!(
5122            msg.contains("50000"),
5123            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5124        );
5125    }
5126
5127    #[test]
5128    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5129        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5130        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5131        // half of Learn You Some Erlang's worker-supervisor default,
5132        // sibling of the `60s` `Period` half that the paired
5133        // [`Default for SupervisorSpec`] impl already pins on the
5134        // sibling `restart_window` axis. Pinning the literal here
5135        // surfaces a future rebrand (a tightening to Elixir's `3`,
5136        // a widening to a per-cluster overlay the operator pins
5137        // through a future `:max-restarts-overrides` slot) as a
5138        // deliberate test edit, not a silent contract migration.
5139        // Peer of the sibling
5140        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5141        // upper-bracket pin on the same axis.
5142        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5143    }
5144
5145    #[test]
5146    fn default_max_restarts_helper_routes_through_lifted_default() {
5147        // Composition pin: the private `default_max_restarts()`
5148        // serde-`#[serde(default = "…")]` helper on
5149        // [`SupervisorSpec::max_restarts`] must route through the
5150        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5151        // typed `pub const` rather than a raw `5` literal. Prior to
5152        // the lift the helper carried an inline `5` with no compile-
5153        // time link back to the shared default, so the wire-format
5154        // author-omitted arm and the caixa-core
5155        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5156        // arm could silently split on any future default rebrand.
5157        // Byte-parity against the lifted constant closes the split.
5158        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5159    }
5160
5161    #[test]
5162    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5163        // Composition pin: the [`Default for SupervisorSpec`] impl's
5164        // struct-literal `max_restarts` field must route through the
5165        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5166        // typed `pub const` (via the private helper this test's
5167        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5168        // already pins onto the constant). Structurally: every
5169        // `SupervisorSpec::default()` call must yield a
5170        // `max_restarts` field byte-equal to the lifted constant
5171        // (the two paired defaults — the serde-side wire-format arm
5172        // and the struct-literal default arm — cannot silently split
5173        // on any future default rebrand). Peer of the sibling
5174        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5175        // — this pin closes the byte-parity arm on the two paired
5176        // altitude entry points onto the shared substrate constant.
5177        assert_eq!(
5178            SupervisorSpec::default().max_restarts(),
5179            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5180        );
5181    }
5182
5183    #[test]
5184    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5185        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5186        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5187        // Learn You Some Erlang's worker-supervisor default, paired
5188        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5189        // `MaxIntensity` half this constant is the sliding-window
5190        // denominator of on the same `MaxIntensity / Period`
5191        // restart-intensity ratio. Pinning the literal here surfaces a
5192        // future coherent rebrand of the paired default (Elixir's
5193        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5194        // the operator pins through a future
5195        // `:restart-window-overrides` slot) as a deliberate test edit,
5196        // not a silent contract migration. Peer of the sibling
5197        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5198        // paired-half pin on the same OTP-canonical default and the
5199        // [`supervisor_restart_window_cap_pins_canonical_value`]
5200        // upper-bracket pin on the same axis.
5201        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5202    }
5203
5204    #[test]
5205    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5206        // Composition pin: the [`Default for SupervisorSpec`] impl's
5207        // struct-literal `restart_window` field must route through the
5208        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5209        // typed `pub const` rather than a raw
5210        // `Duration::from_secs(60)` literal. Prior to this lift the
5211        // paired `{intensity, 5, 60}` OTP-canonical default was split
5212        // across two altitudes with no compile-time link between the
5213        // halves — the `MaxIntensity` half rode through the lifted
5214        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5215        // `Period` half rode as an open-coded literal at the
5216        // composition site, so a future coherent rebrand of the paired
5217        // canonical would have had to migrate one half through the
5218        // constant and the other through a raw literal in lockstep.
5219        // Byte-parity against the lifted constant on the `Period` half
5220        // closes the split — the paired OTP-canonical default now
5221        // migrates as one unit on any future axis change. Peer of the
5222        // sibling
5223        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5224        // byte-parity pin on the paired `MaxIntensity` half.
5225        assert_eq!(
5226            SupervisorSpec::default().restart_window(),
5227            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5228        );
5229    }
5230
5231    #[test]
5232    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5233        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5234        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5235        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5236        // canonical default, paired with the sibling
5237        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5238        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5239        // this constant is the strategy discriminator of on the same
5240        // OTP-canonical worker-supervisor default. Pinning the arm here
5241        // surfaces a future coherent rebrand of the paired triple (Elixir's
5242        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5243        // intensity/period axes leaving this strategy arm untouched, an OTP
5244        // `rest_for_one` widening once the substrate discovers startup-
5245        // order-coupled child cohorts as the more common worker-supervisor
5246        // shape, a per-cluster overlay the operator pins through a future
5247        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5248        // supervision-canary roadmap acknowledges) as a deliberate test
5249        // edit, not a silent contract migration. Peer of the sibling
5250        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5251        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5252        // paired-half pins on the same OTP-canonical default.
5253        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5254    }
5255
5256    #[test]
5257    fn restart_strategy_default_routes_through_lifted_default() {
5258        // Composition pin: the [`Default for RestartStrategy`] impl's
5259        // return arm must route through the substrate-canonical
5260        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5261        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5262        // an inline `Self::OneForOne` with no compile-time link back to
5263        // the shared OTP-canonical `one_for_one` strategy the paired
5264        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5265        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5266        // `.unwrap_or_default()` (now
5267        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5268        // so a future rebrand of the OTP-canonical strategy default (an
5269        // OTP `rest_for_one` widening once the substrate discovers
5270        // startup-order-coupled child cohorts as the more common worker-
5271        // supervisor shape, a per-cluster overlay the operator pins
5272        // through a future `:estrategia-overrides` slot) would have had to
5273        // be threaded through the `Default` impl and the two peer routes
5274        // in lockstep or the three consumers would silently split. Byte-
5275        // parity against the lifted constant closes the split. Peer of
5276        // the sibling
5277        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5278        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5279        // composition pins on the paired `MaxIntensity` + `Period` halves.
5280        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5281    }
5282
5283    #[test]
5284    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5285        // Composition pin: the [`Default for SupervisorSpec`] impl's
5286        // struct-literal `estrategia` field must route through the
5287        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5288        // `pub const` (either directly, or via the
5289        // [`RestartStrategy::default`] impl that the sibling
5290        // `restart_strategy_default_routes_through_lifted_default` pin
5291        // already routes onto the constant). Structurally: every
5292        // `SupervisorSpec::default()` call must yield an `estrategia`
5293        // field byte-equal to the lifted constant (the three paired
5294        // defaults — the [`Default for RestartStrategy`] impl arm, the
5295        // struct-literal default arm here, and the
5296        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5297        // silently split on any future default rebrand). Peer of the
5298        // sibling
5299        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5300        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5301        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5302        // of the same `SupervisorSpec::default()` composed altitude.
5303        assert_eq!(
5304            SupervisorSpec::default().estrategia(),
5305            SUPERVISOR_ESTRATEGIA_DEFAULT,
5306        );
5307    }
5308
5309    #[test]
5310    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5311        // Composition pin: the [`Default for SupervisorSpec`] impl must
5312        // route through the substrate-canonical
5313        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5314        // rather than a re-hand-authored struct-literal cascade. Sharpens
5315        // the sibling per-arm
5316        // `supervisor_spec_default_*_routes_through_lifted_default` pins
5317        // from a per-field lift into a whole-struct one-source-of-truth
5318        // pin — the derived-until-now [`Default::default`] and the
5319        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5320        // construction, not by coincidence.
5321        //
5322        // A future extension of the OTP-canonical baseline (a fifth
5323        // `restart_intensity` field the Erlang/OTP `#supervisor` record
5324        // grows, a per-child-cohort split of the `restart_window` /
5325        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5326        // CR materializer's admission-time overlay pass) reaches both
5327        // paths through exactly one edit on
5328        // [`SupervisorSpec::otp_canonical`] — the derived path could
5329        // silently disagree with the constructor's shape on any new
5330        // field whose [`Default::default`] resolves to a different arm
5331        // than the OTP-canonical baseline the constructor names, while
5332        // this delegated impl reaches the constructor directly and
5333        // picks up every future extension by construction.
5334        //
5335        // Fourth peer on the M2 / M3 typed-slot-spec
5336        // [`Default`]-through-const-ctor fold family — sibling of the
5337        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5338        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5339        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5340        // (91641a4), and [`crate::BehaviorSpec`]
5341        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5342        // per-`Option`-only-typed-slot folds — extended here onto the
5343        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5344        // is not "everything `None`" but the Erlang/OTP-canonical
5345        // `{one_for_one, 5, 60}` worker-supervisor triple.
5346        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5347    }
5348
5349    #[test]
5350    fn supervisor_spec_otp_canonical_byte_equals_default() {
5351        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5352        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5353        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5354        // pin already asserts against the [`Default::default`] path.
5355        // Sharpens the pair-invariant into a per-constructor pin so a
5356        // future extension of [`SupervisorSpec`] with a fifth field
5357        // whose OTP-canonical shape is non-`Default::default`-equivalent
5358        // trips at caixa-core test time rather than at a downstream
5359        // consumer that composed [`SupervisorSpec::otp_canonical`] with
5360        // [`SupervisorSpec::validate`] as its "canonical baseline
5361        // seed".
5362        let canonical = SupervisorSpec::otp_canonical();
5363        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5364        assert_eq!(canonical.max_restarts, 5);
5365        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5366        assert!(canonical.children.is_empty());
5367    }
5368
5369    #[test]
5370    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5371        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5372        // remain callable from a `const`-bound position so downstream
5373        // `const`-context callers wanting a canonical OTP-baseline seed
5374        // can construct one at compile time without runtime dispatch on
5375        // the derived [`Default::default`]. Peer of the sibling
5376        // `pub const fn` [`crate::LimitsSpec::empty`] /
5377        // [`crate::aplicacao::MeshPolicy::empty`] /
5378        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5379        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5380        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5381        // (a non-`const` field-default helper, a non-`const`-stable
5382        // container type promotion), this evaluation fails at
5383        // build time on this file rather than at a downstream
5384        // `const`-context call site.
5385        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5386        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5387        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5388        assert_eq!(
5389            CANONICAL.restart_window,
5390            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5391        );
5392        assert!(CANONICAL.children.is_empty());
5393    }
5394
5395    #[test]
5396    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5397        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5398        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5399        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5400        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5401        // half of the same OTP-shape supervisor-tree default set whose
5402        // per-`:supervisor` halves the sibling
5403        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5404        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5405        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5406        // arm here surfaces a future rebrand of the per-child default (an
5407        // OTP-`transient` widening once the substrate discovers clean-
5408        // completion-aware children as the more common child shape, a
5409        // per-cluster overlay the operator pins through a future
5410        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5411        // supervision-canary roadmap acknowledges) as a deliberate test
5412        // edit, not a silent contract migration. Peer of the sibling
5413        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5414        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5415        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5416        // value pins on the per-`:supervisor` halves.
5417        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5418    }
5419
5420    #[test]
5421    fn restart_policy_default_routes_through_lifted_default() {
5422        // Composition pin: the [`Default for RestartPolicy`] impl's return
5423        // arm must route through the substrate-canonical
5424        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5425        // than a raw `Self::Permanent` arm. Prior to the lift the impl
5426        // carried an inline `Self::Permanent` with no compile-time link
5427        // back to the OTP-shape supervisor-tree default set whose three
5428        // per-`:supervisor` halves already rode through lifted constants
5429        // — so a future coherent rebrand of the set would have had to
5430        // migrate three halves through typed constants and this fourth
5431        // through a raw enum arm in lockstep or the supervisor-level and
5432        // child-level defaults would silently drift apart. Byte-parity
5433        // against the lifted constant closes the split. Peer of the
5434        // sibling
5435        // [`restart_strategy_default_routes_through_lifted_default`]
5436        // composition pin on the per-`:supervisor` `:estrategia` axis.
5437        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5438    }
5439
5440    #[test]
5441    fn child_spec_serde_default_restart_routes_through_lifted_default() {
5442        // Composition pin: the serde-side `#[serde(default)]` on
5443        // [`ChildSpec::restart`] — the wire-format author-omitted
5444        // `:children :restart` arm — must resolve onto the substrate-
5445        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5446        // (via the [`Default for RestartPolicy`] impl the sibling
5447        // `restart_policy_default_routes_through_lifted_default` pin
5448        // already routes onto the constant). Structurally: a `ChildSpec`
5449        // deserialized from a payload that omits the `restart` key must
5450        // yield a `restart` field byte-equal to the lifted constant, so
5451        // the wire-format author-omitted arm and the
5452        // [`RestartPolicy::default`] impl arm cannot silently split on any
5453        // future default rebrand. Peer of the sibling
5454        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5455        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5456        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5457        // byte-parity pins on the per-`:supervisor` halves of the same
5458        // author-omitted-slot resolution surface.
5459        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5460            .expect("ChildSpec must deserialize with the restart key omitted");
5461        assert_eq!(
5462            omitted.restart(),
5463            SUPERVISOR_CHILD_RESTART_DEFAULT,
5464            "an author-omitted :children :restart slot must degrade onto \
5465             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5466             {:?}, expected {:?})",
5467            omitted.restart(),
5468            SUPERVISOR_CHILD_RESTART_DEFAULT,
5469        );
5470    }
5471
5472    #[test]
5473    fn supervisor_max_restarts_cap_pins_canonical_value() {
5474        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5475        // 1000 — the same ceiling the peer
5476        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5477        // `:politicas :circuit-breaker :max-failures` axis (both are
5478        // "trip the next-higher protection layer after N events in a
5479        // rolling window" counters with identical
5480        // degenerate-at-the-high-end shape; uniform top edge so the
5481        // M4 CR materializers and the wasm-operator reconciler reach
5482        // for either field knowing the value is in `1..=1000`). Two
5483        // orders of magnitude above every documented Erlang/OTP /
5484        // Elixir / Riak Core / RabbitMQ production-playbook
5485        // recommendation band and below the clearly-pathological
5486        // "effectively no escalation" floor (10_000, 100_000,
5487        // u32::MAX). Pinning the literal value here surfaces a future
5488        // drift (a relaxation to 10_000, a tightening to 100) as a
5489        // deliberate test edit, not a silent contract narrowing.
5490        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5491    }
5492
5493    #[test]
5494    fn validate_rejects_empty_child_name() {
5495        let s = SupervisorSpec {
5496            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5497            ..SupervisorSpec::default()
5498        };
5499        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5500    }
5501
5502    #[test]
5503    fn validate_rejects_empty_child_version() {
5504        let s = SupervisorSpec {
5505            children: vec![child("w", "", RestartPolicy::Permanent)],
5506            ..SupervisorSpec::default()
5507        };
5508        assert!(matches!(
5509            s.validate().unwrap_err(),
5510            SupervisorError::EmptyChildVersion { .. }
5511        ));
5512    }
5513
5514    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5515
5516    #[test]
5517    fn validate_rejects_invalid_child_versao_requirement() {
5518        // The fail-before-pass-after pin: a non-empty but malformed
5519        // semver requirement (`"^bad-version"`) silently passed
5520        // `validate()` on every pre-gate codebase because the prior
5521        // shape only refused the empty string. The parse failure
5522        // surfaced far downstream at lacre-resolve time with a
5523        // `semver::Error` that didn't name which `:children` entry
5524        // carried the typo. The new gate moves the check to caixa-build
5525        // time at the source caixa.lisp — the third `:versao` typed
5526        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5527        // structural parity.
5528        let s = SupervisorSpec {
5529            children: vec![
5530                child("worker", "^0.1", RestartPolicy::Permanent),
5531                child("cache", "^bad-version", RestartPolicy::Transient),
5532            ],
5533            ..SupervisorSpec::default()
5534        };
5535        let err = s.validate().unwrap_err();
5536        assert!(
5537            matches!(
5538                err,
5539                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5540                    if caixa == "cache" && versao == "^bad-version"
5541            ),
5542            "got {err:?}"
5543        );
5544    }
5545
5546    #[test]
5547    fn validate_rejects_child_versao_with_double_caret_typo() {
5548        // `"^^0.1"` is the canonical doubled-caret typo — looks
5549        // Cargo-shaped on first glance but fails the parser because
5550        // semver doesn't accept stacked operators. Pin this
5551        // adjacent-shape footgun explicitly so a future relaxation that
5552        // accepts "looks-canonical-but-isn't" forms surfaces here.
5553        let s = SupervisorSpec {
5554            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5555            ..SupervisorSpec::default()
5556        };
5557        let err = s.validate().unwrap_err();
5558        assert!(
5559            matches!(
5560                err,
5561                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5562                    if caixa == "worker" && versao == "^^0.1"
5563            ),
5564            "got {err:?}"
5565        );
5566    }
5567
5568    #[test]
5569    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5570        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5571        // semver requirement slot" typo — an author copies the
5572        // publish-side git-tag string verbatim into `:versao`, but
5573        // Cargo's semver parser rejects the leading `v`. Same
5574        // adjacent-shape footgun pinned for `:membros :versao`
5575        // (9888b13).
5576        let s = SupervisorSpec {
5577            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5578            ..SupervisorSpec::default()
5579        };
5580        let err = s.validate().unwrap_err();
5581        assert!(
5582            matches!(
5583                err,
5584                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5585                    if caixa == "worker" && versao == "v0.1"
5586            ),
5587            "got {err:?}"
5588        );
5589    }
5590
5591    #[test]
5592    fn validate_accepts_canonical_child_versao_forms() {
5593        // The Cargo-shaped requirement forms `:deps :versao` and
5594        // `:membros :versao` already accept via
5595        // `crate::parse_requirement` must pass the children gate
5596        // without re-validating at the resolver layer. Pin every leg so
5597        // a future tightening of the canonical set surfaces here as a
5598        // test failure.
5599        for form in [
5600            "^0.1",      // caret — minor-range pin (the most common shape)
5601            "~0.1.2",    // tilde — patch-range pin
5602            "0.1.0",     // exact — single-version pin
5603            "*",         // wildcard — any version (semver::VersionReq::STAR)
5604            ">=0.1, <2", // multi-range — comma-separated comparators
5605        ] {
5606            let s = SupervisorSpec {
5607                children: vec![child("worker", form, RestartPolicy::Permanent)],
5608                ..SupervisorSpec::default()
5609            };
5610            s.validate()
5611                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5612        }
5613    }
5614
5615    #[test]
5616    fn child_versao_empty_takes_precedence_over_invalid() {
5617        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5618        // doesn't try to parse) fires before the new
5619        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5620        // `:versao` keeps its narrower error message —
5621        // `parse_requirement` would also reject `""`, but the
5622        // empty-string arm is the more self-locating diagnostic for the
5623        // author. Same ordering discipline as
5624        // `membro_versao_empty_takes_precedence_over_invalid` in
5625        // aplicacao.rs.
5626        let s = SupervisorSpec {
5627            children: vec![child("worker", "", RestartPolicy::Permanent)],
5628            ..SupervisorSpec::default()
5629        };
5630        let err = s.validate().unwrap_err();
5631        assert!(
5632            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5633            "got {err:?}"
5634        );
5635    }
5636
5637    #[test]
5638    fn child_versao_invalid_fires_before_duplicate_check() {
5639        // Order pin: a malformed requirement on a non-duplicate entry
5640        // surfaces *its own* diagnostic (which names the offending
5641        // `:versao` string), even when a later entry would otherwise
5642        // collapse onto an earlier name. The per-entry shape gate runs
5643        // inline before the duplicate-key insert — parallel to
5644        // `membro_versao_invalid_fires_before_duplicate_check` in
5645        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5646        let s = SupervisorSpec {
5647            children: vec![
5648                child("worker", "^bad", RestartPolicy::Permanent),
5649                child("cache", "^0.1", RestartPolicy::Transient),
5650                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5651            ],
5652            ..SupervisorSpec::default()
5653        };
5654        let err = s.validate().unwrap_err();
5655        assert!(
5656            matches!(
5657                err,
5658                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5659            ),
5660            "got {err:?}"
5661        );
5662    }
5663
5664    #[test]
5665    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5666        // The diagnostic-shape pin: the error names the offending
5667        // `:versao` value verbatim so the author can grep their
5668        // caixa.lisp without re-running the build, and carries a
5669        // non-empty `reason` from `semver::VersionReq::parse` so the
5670        // parser's own wording flows through to the diagnostic.
5671        let s = SupervisorSpec {
5672            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5673            ..SupervisorSpec::default()
5674        };
5675        let err = s.validate().unwrap_err();
5676        let SupervisorError::ChildVersaoInvalid {
5677            caixa,
5678            versao,
5679            reason,
5680        } = err
5681        else {
5682            panic!("expected ChildVersaoInvalid, got other variant");
5683        };
5684        assert_eq!(caixa, "worker");
5685        assert_eq!(versao, "not-a-req");
5686        assert!(
5687            !reason.is_empty(),
5688            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5689        );
5690    }
5691
5692    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5693
5694    #[test]
5695    fn validate_rejects_child_caixa_with_uppercase() {
5696        // The canonical "I copied the Servico's display name verbatim"
5697        // typo — child caixa names are lowercase per K8s DNS-1123 label
5698        // rule. The diagnostic names the offending name and suggests the
5699        // lower-cased fix in one edit, mirroring the
5700        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5701        let s = SupervisorSpec {
5702            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5703            ..SupervisorSpec::default()
5704        };
5705        let err = s.validate().unwrap_err();
5706        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5707            panic!("expected ChildCaixaInvalid, got other variant");
5708        };
5709        assert_eq!(caixa, "Worker");
5710        assert!(
5711            reason.contains("uppercase"),
5712            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5713        );
5714        assert!(
5715            reason.contains("\"worker\""),
5716            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5717        );
5718    }
5719
5720    #[test]
5721    fn validate_rejects_child_caixa_with_underscore() {
5722        // The canonical "I'm thinking of a Python module / Postgres
5723        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5724        // label schema. K8s rejects `metadata.name: my_worker` at
5725        // admission time with an opaque `field is invalid` (no source-
5726        // citing diagnostic). The gate moves it to caixa-build time.
5727        let s = SupervisorSpec {
5728            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5729            ..SupervisorSpec::default()
5730        };
5731        let err = s.validate().unwrap_err();
5732        assert!(
5733            matches!(
5734                err,
5735                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5736                    if caixa == "my_worker" && reason.contains('_')
5737            ),
5738            "got {err:?}"
5739        );
5740    }
5741
5742    #[test]
5743    fn validate_rejects_child_caixa_with_dot() {
5744        // A `:children :caixa` entry is a single DNS-1123 label, not a
5745        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5746        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5747        // (3f9d7a0) on the peer name axis.
5748        let s = SupervisorSpec {
5749            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5750            ..SupervisorSpec::default()
5751        };
5752        let err = s.validate().unwrap_err();
5753        assert!(
5754            matches!(
5755                err,
5756                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5757                    if caixa == "team.worker" && reason.contains('.')
5758            ),
5759            "got {err:?}"
5760        );
5761    }
5762
5763    #[test]
5764    fn validate_rejects_child_caixa_with_leading_hyphen() {
5765        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5766        // with an alphanumeric. The K8s apiserver rejects `-worker`
5767        // outright; the renderer would emit a `metadata.name: "-worker"`
5768        // that fails admission far from the source caixa.lisp.
5769        let s = SupervisorSpec {
5770            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5771            ..SupervisorSpec::default()
5772        };
5773        let err = s.validate().unwrap_err();
5774        assert!(
5775            matches!(
5776                err,
5777                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5778                    if caixa == "-worker" && reason.contains("start and end")
5779            ),
5780            "got {err:?}"
5781        );
5782    }
5783
5784    #[test]
5785    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5786        // The symmetric arm of the boundary rule. Pin separately so
5787        // both ends of the label are covered against a future relaxation
5788        // that only checks one boundary.
5789        let s = SupervisorSpec {
5790            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5791            ..SupervisorSpec::default()
5792        };
5793        let err = s.validate().unwrap_err();
5794        assert!(
5795            matches!(
5796                err,
5797                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5798                    if caixa == "worker-"
5799            ),
5800            "got {err:?}"
5801        );
5802    }
5803
5804    #[test]
5805    fn validate_rejects_child_caixa_with_unicode() {
5806        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5807        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5808        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5809        // by the first byte that fails the `[a-z0-9-]` predicate.
5810        let s = SupervisorSpec {
5811            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5812            ..SupervisorSpec::default()
5813        };
5814        let err = s.validate().unwrap_err();
5815        assert!(
5816            matches!(
5817                err,
5818                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5819                    if caixa == "café"
5820            ),
5821            "got {err:?}"
5822        );
5823    }
5824
5825    #[test]
5826    fn validate_rejects_child_caixa_with_whitespace() {
5827        // Whitespace is the canonical "I pasted from a sketch / doc"
5828        // footgun. The apiserver rejects every `metadata.name` value
5829        // carrying whitespace; pin the gate fires at the right boundary.
5830        let s = SupervisorSpec {
5831            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5832            ..SupervisorSpec::default()
5833        };
5834        let err = s.validate().unwrap_err();
5835        assert!(
5836            matches!(
5837                err,
5838                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5839                    if caixa == "my worker"
5840            ),
5841            "got {err:?}"
5842        );
5843    }
5844
5845    #[test]
5846    fn validate_rejects_child_caixa_too_long() {
5847        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5848        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5849        // axis over the limit at admission time. The diagnostic names
5850        // both the cap and the actual length so the author can shorten
5851        // in one edit, mirroring `rejects_membro_caixa_too_long`
5852        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5853        let too_long = "a".repeat(64);
5854        let s = SupervisorSpec {
5855            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5856            ..SupervisorSpec::default()
5857        };
5858        let err = s.validate().unwrap_err();
5859        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5860            panic!("expected ChildCaixaInvalid, got other variant");
5861        };
5862        assert_eq!(caixa, too_long);
5863        assert!(
5864            reason.contains("63"),
5865            "diagnostic must name the 63-byte cap (got: {reason:?})"
5866        );
5867        assert!(
5868            reason.contains("64"),
5869            "diagnostic must name the actual length (got: {reason:?})"
5870        );
5871    }
5872
5873    #[test]
5874    fn child_caixa_max_length_validates() {
5875        // The 63-byte boundary control pin — exactly-at-the-cap is
5876        // accepted, mirroring `membro_caixa_max_length_validates`
5877        // (3f9d7a0) and `placement_cluster_max_length_validates`
5878        // (6cbb900). Pinned separately so a future off-by-one tightening
5879        // surfaces here.
5880        let max_label = "a".repeat(63);
5881        let s = SupervisorSpec {
5882            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5883            ..SupervisorSpec::default()
5884        };
5885        s.validate().unwrap();
5886    }
5887
5888    #[test]
5889    fn validate_accepts_canonical_child_caixa_forms() {
5890        // The realistic shapes a supervised child's `:caixa` carries —
5891        // single-word `worker`, version-suffixed `cache-v2`, single-char
5892        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5893        // `payment-retry`, all-digit `0`. Pin every leg so a future
5894        // tightening (e.g. requiring a leading lowercase letter) surfaces
5895        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5896        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5897        // (6cbb900).
5898        for form in [
5899            "worker",
5900            "cache-v2",
5901            "a",
5902            "db",
5903            "2-pool",
5904            "payment-retry",
5905            "0",
5906        ] {
5907            let s = SupervisorSpec {
5908                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5909                ..SupervisorSpec::default()
5910            };
5911            s.validate()
5912                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5913        }
5914    }
5915
5916    #[test]
5917    fn child_caixa_empty_takes_precedence_over_invalid() {
5918        // Order pin: the existing `EmptyChildName` diagnostic (which
5919        // doesn't try to parse the DNS-1123 shape) fires before the new
5920        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5921        // its narrower error message — `is_dns_1123_label` would reject
5922        // the empty string too (boundary check on the first byte), but
5923        // the empty-string arm is the more self-locating diagnostic for
5924        // the author. Same ordering discipline as
5925        // `membro_caixa_empty_takes_precedence_over_invalid` in
5926        // aplicacao.rs.
5927        let s = SupervisorSpec {
5928            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5929            ..SupervisorSpec::default()
5930        };
5931        let err = s.validate().unwrap_err();
5932        assert_eq!(err, SupervisorError::EmptyChildName);
5933    }
5934
5935    #[test]
5936    fn child_caixa_invalid_fires_before_versao_check() {
5937        // Order pin: the per-axis shape gate runs inline before the
5938        // per-entry versao check, so a malformed `:caixa` on an entry
5939        // whose `:versao` would also fail surfaces the more self-
5940        // locating name-axis diagnostic first. Parallel to
5941        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5942        // and `placement_cluster_invalid_fires_before_duplicate_check`
5943        // (6cbb900).
5944        let s = SupervisorSpec {
5945            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5946            ..SupervisorSpec::default()
5947        };
5948        let err = s.validate().unwrap_err();
5949        assert!(
5950            matches!(
5951                err,
5952                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5953            ),
5954            "got {err:?}"
5955        );
5956    }
5957
5958    #[test]
5959    fn child_caixa_invalid_fires_before_duplicate_check() {
5960        // Order pin: a malformed name on a non-duplicate entry surfaces
5961        // its own diagnostic, even when a later entry would otherwise
5962        // collapse onto an earlier name. The per-entry shape gate runs
5963        // inline before the duplicate-key HashSet insert, mirroring
5964        // `placement_cluster_invalid_fires_before_duplicate_check`
5965        // (6cbb900).
5966        let s = SupervisorSpec {
5967            children: vec![
5968                child("Worker", "^0.1", RestartPolicy::Permanent),
5969                child("cache", "^0.1", RestartPolicy::Transient),
5970                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5971            ],
5972            ..SupervisorSpec::default()
5973        };
5974        let err = s.validate().unwrap_err();
5975        assert!(
5976            matches!(
5977                err,
5978                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5979            ),
5980            "got {err:?}"
5981        );
5982    }
5983
5984    #[test]
5985    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5986        // The diagnostic-shape pin: the error names the offending
5987        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5988        // the author can grep their caixa.lisp without re-running the
5989        // build. Mirrors the diagnostic-shape sweep on every prior
5990        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5991        let s = SupervisorSpec {
5992            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5993            ..SupervisorSpec::default()
5994        };
5995        let err = s.validate().unwrap_err();
5996        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5997            panic!("expected ChildCaixaInvalid, got other variant");
5998        };
5999        assert_eq!(caixa, "My_Worker");
6000        assert!(
6001            !reason.is_empty(),
6002            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6003        );
6004    }
6005
6006    // ── value-shape: zero restart_window + duplicate child names ──────────
6007
6008    #[test]
6009    fn validate_accepts_none_restart_window() {
6010        // Omitted `:restart-window` is the "never reset" sentinel —
6011        // valid by design. Mirrors :limits axes where None = unbounded.
6012        let s = SupervisorSpec {
6013            restart_window: None,
6014            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6015            ..SupervisorSpec::default()
6016        };
6017        s.validate().unwrap();
6018    }
6019
6020    #[test]
6021    fn validate_rejects_zero_restart_window() {
6022        // Same "0 means the opposite of what you think" footgun closed
6023        // for :politicas :timeout (Envoy treats 0s as infinite) and
6024        // :limits :wall-clock (wasmtime traps before the call starts).
6025        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6026        let s = SupervisorSpec {
6027            restart_window: Some(Duration::ZERO),
6028            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6029            ..SupervisorSpec::default()
6030        };
6031        assert_eq!(
6032            s.validate().unwrap_err(),
6033            SupervisorError::RestartWindowZero
6034        );
6035    }
6036
6037    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6038    //
6039    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6040    // the integer-millisecond canonical-form gate — peer with
6041    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6042    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6043    // path is already gated at the shared codec layer (see
6044    // `restart_window_serde_rejects_fractional_seconds`); this arm
6045    // closes the programmatic-struct-literal path the codec gate can't
6046    // see.
6047
6048    #[test]
6049    fn validate_rejects_sub_millisecond_restart_window() {
6050        // The fail-before-pass-after pin: a programmatic
6051        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6052        // `validate` on every pre-gate codebase, then truncated to
6053        // `as_millis() == 1` on first serialize — the shared codec
6054        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6055        // 1_000_000 ns, the typed `restart_window` no longer matches
6056        // its rendered form.
6057        let s = SupervisorSpec {
6058            restart_window: Some(Duration::from_micros(1500)),
6059            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6060            ..SupervisorSpec::default()
6061        };
6062        match s.validate().unwrap_err() {
6063            SupervisorError::RestartWindowNotCanonical { window } => {
6064                assert_eq!(window, Duration::from_micros(1500));
6065            }
6066            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6067        }
6068    }
6069
6070    #[test]
6071    fn validate_rejects_one_nanosecond_restart_window() {
6072        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6073        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6074        // so the shared codec emits the literal `"0s"` — the next
6075        // serde round-trip would parse back to `Duration::ZERO`, which
6076        // the `RestartWindowZero` arm then rejects on re-validate. The
6077        // canonical-form gate at this layer surfaces a self-locating
6078        // diagnostic naming the offending Duration verbatim rather
6079        // than a downstream `RestartWindowZero` whose remediation
6080        // points at omitting the slot.
6081        let s = SupervisorSpec {
6082            restart_window: Some(Duration::from_nanos(1)),
6083            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6084            ..SupervisorSpec::default()
6085        };
6086        match s.validate().unwrap_err() {
6087            SupervisorError::RestartWindowNotCanonical { window } => {
6088                assert_eq!(window, Duration::from_nanos(1));
6089            }
6090            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6091        }
6092    }
6093
6094    #[test]
6095    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6096        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6097        // 1_000_001 ns is structurally past the integer-ms granularity
6098        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6099        // trip would truncate to `1ms` and the consumer would observe
6100        // a 1-ns drift on every emit. Same boundary the peer
6101        // `validate_rejects_nanosecond_past_canonical_boundary` test
6102        // in limits.rs pins for the `:limits :wall-clock` axis.
6103        let w = Duration::from_nanos(1_000_001);
6104        let s = SupervisorSpec {
6105            restart_window: Some(w),
6106            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6107            ..SupervisorSpec::default()
6108        };
6109        assert_eq!(
6110            s.validate().unwrap_err(),
6111            SupervisorError::RestartWindowNotCanonical { window: w }
6112        );
6113    }
6114
6115    #[test]
6116    fn validate_accepts_integer_millisecond_restart_window_values() {
6117        // The positive-control sweep: every `Duration` the shared
6118        // codec can round-trip losslessly — the canonical
6119        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6120        // pair emits and accepts — passes `validate` without
6121        // surfacing the new canonical-form arm. Mirrors
6122        // `validate_accepts_integer_millisecond_wall_clock_values` on
6123        // the sibling `:limits :wall-clock` axis.
6124        for w in [
6125            Duration::from_millis(1),
6126            Duration::from_millis(500),
6127            Duration::from_millis(1500),
6128            Duration::from_secs(1),
6129            Duration::from_secs(30),
6130            Duration::from_secs(60),
6131            Duration::from_secs(120),
6132            Duration::from_secs(3600),
6133        ] {
6134            let s = SupervisorSpec {
6135                restart_window: Some(w),
6136                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6137                ..SupervisorSpec::default()
6138            };
6139            s.validate()
6140                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6141        }
6142    }
6143
6144    #[test]
6145    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6146        // Cross-arm ordering pin: `Duration::ZERO` has
6147        // `subsec_nanos() == 0` and would otherwise pass the
6148        // canonical-form arm — the zero-floor arm must fire first so
6149        // the more self-locating `RestartWindowZero` diagnostic (with
6150        // its omit-axis remediation directly named) leads. Same
6151        // posture every peer zero-then-shape gate uses
6152        // (`WallClockZero` → `WallClockNotCanonical`,
6153        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6154        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6155        let s = SupervisorSpec {
6156            restart_window: Some(Duration::ZERO),
6157            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6158            ..SupervisorSpec::default()
6159        };
6160        assert_eq!(
6161            s.validate().unwrap_err(),
6162            SupervisorError::RestartWindowZero
6163        );
6164    }
6165
6166    #[test]
6167    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6168        // Diagnostic-shape pin: the canonical-form arm names the
6169        // offending `Duration` verbatim so the author's grep lands on
6170        // the field's value, not a generic "duration not canonical"
6171        // message. Same shape every other typed-canonical-form arm
6172        // on this surface carries (`WallClockNotCanonical` carries
6173        // the offending `Duration` verbatim,
6174        // `PolicyTimeoutNotCanonical` carries the offending
6175        // `Duration` verbatim).
6176        let w = Duration::from_micros(500);
6177        let s = SupervisorSpec {
6178            restart_window: Some(w),
6179            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6180            ..SupervisorSpec::default()
6181        };
6182        let err = s.validate().unwrap_err();
6183        let msg = err.to_string();
6184        assert!(
6185            msg.contains("500"),
6186            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6187        );
6188        assert!(
6189            msg.contains("sub-millisecond"),
6190            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6191        );
6192    }
6193
6194    #[test]
6195    fn restart_window_validated_value_round_trips_through_codec() {
6196        // The structural property the canonical-ms gate enforces:
6197        // every `SupervisorSpec::restart_window` past
6198        // `SupervisorSpec::validate` round-trips losslessly through
6199        // the shared duration codec (serialize → string →
6200        // deserialize → equal value). Pin this end-to-end so a future
6201        // change to either side (the validate gate's accepted
6202        // granularity, the codec's parse/render unit set) that breaks
6203        // the alignment surfaces here. Peer of
6204        // `wall_clock_validated_value_round_trips_through_codec` on
6205        // the sibling `:limits :wall-clock` axis.
6206        for w in [
6207            Duration::from_millis(1),
6208            Duration::from_millis(1500),
6209            Duration::from_secs(30),
6210            Duration::from_secs(3600),
6211        ] {
6212            let s = SupervisorSpec {
6213                restart_window: Some(w),
6214                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6215                ..SupervisorSpec::default()
6216            };
6217            s.validate().unwrap();
6218            let json = serde_json::to_string(&s).unwrap();
6219            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6220            assert_eq!(back.restart_window, Some(w));
6221        }
6222    }
6223
6224    // ── value-shape: upper cap on :restart-window ─────────────────────────
6225    //
6226    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6227    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6228    // `:politicas :timeout` (2e8ee7e), and `:politicas
6229    // :circuit-breaker :window` (379a814). Brackets the typed
6230    // `:restart-window` axis structurally: every validated value lies
6231    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6232    // granularity, closing the
6233    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6234    // zero-floor-and-canonical-form-only checks left open.
6235
6236    #[test]
6237    fn validate_rejects_restart_window_above_cap() {
6238        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6239        // structurally one canonical-tick past the
6240        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6241        // integer-millisecond magnitude the canonical-form arm above
6242        // accepts cleanly, that the shared duration codec round-trips
6243        // losslessly as `"3601s"`, and that silently passed validate on
6244        // every pre-gate codebase because the typed slot's only checks
6245        // were the zero-floor and canonical-form arms. The runtime
6246        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6247        // Period reconciler, the future wasm-operator's per-supervisor
6248        // restart-intensity counter) reaches for a `Duration` so long
6249        // no realistic restart-recovery pattern resets the counter,
6250        // far from the source caixa.lisp.
6251        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6252        let s = SupervisorSpec {
6253            restart_window: Some(w),
6254            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6255            ..SupervisorSpec::default()
6256        };
6257        assert_eq!(
6258            s.validate().unwrap_err(),
6259            SupervisorError::RestartWindowExceedsCap { window: w }
6260        );
6261    }
6262
6263    #[test]
6264    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6265        // Boundary case: exactly 1ms past the cap (the granularity the
6266        // canonical-form gate enforces). Catches a future "strictly
6267        // less than" half-measure and pins the diagnostic to name the
6268        // offending `Duration` verbatim. Peer of
6269        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6270        // `rejects_policy_timeout_one_millisecond_above_cap` /
6271        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6272        // on the sibling typed-`Duration` axes' top edges.
6273        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6274        let s = SupervisorSpec {
6275            restart_window: Some(w),
6276            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6277            ..SupervisorSpec::default()
6278        };
6279        assert_eq!(
6280            s.validate().unwrap_err(),
6281            SupervisorError::RestartWindowExceedsCap { window: w }
6282        );
6283    }
6284
6285    #[test]
6286    fn validate_rejects_restart_window_far_above_cap() {
6287        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6288        // `(:restart-window "7d")`, or any "I want a lifetime counter
6289        // but wrote a `<integer>h` magnitude anyway" typo — values the
6290        // canonical-form arm accepts as integer-millisecond magnitudes,
6291        // the codec round-trips losslessly through serde, but the
6292        // operator's `MaxIntensity / Period` reconciler cannot honor
6293        // as a meaningful rolling window. Until this gate landed
6294        // validate accepted them. Pin the common above-cap values (24h,
6295        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6296        // surfaces here.
6297        for w in [
6298            Duration::from_secs(86_400),    // 24h
6299            Duration::from_secs(604_800),   // 7d
6300            Duration::from_secs(1_000_000), // ~11.5 days
6301        ] {
6302            let s = SupervisorSpec {
6303                restart_window: Some(w),
6304                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6305                ..SupervisorSpec::default()
6306            };
6307            assert_eq!(
6308                s.validate().unwrap_err(),
6309                SupervisorError::RestartWindowExceedsCap { window: w }
6310            );
6311        }
6312    }
6313
6314    #[test]
6315    fn validate_accepts_restart_window_at_cap() {
6316        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6317        // (1h) — must validate. The cap is inclusive on the top edge,
6318        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6319        // [`crate::POLICY_TIMEOUT_MAX`] /
6320        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6321        // capped axes. Pin the boundary explicitly so a future
6322        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6323        // instead of `>`) surfaces here as a test failure rather than a
6324        // silent contract narrowing.
6325        let s = SupervisorSpec {
6326            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6327            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6328            ..SupervisorSpec::default()
6329        };
6330        s.validate()
6331            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6332    }
6333
6334    #[test]
6335    fn validate_accepts_restart_window_typical_values() {
6336        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6337        // per-supervisor production-playbook band positive-control
6338        // sweep — every value Learn You Some Erlang's `{intensity, 5,
6339        // 60}` worker-supervisor `Period = 60s` default, Elixir's
6340        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6341        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6342        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6343        // default recommend (5s..=300s) must pass, plus a sweep
6344        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6345        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6346        // on the sibling `:limits :wall-clock` axis.
6347        for w in [
6348            Duration::from_millis(1),
6349            Duration::from_millis(500),
6350            Duration::from_secs(1),
6351            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
6352            Duration::from_secs(10), // Riak Core lower
6353            Duration::from_secs(30),
6354            Duration::from_secs(60),  // Learn You Some Erlang default
6355            Duration::from_secs(120), // OTP supervisor MaxT typical
6356            Duration::from_secs(300), // Riak Core upper
6357            Duration::from_secs(900), // 15m
6358            Duration::from_secs(1800),
6359            Duration::from_secs(3600), // exactly 1h, the cap
6360        ] {
6361            let s = SupervisorSpec {
6362                restart_window: Some(w),
6363                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6364                ..SupervisorSpec::default()
6365            };
6366            s.validate()
6367                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6368        }
6369    }
6370
6371    #[test]
6372    fn restart_window_zero_takes_precedence_over_cap() {
6373        // The cross-arm ordering pin: `Duration::ZERO` is structurally
6374        // outside both `>= 1ms` (zero-floor) and `<=
6375        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6376        // diagnostic is the more self-locating one (it directly names
6377        // the omit-axis remediation), so the validate gate must fire
6378        // on zero first. Same shape every other zero-then-cap ordering
6379        // on this surface uses (`WallClockZero` then
6380        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6381        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6382        // `PolicyBreakerWindowExceedsCap`).
6383        let s = SupervisorSpec {
6384            restart_window: Some(Duration::ZERO),
6385            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6386            ..SupervisorSpec::default()
6387        };
6388        assert_eq!(
6389            s.validate().unwrap_err(),
6390            SupervisorError::RestartWindowZero,
6391            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6392        );
6393    }
6394
6395    #[test]
6396    fn restart_window_canonical_takes_precedence_over_cap() {
6397        // The cross-arm ordering pin: a `Duration` that is *both*
6398        // sub-millisecond (non-canonical-form) and structurally above
6399        // the cap surfaces the canonical-form diagnostic first,
6400        // because the round-trip-shape break is the more fundamental
6401        // issue (the value can't even round-trip through the codec,
6402        // so the cap diagnostic naming `1ms..=1h` would be misleading
6403        // — there's no integer-ms form of the offending value). Pin
6404        // the order so a future refactor that reorders the arms
6405        // surfaces here as a test failure rather than a silent
6406        // diagnostic regression. Peer of
6407        // `wall_clock_canonical_takes_precedence_over_cap` /
6408        // `policy_timeout_canonical_takes_precedence_over_cap`.
6409        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6410        let s = SupervisorSpec {
6411            restart_window: Some(w),
6412            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6413            ..SupervisorSpec::default()
6414        };
6415        assert_eq!(
6416            s.validate().unwrap_err(),
6417            SupervisorError::RestartWindowNotCanonical { window: w },
6418            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6419        );
6420    }
6421
6422    #[test]
6423    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6424        // The cross-arm ordering pin between the `:max-restarts` cap
6425        // and the sibling `:restart-window` cap. A supervisor carrying
6426        // both an over-cap `max_restarts` AND an over-cap window must
6427        // surface the `MaxRestartsExceedsCap` diagnostic first — the
6428        // cap arm is wired immediately after the zero-restart arm and
6429        // strictly before every window-axis arm (zero / canonical /
6430        // cap), so the offending value the diagnostic names matches
6431        // the order the author would discover the gates by reading
6432        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6433        // order so a future refactor that reorders the arms surfaces
6434        // here as a test failure rather than a silent diagnostic
6435        // regression. Peer of
6436        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6437        // on the sibling zero / canonical window arms.
6438        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6439        let s = SupervisorSpec {
6440            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6441            restart_window: Some(w),
6442            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6443            ..SupervisorSpec::default()
6444        };
6445        assert_eq!(
6446            s.validate().unwrap_err(),
6447            SupervisorError::MaxRestartsExceedsCap {
6448                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6449            },
6450            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6451        );
6452    }
6453
6454    #[test]
6455    fn restart_window_cap_diagnostic_carries_offending_value() {
6456        // The diagnostic-shape pin: the offending `Duration` is
6457        // carried verbatim into the
6458        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6459        // surfaced error message names the value the author wrote,
6460        // not just the cap. Same self-locating diagnostic shape every
6461        // other typed-cap arm on this surface carries
6462        // (`WallClockExceedsCap` carries the offending `Duration`
6463        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6464        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6465        // the offending `Duration` verbatim).
6466        let w = Duration::from_secs(7200); // 2h
6467        let s = SupervisorSpec {
6468            restart_window: Some(w),
6469            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6470            ..SupervisorSpec::default()
6471        };
6472        let err = s.validate().unwrap_err();
6473        assert!(
6474            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6475            "got {err:?}"
6476        );
6477        let msg = err.to_string();
6478        assert!(
6479            msg.contains("7200"),
6480            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6481        );
6482    }
6483
6484    #[test]
6485    fn supervisor_restart_window_cap_pins_canonical_value() {
6486        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6487        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6488        // shared duration codec emits as a clean canonical string
6489        // (`"<n>h"`). Pinning the literal value here surfaces a future
6490        // drift (a relaxation to 24h, a tightening to 5m) as a
6491        // deliberate test edit, not a silent contract narrowing.
6492        //
6493        // The four typed-`Duration` caps on the validation surface
6494        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6495        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6496        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6497        // single uniform top edge at the codec's largest emitted unit
6498        // — a structural-property invariant the equality assertions
6499        // here enshrine, so a future drift on any of the four
6500        // surfaces as a deliberate test edit. Same shape every other
6501        // typed-cap value pin uses
6502        // (`wall_clock_cap_pins_canonical_value`,
6503        // `policy_timeout_cap_pins_canonical_value`,
6504        // `circuit_breaker_window_cap_pins_canonical_value`).
6505        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6506        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6507        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6508        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6509        assert_eq!(
6510            SUPERVISOR_RESTART_WINDOW_MAX,
6511            crate::POLICY_BREAKER_WINDOW_MAX
6512        );
6513    }
6514
6515    #[test]
6516    fn restart_window_cap_value_round_trips_through_codec() {
6517        // The codec round-trip property the cap arm preserves: the
6518        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6519        // through the shared duration codec — every value at the cap
6520        // serializes to the canonical `"1h"` form and parses back
6521        // identically. Pin the round-trip so a future change to the
6522        // codec's unit set or to the cap's magnitude that breaks the
6523        // round-trip property surfaces here. Peer of
6524        // `wall_clock_cap_value_round_trips_through_codec` on the
6525        // sibling `:limits :wall-clock` axis.
6526        let s = SupervisorSpec {
6527            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6528            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6529            ..SupervisorSpec::default()
6530        };
6531        s.validate().unwrap();
6532        let json = serde_json::to_string(&s).unwrap();
6533        assert!(
6534            json.contains("\"1h\""),
6535            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6536        );
6537        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6538        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6539    }
6540
6541    #[test]
6542    fn validate_rejects_duplicate_child_caixa() {
6543        // Two children with the same :caixa render to two ComputeUnits
6544        // with the same name in the cluster's HelmRelease values —
6545        // one silently overwrites the other. Erlang/OTP's child_spec.id
6546        // is required-unique per supervisor; same set-not-multiset
6547        // discipline applied here as for :membros / :placement
6548        // :clusters / :entrada :paths.
6549        let s = SupervisorSpec {
6550            children: vec![
6551                child("worker", "^0.1", RestartPolicy::Permanent),
6552                child("cache", "^0.1", RestartPolicy::Transient),
6553                child("worker", "^0.2", RestartPolicy::Permanent),
6554            ],
6555            ..SupervisorSpec::default()
6556        };
6557        let err = s.validate().unwrap_err();
6558        assert!(
6559            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6560            "got {err:?}"
6561        );
6562    }
6563
6564    #[test]
6565    fn validate_duplicate_child_diagnostic_names_first_collision() {
6566        // Iteration walks the :children list in declaration order —
6567        // the diagnostic names the first repeat, deterministically,
6568        // even when multiple names duplicate.
6569        let s = SupervisorSpec {
6570            children: vec![
6571                child("a", "^0.1", RestartPolicy::Permanent),
6572                child("b", "^0.1", RestartPolicy::Permanent),
6573                child("a", "^0.1", RestartPolicy::Permanent),
6574                child("b", "^0.1", RestartPolicy::Permanent),
6575            ],
6576            ..SupervisorSpec::default()
6577        };
6578        let err = s.validate().unwrap_err();
6579        assert!(
6580            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6581            "got {err:?}"
6582        );
6583    }
6584
6585    // ── self-supervision cross-slot gate ──────────────────────────
6586
6587    #[test]
6588    fn validate_no_self_supervision_rejects_self_referential_child() {
6589        // A supervisor whose `:children` lists its own `:nome` is a
6590        // one-node reconciliation cycle — rejected, naming the parent.
6591        let children = vec![
6592            child("worker", "^0.1", RestartPolicy::Permanent),
6593            child("orquestra", "^0.1", RestartPolicy::Permanent),
6594        ];
6595        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6596        assert!(
6597            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6598            "got {err:?}"
6599        );
6600    }
6601
6602    #[test]
6603    fn validate_no_self_supervision_accepts_distinct_children() {
6604        // Positive control: distinct child names (including a child that
6605        // is itself a supervisor — nested trees are valid OTP) pass.
6606        let children = vec![
6607            child("worker", "^0.1", RestartPolicy::Permanent),
6608            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6609        ];
6610        validate_no_self_supervision(&children, "orquestra").unwrap();
6611    }
6612
6613    #[test]
6614    fn validate_no_self_supervision_empty_children_is_ok() {
6615        // SimpleOneForOne / no-static-children supervisors have nothing
6616        // to self-reference — the gate is vacuously satisfied.
6617        validate_no_self_supervision(&[], "orquestra").unwrap();
6618    }
6619
6620    #[test]
6621    fn validate_simple_one_for_one_skips_uniqueness_check() {
6622        // SimpleOneForOne supervisors carry no static children — the
6623        // duplicate-child loop never runs. A zero-window declaration
6624        // on a SimpleOneForOne supervisor still trips the window check
6625        // (window applies to dynamic children too).
6626        let s = SupervisorSpec {
6627            estrategia: RestartStrategy::SimpleOneForOne,
6628            restart_window: None,
6629            children: vec![],
6630            ..SupervisorSpec::default()
6631        };
6632        s.validate().unwrap();
6633        let s_zero = SupervisorSpec {
6634            estrategia: RestartStrategy::SimpleOneForOne,
6635            restart_window: Some(Duration::ZERO),
6636            children: vec![],
6637            ..SupervisorSpec::default()
6638        };
6639        assert_eq!(
6640            s_zero.validate().unwrap_err(),
6641            SupervisorError::RestartWindowZero
6642        );
6643    }
6644
6645    #[test]
6646    fn validate_zero_window_runs_after_max_restarts_check() {
6647        // Pin the order: max_restarts == 0 fires before
6648        // restart_window == 0s, so an author with both wrong sees the
6649        // counter-axis diagnostic first (matches the order in the
6650        // struct and in the doc comment).
6651        let s = SupervisorSpec {
6652            max_restarts: 0,
6653            restart_window: Some(Duration::ZERO),
6654            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6655            ..SupervisorSpec::default()
6656        };
6657        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6658    }
6659
6660    #[test]
6661    fn round_trip_all_strategies() {
6662        for &strat in RestartStrategy::ALL {
6663            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6664            // shape partition through the [`gen_platform::IsVariant`]
6665            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6666            // predicate rather than the raw
6667            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6668            // open-coded pattern-match — same closed-set-typed-enum
6669            // arm-discriminator dispatch discipline the sibling
6670            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6671            // (915a934) extended onto its two paired positive / negated
6672            // `matches!` filter sites, and the sibling
6673            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6674            // predicate convergence (766ec63) extended onto the M3 mesh-
6675            // slot per-`:placement` distribution-strategy `matches!`
6676            // discriminator axis. See the sibling
6677            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6678            // fixture and the peer `manifest::tests::
6679            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6680            // fixture — all three sites (the last unlifted
6681            // `matches!`-based arm-discriminator axis on the OTP-shape
6682            // supervisor sibling-restart-strategy closed-set typed enum,
6683            // acknowledged in 915a934's Prior-commits footnote as the
6684            // outstanding follow-up) now consult one typed dispatch on
6685            // the substrate primitive.
6686            let s = SupervisorSpec {
6687                estrategia: strat,
6688                children: if strat.is_simple_one_for_one() {
6689                    vec![]
6690                } else {
6691                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6692                },
6693                ..SupervisorSpec::default()
6694            };
6695            let json = serde_json::to_string(&s).unwrap();
6696            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6697            assert_eq!(s, back);
6698        }
6699    }
6700
6701    #[test]
6702    fn round_trip_all_restart_policies() {
6703        for policy in [
6704            RestartPolicy::Permanent,
6705            RestartPolicy::Temporary,
6706            RestartPolicy::Transient,
6707        ] {
6708            let c = child("w", "^0.1", policy);
6709            let json = serde_json::to_string(&c).unwrap();
6710            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6711            assert_eq!(c, back);
6712        }
6713    }
6714
6715    #[test]
6716    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6717        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6718        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6719        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6720        // is the only variant that satisfies `.is_simple_one_for_one()`;
6721        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6722        // / `RestForOne`) returns `false`. This pin makes the partition
6723        // invariant load-bearing at caixa-core test time so a future
6724        // derive regression (a hole that returns `false` for
6725        // `SimpleOneForOne` too, or a byte-collision that flips a second
6726        // variant to `true`) trips here rather than laundering the arm
6727        // at the three test-fixture builder sites (a hole flips the
6728        // `SimpleOneForOne` fixture to carry a non-empty children list
6729        // and the subsequent `SupervisorSpec::validate` would refuse the
6730        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6731        // a collision flips a peer strategy's fixture to carry an empty
6732        // children list and the subsequent `validate` would refuse with
6733        // [`SupervisorError::NoChildren`] — either way, the pin fires
6734        // here, at the derive site, rather than at the fixture-refusal
6735        // site far away). Peer of the sibling
6736        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6737        // (915a934) pin on the M2 OTP-appup axis and the sibling
6738        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6739        // pin on the M0 `:kind` axis.
6740        let cases: &[(RestartStrategy, bool)] = &[
6741            (RestartStrategy::OneForOne, false),
6742            (RestartStrategy::OneForAll, false),
6743            (RestartStrategy::RestForOne, false),
6744            (RestartStrategy::SimpleOneForOne, true),
6745        ];
6746        for (variant, expected) in cases {
6747            assert_eq!(
6748                variant.is_simple_one_for_one(),
6749                *expected,
6750                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6751                 return {expected} (partition invariant on the \
6752                 IsVariant-derived arm-discriminator predicate — every \
6753                 test-fixture site that partitions the `:children` slot \
6754                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6755                 off this typed dispatch, so a derive regression must \
6756                 surface here rather than at the fixture-refusal site)"
6757            );
6758        }
6759    }
6760
6761    #[test]
6762    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6763        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6764        // fixture-shape partition against the pre-lift
6765        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6766        // pattern-match every test-fixture builder site previously
6767        // coupled to inline. Asserts the two projections agree byte-for-
6768        // byte on every arm of the enum, so a future derive regression
6769        // that flipped either predicate's arm-set would surface here at
6770        // caixa-core test time rather than at the three fixture-builder
6771        // sites (`supervisor::tests::round_trip_all_strategies`,
6772        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6773        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6774        // far from the derive site. Same peer-shape byte-identity pin
6775        // every sibling `IsVariant`-derive-routed convergence carries on
6776        // the substrate's closed-set typed-enum surface (peer of
6777        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6778        // on the M2 OTP-appup axis).
6779        for &strat in RestartStrategy::ALL {
6780            let via_predicate = strat.is_simple_one_for_one();
6781            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6782            assert_eq!(
6783                via_predicate, via_matches,
6784                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6785                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6786                 the pre-lift open-coded pattern and the \
6787                 IsVariant-derived predicate are the same axis, \
6788                 one typed dispatch"
6789            );
6790        }
6791    }
6792
6793    #[test]
6794    fn duration_codec_round_trip_canonical_units() {
6795        // Note the canonical-form rule: durations serialize to the
6796        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6797        // "60s" — but the round-trip preserves the underlying Duration.
6798        let cases = [
6799            ("30s", Duration::from_secs(30)),
6800            ("5m", Duration::from_secs(300)),
6801            ("1h", Duration::from_secs(3600)),
6802            ("500ms", Duration::from_millis(500)),
6803        ];
6804        for (lit, dur) in cases {
6805            let s = SupervisorSpec {
6806                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6807                restart_window: Some(dur),
6808                ..SupervisorSpec::default()
6809            };
6810            let json = serde_json::to_string(&s).unwrap();
6811            assert!(
6812                json.contains(&format!("\"{lit}\"")),
6813                "expected \"{lit}\" in {json}"
6814            );
6815            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6816            assert_eq!(back.restart_window, Some(dur));
6817        }
6818    }
6819
6820    #[test]
6821    fn duration_canonicalizes_to_largest_unit() {
6822        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6823        // typed Duration still equals 60s on the way back.
6824        let s = SupervisorSpec {
6825            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6826            restart_window: Some(Duration::from_secs(60)),
6827            ..SupervisorSpec::default()
6828        };
6829        let json = serde_json::to_string(&s).unwrap();
6830        assert!(json.contains("\"1m\""), "{json}");
6831        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6832        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6833    }
6834
6835    #[test]
6836    fn three_child_one_for_one_validates() {
6837        let s = SupervisorSpec {
6838            estrategia: RestartStrategy::OneForOne,
6839            max_restarts: 5,
6840            restart_window: Some(Duration::from_secs(60)),
6841            children: vec![
6842                child("worker", "^0.1", RestartPolicy::Permanent),
6843                child("cache", "^0.1", RestartPolicy::Transient),
6844                child("scratch", "^0.1", RestartPolicy::Temporary),
6845            ],
6846        };
6847        s.validate().unwrap();
6848    }
6849
6850    #[test]
6851    fn json_uses_pascal_case_for_strategy_and_policy() {
6852        // Variant names are PascalCase by default in serde, matching
6853        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6854        let c = child("w", "^0.1", RestartPolicy::Permanent);
6855        let json = serde_json::to_string(&c).unwrap();
6856        assert!(json.contains("\"Permanent\""));
6857        assert!(!json.contains("\"permanent\""));
6858
6859        let s = SupervisorSpec {
6860            estrategia: RestartStrategy::OneForOne,
6861            children: vec![c],
6862            ..SupervisorSpec::default()
6863        };
6864        let json = serde_json::to_string(&s).unwrap();
6865        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6866    }
6867
6868    // ── shared duration codec: integer-magnitude canonical-form gate ──
6869    //
6870    // The gate lifts the discipline `crate::limits::parse_duration`
6871    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6872    // the shared codec backing the remaining three typed-duration
6873    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6874    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6875    // emits is a non-negative integer with no decimal point and no
6876    // leading sign, so the codec's accepted set must match for
6877    // serialize/deserialize to round-trip without canonical-form
6878    // drift.
6879
6880    #[test]
6881    fn parse_accepts_integer_canonical_units() {
6882        // Pin the happy-path: every canonical author shape `render`
6883        // ever emits parses to the same `Duration` value, so the
6884        // codec's accepted set is at least a superset of its emitted
6885        // set on the canonical-unit axis.
6886        for (lit, dur) in [
6887            ("30s", Duration::from_secs(30)),
6888            ("500ms", Duration::from_millis(500)),
6889            ("2m", Duration::from_secs(120)),
6890            ("1h", Duration::from_secs(3600)),
6891            ("0s", Duration::ZERO),
6892        ] {
6893            assert_eq!(
6894                duration_codec::parse(lit).unwrap(),
6895                dur,
6896                "parse({lit:?}) should be {dur:?}"
6897            );
6898        }
6899    }
6900
6901    #[test]
6902    fn parse_accepts_bare_integer_as_seconds() {
6903        // The `"s" | ""` arm: a bare integer with no unit is read as
6904        // seconds. Pin this so the unit-empty form keeps parsing (it
6905        // renders to `"<n>s"` on serialize — that's a unit-choice
6906        // drift the integer-magnitude gate does NOT close, matching
6907        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6908        // the peer `:limits :memory` codec).
6909        assert_eq!(
6910            duration_codec::parse("30").unwrap(),
6911            Duration::from_secs(30)
6912        );
6913    }
6914
6915    #[test]
6916    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6917        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6918        // on first serialize — DRIFT. The integer-magnitude gate names
6919        // the offending `"1.5"` verbatim and points at the canonical
6920        // remediation `"1500ms"`.
6921        let err = duration_codec::parse("1.5s").unwrap_err();
6922        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6923        assert!(
6924            err.contains("not a non-negative integer"),
6925            "missing canonical-form reason in {err:?}"
6926        );
6927        assert!(
6928            err.contains("\"1500ms\""),
6929            "missing canonical-form remediation in {err:?}"
6930        );
6931    }
6932
6933    #[test]
6934    fn parse_rejects_decimal_shaped_integer_seconds() {
6935        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6936        // `1s` exactly, so the round-trip looks correct — but the
6937        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6938        // decimal-shape-with-integer-value form so author intent is
6939        // never silently rewritten.
6940        let err = duration_codec::parse("1.0s").unwrap_err();
6941        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6942        assert!(
6943            err.contains("not a non-negative integer"),
6944            "missing canonical-form reason in {err:?}"
6945        );
6946    }
6947
6948    #[test]
6949    fn parse_rejects_half_unit_minute() {
6950        // `"0.5m"` is the unit-fraction footgun — author writes a
6951        // human-readable half-minute, serde silently rewrites to
6952        // `"30s"` on next emit. The gate names the offending
6953        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6954        // form.
6955        let err = duration_codec::parse("0.5m").unwrap_err();
6956        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6957        assert!(
6958            err.contains("\"30s\""),
6959            "missing canonical-form remediation in {err:?}"
6960        );
6961    }
6962
6963    #[test]
6964    fn parse_rejects_leading_plus_sign() {
6965        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6966        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6967        // cleanly to 30s and round-tripped to `"30s"` on next emit
6968        // (DRIFT). The digit-only gate closes the leading-sign class
6969        // first; the diagnostic names `"+30"` verbatim.
6970        let err = duration_codec::parse("+30s").unwrap_err();
6971        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6972        assert!(
6973            err.contains("not a non-negative integer"),
6974            "missing canonical-form reason in {err:?}"
6975        );
6976    }
6977
6978    #[test]
6979    fn parse_rejects_leading_minus_sign() {
6980        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6981        // rejected with `"negative duration in \"-30s\""`. Under the
6982        // integer-magnitude gate the diagnostic is unified — `-30` is
6983        // non-digit-only, f64-numeric, and surfaces with the canonical-
6984        // form reason (no leading `+` / `-` sign) naming the offending
6985        // `"-30"` verbatim. Same diagnostic shape as every other
6986        // rejected non-integer magnitude.
6987        let err = duration_codec::parse("-30s").unwrap_err();
6988        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6989        assert!(
6990            err.contains("not a non-negative integer"),
6991            "missing canonical-form reason in {err:?}"
6992        );
6993    }
6994
6995    #[test]
6996    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6997        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6998        // through to the narrower "bad duration magnitude" arm — the
6999        // canonical-form diagnostic is reserved for the parser-shape
7000        // footgun case, not the "not a number at all" case. Same
7001        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7002        // the peer `:limits :memory` codec.
7003        let err = duration_codec::parse("--1s").unwrap_err();
7004        assert!(
7005            err.contains("bad duration magnitude"),
7006            "expected bad-magnitude wording in {err:?}"
7007        );
7008    }
7009
7010    #[test]
7011    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7012        // The accepted set is now closed under `u64`-exact integer
7013        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7014        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7015        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7016        // possible. Pin the integer-exact arms across the four unit
7017        // suffixes so a future refactor that reaches back for f64
7018        // (`from_secs_f64`, `mul_f64`) surfaces here.
7019        assert_eq!(
7020            duration_codec::parse("3600s").unwrap(),
7021            Duration::from_secs(3600)
7022        );
7023        assert_eq!(
7024            duration_codec::parse("60m").unwrap(),
7025            Duration::from_secs(3600)
7026        );
7027        assert_eq!(
7028            duration_codec::parse("1h").unwrap(),
7029            Duration::from_secs(3600)
7030        );
7031        assert_eq!(
7032            duration_codec::parse("999ms").unwrap(),
7033            Duration::from_millis(999)
7034        );
7035    }
7036
7037    #[test]
7038    fn restart_window_serde_rejects_fractional_seconds() {
7039        // The shared codec backs `SupervisorSpec::restart_window`
7040        // (`with = "duration_codec"`) — so the gate applies on serde
7041        // deserialize for the typed Supervisor slot. A
7042        // `{"restartWindow":"1.5s"}` payload that previously round-
7043        // tripped to a different canonical string on next serialize
7044        // is now refused at deserialize with the integer-magnitude
7045        // diagnostic.
7046        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7047            "restartWindow":"1.5s",
7048            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7049        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7050        let msg = err.to_string();
7051        assert!(
7052            msg.contains("not a non-negative integer"),
7053            "expected integer-magnitude diagnostic in {msg:?}"
7054        );
7055        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7056    }
7057
7058    #[test]
7059    fn restart_window_serde_rejects_leading_plus() {
7060        // The `u64::from_str` leading-`+` permissiveness gap that
7061        // motivated the digit-only gate (the `f64`-side accepted
7062        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7063        // is now closed on the shared codec — surfaces as a structured
7064        // diagnostic at the serde layer for every typed-duration slot.
7065        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7066            "restartWindow":"+30s",
7067            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7068        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7069        let msg = err.to_string();
7070        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7071        assert!(
7072            msg.contains("not a non-negative integer"),
7073            "missing canonical-form reason in {msg:?}"
7074        );
7075    }
7076
7077    #[test]
7078    fn parse_rejects_leading_zero_magnitude() {
7079        // `"030s"` is digit-only, so the existing non-digit-only / sign
7080        // / fractional arm doesn't catch it — `u64::from_str("030")`
7081        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7082        // `Duration::from_secs(30)` and round-tripped through `render`
7083        // to `"30s"` — a *different* canonical string on the next emit,
7084        // breaking the THEORY.md Part V render-determinism contract
7085        // exactly the way `"+30s"` did before the leading-`+` arm
7086        // landed. Peer with the `rate_limit_codec` leading-zero arm
7087        // (4f46830) on the same canonical-form-drift axis.
7088        let err = duration_codec::parse("030s").unwrap_err();
7089        assert!(
7090            err.contains("non-canonical leading zero"),
7091            "expected leading-zero diagnostic in {err:?}"
7092        );
7093        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7094        assert!(
7095            err.contains("\"30s\""),
7096            "missing canonical-form remediation in {err:?}"
7097        );
7098        assert!(
7099            err.contains("THEORY.md"),
7100            "missing render-determinism citation in {err:?}"
7101        );
7102    }
7103
7104    #[test]
7105    fn parse_rejects_multi_digit_zero_magnitude() {
7106        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7107        // digit-only, parse losslessly to `Duration::ZERO`, but render
7108        // back to `"0s"` (the single-byte canonical form) on the next
7109        // emit. The leading-zero arm refuses the drift class at the
7110        // codec layer; the semantic-zero gate downstream
7111        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7112        // the single-byte canonical form `"0s"` separately on the
7113        // typed-validate layer.
7114        let err = duration_codec::parse("00s").unwrap_err();
7115        assert!(
7116            err.contains("non-canonical leading zero"),
7117            "expected leading-zero diagnostic in {err:?}"
7118        );
7119        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7120    }
7121
7122    #[test]
7123    fn parse_rejects_leading_zero_per_hour_window() {
7124        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7125        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7126        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7127        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7128        // `h` / bare-integer-as-seconds) inherits the same gate.
7129        let err = duration_codec::parse("01h").unwrap_err();
7130        assert!(
7131            err.contains("non-canonical leading zero"),
7132            "expected leading-zero diagnostic in {err:?}"
7133        );
7134        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7135    }
7136
7137    #[test]
7138    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7139        // The `parse_accepts_bare_integer_as_seconds` happy-path
7140        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7141        // multi-byte starts-with-`0`, parses losslessly to
7142        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7143        // bare-integer surface accepts permissive unit-empty
7144        // shorthand but still must reject leading-zero padding.
7145        let err = duration_codec::parse("030").unwrap_err();
7146        assert!(
7147            err.contains("non-canonical leading zero"),
7148            "expected leading-zero diagnostic in {err:?}"
7149        );
7150        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7151    }
7152
7153    #[test]
7154    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7155        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7156        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7157        // each round-trips losslessly through `render`
7158        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7159        // accepts them. The downstream semantic-zero gates
7160        // (`SupervisorError::ZeroRestartWindow`,
7161        // `AplicacaoError::PolicyTimeoutZero`,
7162        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7163        // zero-magnitude authoring at the typed-validate layer above,
7164        // peer with the `rate_limit_codec` codec-layer / typed-
7165        // validate-layer partition for `"0/s"`.
7166        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7167        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7168        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7169    }
7170
7171    #[test]
7172    fn parse_accepts_canonical_magnitude_with_leading_one() {
7173        // The complementary boundary: a future tightening cannot
7174        // drift into rejecting valid canonical magnitudes that
7175        // happen to start with `1` (or any digit `[1-9]`). Pin
7176        // every canonical-unit suffix so the leading-zero arm
7177        // remains strictly narrower than the digit-only arm.
7178        assert_eq!(
7179            duration_codec::parse("100ms").unwrap(),
7180            Duration::from_millis(100)
7181        );
7182        assert_eq!(
7183            duration_codec::parse("100s").unwrap(),
7184            Duration::from_secs(100)
7185        );
7186        assert_eq!(
7187            duration_codec::parse("10m").unwrap(),
7188            Duration::from_secs(600)
7189        );
7190        assert_eq!(
7191            duration_codec::parse("10h").unwrap(),
7192            Duration::from_secs(36_000)
7193        );
7194    }
7195
7196    #[test]
7197    fn restart_window_serde_rejects_leading_zero() {
7198        // The shared codec backs `SupervisorSpec::restart_window`
7199        // (`with = "duration_codec"`) — so the leading-zero arm
7200        // applies on serde deserialize for the typed Supervisor slot.
7201        // A `{"restartWindow":"030s"}` payload that previously round-
7202        // tripped to a different canonical string on next serialize
7203        // is now refused at deserialize with the leading-zero
7204        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7205        // / `restart_window_serde_rejects_fractional_seconds` on the
7206        // same canonical-form-drift axis.
7207        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7208            "restartWindow":"030s",
7209            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7210        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7211        let msg = err.to_string();
7212        assert!(
7213            msg.contains("non-canonical leading zero"),
7214            "expected leading-zero diagnostic in {msg:?}"
7215        );
7216        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7217    }
7218
7219    #[test]
7220    fn parse_rejects_leading_whitespace() {
7221        // `" 30s"` — the canonical paste-from-aligned-doc /
7222        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7223        // gate the top-level `s.trim()` at parse entry silently ate
7224        // the leading space and parsed the value to
7225        // `Duration::from_secs(30)`, which then round-tripped through
7226        // `render` to `"30s"` (a *different* canonical string on the
7227        // next emit) — the exact canonical-form-drift class the
7228        // leading-`+` / leading-zero arms already close, extended
7229        // to the whitespace-byte class. Peer with the sibling
7230        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7231        // the M3 `:politicas` axis.
7232        let err = duration_codec::parse(" 30s").unwrap_err();
7233        assert!(
7234            err.contains("contains whitespace byte"),
7235            "expected whitespace diagnostic in {err:?}"
7236        );
7237        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7238        assert!(
7239            err.contains("THEORY.md"),
7240            "missing render-determinism contract citation in {err:?}"
7241        );
7242    }
7243
7244    #[test]
7245    fn parse_rejects_trailing_whitespace() {
7246        // `"30s "` — the canonical shell-history / trailing-space
7247        // paste footgun. Before this gate the top-level `s.trim()`
7248        // silently ate the trailing space and parsed to
7249        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7250        // next emit — same canonical-form drift as the leading-space
7251        // sibling, closed on the same whitespace-byte arm.
7252        let err = duration_codec::parse("30s ").unwrap_err();
7253        assert!(
7254            err.contains("contains whitespace byte"),
7255            "expected whitespace diagnostic in {err:?}"
7256        );
7257        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7258    }
7259
7260    #[test]
7261    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7262        // `"30 s"` — the canonical typographically-spaced author
7263        // shape (the same idiom every prose reference to a duration
7264        // renders as, mistakenly retained when the value is pasted
7265        // into a codec-shaped slot). Before this gate the per-part
7266        // `num_part.trim()` / `unit.trim()` calls silently ate the
7267        // whitespace between the magnitude and the unit and parsed
7268        // the value to `Duration::from_secs(30)`, round-tripping to
7269        // `"30s"` — the codec's *internal* whitespace-tolerance
7270        // vector, orthogonal to the leading / trailing surface but
7271        // the same canonical-form-drift class. Pins the arm as
7272        // strictly stronger than the pre-existing top-level
7273        // `s.trim()` behavior: it fires on whitespace anywhere in
7274        // the value, not just at the string boundary.
7275        let err = duration_codec::parse("30 s").unwrap_err();
7276        assert!(
7277            err.contains("contains whitespace byte"),
7278            "expected whitespace diagnostic in {err:?}"
7279        );
7280        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7281    }
7282
7283    #[test]
7284    fn parse_rejects_tab_byte() {
7285        // `"\t30s"` — the canonical paste-from-indented-doc /
7286        // paste-from-YAML-block-scalar footgun where a tab byte leads
7287        // the magnitude. Pins that the gate covers tab (`0x09`) as
7288        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7289        // members and both would be silently swallowed by `s.trim()`
7290        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7291        // space alone to the full ASCII-whitespace set (space `0x20`,
7292        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7293        // the tab arm as a representative of the non-space members.
7294        let err = duration_codec::parse("\t30s").unwrap_err();
7295        assert!(
7296            err.contains("contains whitespace byte"),
7297            "expected whitespace diagnostic in {err:?}"
7298        );
7299        assert!(
7300            err.contains("0x09"),
7301            "missing offending tab byte in {err:?}"
7302        );
7303    }
7304
7305    #[test]
7306    fn restart_window_serde_rejects_whitespace() {
7307        // The shared codec backs `SupervisorSpec::restart_window`
7308        // (`with = "duration_codec"`) — so the whitespace arm
7309        // applies on serde deserialize for the typed Supervisor slot.
7310        // A `{"restartWindow":" 30s"}` payload that previously round-
7311        // tripped to a different canonical string on next serialize
7312        // is now refused at deserialize with the whitespace-byte
7313        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7314        // / `restart_window_serde_rejects_leading_plus` /
7315        // `restart_window_serde_rejects_fractional_seconds` on the
7316        // same canonical-form-drift axis.
7317        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7318            "restartWindow":" 30s",
7319            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7320        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7321        let msg = err.to_string();
7322        assert!(
7323            msg.contains("contains whitespace byte"),
7324            "expected whitespace diagnostic in {msg:?}"
7325        );
7326        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7327    }
7328
7329    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7330    //
7331    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7332    // duration codec — closes the strictly-complementary class the
7333    // byte-scan cannot see, through the lifted
7334    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7335    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7336    // and `:politicas :circuit-breaker :window` simultaneously via
7337    // this shared codec.
7338
7339    #[test]
7340    fn duration_codec_parse_rejects_leading_nbsp() {
7341        // NBSP prefix — the strictly-complementary drift class the
7342        // ASCII byte-scan cannot see. `str::trim` strips it silently
7343        // and the value drifts to `"30s"` on next serialize.
7344        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7345        assert!(
7346            err.contains("non-ASCII Unicode whitespace character"),
7347            "expected non-ASCII whitespace diagnostic in {err:?}"
7348        );
7349        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7350    }
7351
7352    #[test]
7353    fn duration_codec_parse_rejects_trailing_line_separator() {
7354        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7355        // footgun.
7356        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7357        assert!(
7358            err.contains("non-ASCII Unicode whitespace character"),
7359            "expected non-ASCII whitespace diagnostic in {err:?}"
7360        );
7361        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7362    }
7363
7364    #[test]
7365    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7366        // Positive-control pin: every ASCII-only canonical form the
7367        // renderer emits stays accepted through the new arm.
7368        assert_eq!(
7369            duration_codec::parse("30s").unwrap(),
7370            Duration::from_secs(30)
7371        );
7372        assert_eq!(
7373            duration_codec::parse("500ms").unwrap(),
7374            Duration::from_millis(500)
7375        );
7376        assert_eq!(
7377            duration_codec::parse("1h").unwrap(),
7378            Duration::from_secs(3600)
7379        );
7380    }
7381
7382    #[test]
7383    fn restart_window_serde_rejects_non_ascii_whitespace() {
7384        // The shared codec backs `SupervisorSpec::restart_window` — so
7385        // the new non-ASCII Unicode whitespace arm applies on serde
7386        // deserialize for the typed Supervisor slot. A
7387        // `{"restartWindow":" 30s"}` payload that previously
7388        // survived the ASCII byte-scan (only ASCII whitespace was
7389        // refused) is now refused at deserialize with the
7390        // non-ASCII-whitespace-and-codepoint diagnostic.
7391        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7392            \"restartWindow\":\"\u{00A0}30s\",\
7393            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7394        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7395        let msg = err.to_string();
7396        assert!(
7397            msg.contains("non-ASCII Unicode whitespace character"),
7398            "expected non-ASCII whitespace diagnostic in {msg:?}"
7399        );
7400        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7401    }
7402
7403    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7404
7405    #[test]
7406    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7407        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7408        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7409        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7410        // name the exact camelCase JSON keys the
7411        // `#[serde(rename_all = "camelCase")]` attribute on
7412        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7413        // field carries `Some(_)` / non-empty) and pin that each canonical
7414        // byte-sequence appears verbatim in the JSON — a future accidental
7415        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7416        // name flip at the derive attribute (any of which would silently
7417        // break every downstream JSON consumer that reaches for one of the
7418        // four consts via `Value::get(...)`) surfaces here as a build-time
7419        // test failure at `supervisor.rs`, not as an apply-time
7420        // `.get(<stale-canonical-const>)` returning `None` far from the
7421        // derive-attr drift's commit. Peer with the sibling
7422        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7423        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7424        // M2 typed-slot family established, extended here to close the
7425        // top-level Supervisor axis.
7426        let spec = SupervisorSpec {
7427            estrategia: RestartStrategy::OneForOne,
7428            max_restarts: 5,
7429            restart_window: Some(Duration::from_secs(60)),
7430            children: vec![ChildSpec {
7431                caixa: "w".into(),
7432                versao: "^0.1".into(),
7433                restart: RestartPolicy::Permanent,
7434            }],
7435        };
7436        let json = serde_json::to_string(&spec).unwrap();
7437        for key in [
7438            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7439            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7440            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7441            crate::render::SUPERVISOR_KEY_CHILDREN,
7442        ] {
7443            let quoted = format!("\"{key}\"");
7444            assert!(
7445                json.contains(&quoted),
7446                "serialized SupervisorSpec must carry the lifted \
7447                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7448                 the JSON emission (got: {json})",
7449            );
7450        }
7451    }
7452
7453    #[test]
7454    fn supervisor_key_consts_are_pairwise_distinct() {
7455        // Cross-axis drift-detection pin: a future collapse of two
7456        // canonical top-level byte-strings onto the same value (e.g. an
7457        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7458        // also read `"estrategia"`) would silently reroute every
7459        // downstream probe on one axis onto the sibling axis's overlay
7460        // entry and pass every propagation-probe test that expected only
7461        // the stale axis's value. Peer of the sibling four-way distinct
7462        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7463        let all = [
7464            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7465            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7466            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7467            crate::render::SUPERVISOR_KEY_CHILDREN,
7468        ];
7469        for (i, a) in all.iter().enumerate() {
7470            for b in all.iter().skip(i + 1) {
7471                assert_ne!(
7472                    a, b,
7473                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7474                     canonical byte-sequences — got `{a}` == `{b}`",
7475                );
7476            }
7477        }
7478    }
7479
7480    #[test]
7481    fn supervisor_key_consts_are_lower_camel_case_shape() {
7482        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7483        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7484        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7485        // capital, no whitespace / dots) — the canonical shape the
7486        // `#[serde(rename_all = "camelCase")]` derive produces on
7487        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7488        // at the derive surfaces both here (this test fails on the
7489        // stale-constant shape) and at
7490        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7491        // (that test fails on the mismatch between const and derive).
7492        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7493        // (d8b8b4f) on the sibling M2 `:limits` axis.
7494        for key in [
7495            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7496            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7497            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7498            crate::render::SUPERVISOR_KEY_CHILDREN,
7499        ] {
7500            assert!(
7501                !key.is_empty(),
7502                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7503            );
7504            let first = key.chars().next().unwrap();
7505            assert!(
7506                first.is_ascii_lowercase(),
7507                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7508                 (got {key:?}, leads with {first:?})",
7509            );
7510            assert!(
7511                key.chars().all(|c| c.is_ascii_alphanumeric()),
7512                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7513                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7514            );
7515        }
7516    }
7517
7518    #[test]
7519    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7520        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7521        // (camelCase JSON keys, no leading colon) must never collide
7522        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7523        // consts (kebab-case author-facing labels with leading colon)
7524        // that sit next to them at `caixa_core::render`. Both families
7525        // cover the same four typed Supervisor slots on two distinct
7526        // axes (author-side kebab vs renderer-side camelCase);
7527        // collapsing either family onto the other's byte-shape would
7528        // silently reroute the render-side probe onto the author-facing
7529        // surface, or vice versa. Peer of the byte-distinctness
7530        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7531        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7532        let pairs = [
7533            (
7534                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7535                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7536            ),
7537            (
7538                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7539                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7540            ),
7541            (
7542                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7543                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7544            ),
7545            (
7546                crate::render::SUPERVISOR_KEY_CHILDREN,
7547                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7548            ),
7549        ];
7550        for (json_key, author_key) in pairs {
7551            assert_ne!(
7552                json_key, author_key,
7553                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7554                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7555                 got JSON `{json_key}` == author `{author_key}`",
7556            );
7557        }
7558    }
7559
7560    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7561
7562    #[test]
7563    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7564        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7565        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7566        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7567        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7568        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7569        // pin that each canonical byte-sequence appears verbatim in the
7570        // JSON — a future accidental `rename_all = "snake_case"` /
7571        // `"kebab-case"` / verbatim-field-name flip at the derive
7572        // attribute (any of which would silently break every downstream
7573        // JSON consumer that reaches for one of the three consts via
7574        // `Value::get(...)`) surfaces here as a build-time test failure at
7575        // `supervisor.rs`, not as an apply-time
7576        // `.get(<stale-canonical-const>)` returning `None` far from the
7577        // derive-attr drift's commit. Peer with the enclosing
7578        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7579        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7580        // discipline the SupervisorSpec top-level lift established,
7581        // extended here to the sibling per-`:children` entry `ChildSpec`
7582        // derive so the last M2 typed-struct sub-block
7583        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7584        // surface without a lifted serde-key peer joins the substrate's
7585        // "one canonical byte-string per typed serialized-key axis"
7586        // discipline.
7587        let c = ChildSpec {
7588            caixa: "worker".into(),
7589            versao: "^0.1".into(),
7590            restart: RestartPolicy::Permanent,
7591        };
7592        let json = serde_json::to_string(&c).unwrap();
7593        for key in [
7594            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7595            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7596            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7597        ] {
7598            let quoted = format!("\"{key}\"");
7599            assert!(
7600                json.contains(&quoted),
7601                "serialized ChildSpec must carry the lifted \
7602                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7603                 in the JSON emission (got: {json})",
7604            );
7605        }
7606    }
7607
7608    #[test]
7609    fn supervisor_child_key_consts_are_pairwise_distinct() {
7610        // Cross-axis drift-detection pin: a future collapse of two
7611        // canonical `ChildSpec` per-entry byte-strings onto the same
7612        // value (e.g. an accidental copy-paste flip of
7613        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7614        // silently reroute every downstream probe on one axis onto the
7615        // sibling axis's overlay entry and pass every propagation-probe
7616        // test that expected only the stale axis's value. Peer of the
7617        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7618        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7619        // pair (ce80ca0).
7620        let all = [
7621            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7622            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7623            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7624        ];
7625        for (i, a) in all.iter().enumerate() {
7626            for b in all.iter().skip(i + 1) {
7627                assert_ne!(
7628                    a, b,
7629                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7630                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7631                );
7632            }
7633        }
7634    }
7635
7636    #[test]
7637    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7638        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7639        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7640        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7641        // capital, no whitespace / dots) — the canonical shape the
7642        // `#[serde(rename_all = "camelCase")]` derive produces on
7643        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7644        // derive surfaces both here (this test fails on the
7645        // stale-constant shape) and at
7646        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7647        // (that test fails on the mismatch between const and derive).
7648        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7649        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7650        for key in [
7651            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7652            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7653            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7654        ] {
7655            assert!(
7656                !key.is_empty(),
7657                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7658            );
7659            let first = key.chars().next().unwrap();
7660            assert!(
7661                first.is_ascii_lowercase(),
7662                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7663                 byte (got {key:?}, leads with {first:?})",
7664            );
7665            assert!(
7666                key.chars().all(|c| c.is_ascii_alphanumeric()),
7667                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7668                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7669            );
7670        }
7671    }
7672
7673    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7674
7675    #[test]
7676    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7677        // The fail-before-pass-after pin: pre-lift there was no
7678        // single-source binding between the [`RestartStrategy`] variant
7679        // name the un-`rename`d `Serialize` derive emits under
7680        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7681        // every downstream cluster-side dispatcher (the future
7682        // wasm-operator's per-supervisor sibling-restart branch, the
7683        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7684        // admission-time enum-arm bind, the `caixa-operator`'s
7685        // hierarchical reconciliation scheduler's per-strategy fan-out)
7686        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7687        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7688        // override, or a variant rename in the source — would silently
7689        // rebrand the emitted scalar under one spelling while every
7690        // downstream dispatcher still probed the other, with the failure
7691        // surfacing at the operator's reconcile posture (subtrees coming
7692        // up under the `default()` `OneForOne` arm rather than the typed
7693        // slot's declared strategy — a bad child would then only take
7694        // itself down instead of the sibling set the author intended, so
7695        // shared-state children fall out of sync) far from the source
7696        // rebrand commit and with no field naming the drift. Pinning the
7697        // two paths (the `Serialize` derive's serialized string AND the
7698        // [`RestartStrategy::as_str`] helper) to the same four lifted
7699        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7700        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7701        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7702        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7703        // byte-strings makes any future drift on either endpoint fail
7704        // here at caixa-core build time. Peer of the M3
7705        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7706        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7707        // three-path-convergence discipline, extended to close the
7708        // OTP-shaped per-supervisor sibling-restart axis.
7709        for (variant, expected) in [
7710            (
7711                RestartStrategy::OneForOne,
7712                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7713            ),
7714            (
7715                RestartStrategy::OneForAll,
7716                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7717            ),
7718            (
7719                RestartStrategy::RestForOne,
7720                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7721            ),
7722            (
7723                RestartStrategy::SimpleOneForOne,
7724                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7725            ),
7726        ] {
7727            let json = serde_json::to_string(&variant).unwrap();
7728            assert_eq!(
7729                json,
7730                format!("\"{expected}\""),
7731                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7732            );
7733            assert_eq!(
7734                variant.as_str(),
7735                expected,
7736                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7737                 SUPERVISOR_ESTRATEGIA_* constant"
7738            );
7739        }
7740    }
7741
7742    #[test]
7743    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7744        // Cross-arm drift-detection pin: a future collapse of two
7745        // canonical variant byte-strings onto the same value (e.g. an
7746        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7747        // to also read `"OneForOne"`) would silently reroute every
7748        // downstream operator's per-strategy dispatch onto the sibling
7749        // arm's reconcile branch and pass every propagation-probe test
7750        // that expected only the stale arm's value — the mis-strategied
7751        // subtree would come up with the wrong sibling-restart posture
7752        // on every subsequent failure. Peer of the sibling four-way
7753        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7754        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7755        let all = [
7756            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7757            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7758            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7759            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7760        ];
7761        for (i, a) in all.iter().enumerate() {
7762            for (j, b) in all.iter().enumerate() {
7763                if i != j {
7764                    assert_ne!(
7765                        a, b,
7766                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7767                         — got duplicate {a:?} at indices {i} and {j}",
7768                    );
7769                }
7770            }
7771        }
7772    }
7773
7774    #[test]
7775    fn restart_strategy_display_routes_through_as_str_helper() {
7776        // The fail-before-pass-after pin on the first half of the
7777        // three-path convergence: pre-convergence the sibling
7778        // OTP-shape typed enum [`RestartStrategy`] carried a
7779        // [`std::fmt::Display`] surface via its
7780        // `#[discriminant(also_display)]` gen-platform derive route,
7781        // which arrived kebab-case as `"one-for-one"` /
7782        // `"one-for-all"` / `"rest-for-one"` /
7783        // `"simple-one-for-one"` while the wire format ran as
7784        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7785        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7786        // Every consumer reaching for a strategy byte-string past the
7787        // wire format had to pick between three paths
7788        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7789        // serialized string, or `format!("{v}")` on the
7790        // discriminant-Display route), any two of which a future
7791        // variant rename or `#[serde(rename_all = "kebab-case")]`
7792        // attribute would silently desynchronize. Wiring
7793        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7794        // closes the third path: every `format!("{v}")` call reaches
7795        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7796        // const the wire format and the [`RestartStrategy::as_str`]
7797        // helper already route through, so a future variant rename
7798        // lands at exactly one place. Pin the routing here so a future
7799        // `impl std::fmt::Display for RestartStrategy`
7800        // reimplementation that hand-rolls the arms instead of
7801        // delegating to [`RestartStrategy::as_str`] fails at
7802        // caixa-core build time. Peer of the M3
7803        // `placement_strategy_display_routes_through_as_str_helper`
7804        // (cc8f749) which the M3 axis converged first.
7805        for &variant in RestartStrategy::ALL {
7806            assert_eq!(
7807                variant.to_string(),
7808                variant.as_str(),
7809                "RestartStrategy::{variant:?} Display must route through \
7810                 RestartStrategy::as_str (single source of truth: the lifted \
7811                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7812            );
7813        }
7814    }
7815
7816    #[test]
7817    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7818        // The fail-before-pass-after pin on the second half of the
7819        // three-path convergence: `Display` (user-facing text) agrees
7820        // byte-for-byte with the `Serialize` derive's wire format
7821        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7822        // scalar) on every variant. Pre-convergence the two paths
7823        // were structurally independent — a future
7824        // `#[serde(rename_all = "kebab-case")]` attribute on the
7825        // enum would silently rebrand the emitted wire scalar
7826        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7827        // `simple-one-for-one`) while every consumer that
7828        // pretty-prints the strategy (the future wasm-operator's
7829        // per-supervisor sibling-restart-strategy diagnostic line,
7830        // the future `feira app graph` per-supervisor strategy line,
7831        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7832        // materializer's admission-webhook rejection body) would
7833        // still emit the PascalCase form the `as_str` / `Display`
7834        // route returns, with the mismatch surfacing at consumer
7835        // parse time / operator dispatch time far from the source
7836        // rebrand commit. Pin the two paths byte-for-byte here so any
7837        // future serde-attribute or variant-rename drift is a
7838        // caixa-core-build-time test failure at this call, not a
7839        // silent per-consumer dispatch miss. Peer of the M3
7840        // `placement_strategy_display_matches_serialized_wire_byte_string`
7841        // (cc8f749) which the M3 axis converged first.
7842        for &variant in RestartStrategy::ALL {
7843            let wire = serde_json::to_string(&variant).unwrap();
7844            let unquoted = wire
7845                .strip_prefix('"')
7846                .and_then(|s| s.strip_suffix('"'))
7847                .expect("serialized RestartStrategy is a JSON string");
7848            assert_eq!(
7849                variant.to_string(),
7850                unquoted,
7851                "RestartStrategy::{variant:?} Display byte-string must match the \
7852                 Serialize derive's wire byte-string (three-path convergence: \
7853                 Display + as_str + Serialize all resolve to the same \
7854                 SUPERVISOR_ESTRATEGIA_* const)"
7855            );
7856        }
7857    }
7858
7859    #[test]
7860    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7861        // Fail-before-pass-after byte-parity pin on the lifted
7862        // `impl AsRef<str> for RestartStrategy` — asserts the
7863        // standard-library trait impl and the substrate-primitive
7864        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7865        // to the same `&str` per instance across the four-arm
7866        // closed set, so any future silent detour that routes the
7867        // impl through a divergent projection (a per-arm inline
7868        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7869        // re-inlining that opens a compile-time link to the un-lifted
7870        // arm-literal, a swap onto the kebab-case
7871        // [`gen_platform::Discriminant`] catalog identity that would
7872        // collide the wire axis with the dispatcher-catalog axis) trips
7873        // at caixa-core test time under `PartialEq` rather than at a
7874        // downstream `impl AsRef<str>`-bound consumer's silent split.
7875        // Sweeps every one of the four arms
7876        // [`RestartStrategy::ALL`] carries so no arm's projection is
7877        // covered only by the sibling wire-format `Serialize` derive
7878        // path. Peer of the sibling
7879        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7880        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7881        // top-level `:versao` typed newtype — the two pins together
7882        // cover the substrate primitive's `AsRef<str>` projection axis
7883        // on the paired newtype + closed-set-typed-enum surface.
7884        for &variant in RestartStrategy::ALL {
7885            assert_eq!(
7886                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7887                variant.as_str(),
7888                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7889                 byte-equal RestartStrategy::as_str on the same instance \
7890                 — divergence signals a silent detour off the substrate-\
7891                 primitive accessor"
7892            );
7893        }
7894    }
7895
7896    #[test]
7897    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7898        // Fail-before-pass-after byte-parity pin on the three-path
7899        // convergence discipline the M2 sibling-restart primitive now
7900        // carries on the `&str`-projection axis:
7901        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7902        // lifted impl), `format!("{s}")` (the pre-existing
7903        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7904        // primitive `pub const fn` accessor both trait impls delegate
7905        // through) must resolve to the same byte-string on every
7906        // instance across the four-arm closed set. Refuses any future
7907        // divergence between the two trait impls (a stray
7908        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7909        // rather than delegating through the shared accessor; a
7910        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7911        // literal cascade) that would silently split the two
7912        // projection paths of the same closed-set typed enum. Mirrors
7913        // the sibling three-path-convergence discipline the peer
7914        // [`crate::CaixaVersion`] typed newtype carries on its
7915        // `AsRef<str>` / `Display` / `as_str` triple
7916        // (version.rs pin
7917        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7918        // 16d5c7e).
7919        for &variant in RestartStrategy::ALL {
7920            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7921            let via_display: String = format!("{variant}");
7922            let via_accessor: &str = variant.as_str();
7923            assert_eq!(via_as_ref, via_accessor);
7924            assert_eq!(via_display, via_accessor);
7925            assert_eq!(via_as_ref, via_display.as_str());
7926        }
7927    }
7928
7929    #[test]
7930    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7931        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7932        // exhaustive-iteration surface: every variant appears exactly
7933        // once, and the slice length matches the arm count of the
7934        // closed set. Every consumer that walks the accepted-strategy
7935        // set (a future `feira supervisor --estrategia …` CLI-side
7936        // arg-parse's "did you mean" hint, a future M4 admission-
7937        // webhook's rejection body naming the accepted-`:estrategia`
7938        // list, the [`RestartStrategy::from_wire`] reverse-projection
7939        // consumers that iterate the accept-set for diagnostic
7940        // rendering) reads through this slice, so a future arm addition
7941        // that grows the enum but forgets to grow [`Self::ALL`]
7942        // silently truncates every downstream consumer's accept-set at
7943        // the same pre-addition boundary — this pin fails at caixa-core
7944        // build time on the pairwise-distinct + arm-count invariants.
7945        //
7946        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7947        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7948        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7949        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7950        // pins on the peer closed-set typed-enum axes.
7951        let all: &[RestartStrategy] = RestartStrategy::ALL;
7952        assert_eq!(
7953            all.len(),
7954            4,
7955            "RestartStrategy::ALL must enumerate every variant of the \
7956             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7957             SimpleOneForOne); got {all:?}"
7958        );
7959        for (i, a) in all.iter().enumerate() {
7960            for (j, b) in all.iter().enumerate() {
7961                if i != j {
7962                    assert_ne!(
7963                        a, b,
7964                        "RestartStrategy::ALL must carry every variant exactly \
7965                         once — got duplicate {a:?} at indices {i} and {j}"
7966                    );
7967                }
7968            }
7969        }
7970        for variant in [
7971            RestartStrategy::OneForOne,
7972            RestartStrategy::OneForAll,
7973            RestartStrategy::RestForOne,
7974            RestartStrategy::SimpleOneForOne,
7975        ] {
7976            assert!(
7977                all.contains(&variant),
7978                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7979                 addition that grows the enum but forgets to grow the ALL slice \
7980                 silently truncates every downstream consumer's accept-set at \
7981                 the pre-addition boundary"
7982            );
7983        }
7984    }
7985
7986    #[test]
7987    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7988        // Fail-before-pass-after pin on the forward accept-set of the
7989        // [`RestartStrategy::from_wire`] reverse projection: every
7990        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7991        // constant the [`RestartStrategy::as_str`] emitter walks parses
7992        // back to its paired variant. Any future arm addition that
7993        // grows the emitter's `as_str` match but forgets to grow the
7994        // parser's `from_wire` match silently splits the two halves of
7995        // the round-trip — the wire byte-string one non-serde consumer
7996        // parses from the one the emitter wrote — with the failure
7997        // surfacing at parse time far from the rebrand commit. Pinning
7998        // the four-arm accept-set here catches the drift at caixa-core
7999        // build time.
8000        //
8001        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8002        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8003        // accept-set pins on the peer closed-set typed-enum `str → Self`
8004        // axes.
8005        for (wire, expected) in [
8006            (
8007                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8008                RestartStrategy::OneForOne,
8009            ),
8010            (
8011                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8012                RestartStrategy::OneForAll,
8013            ),
8014            (
8015                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8016                RestartStrategy::RestForOne,
8017            ),
8018            (
8019                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8020                RestartStrategy::SimpleOneForOne,
8021            ),
8022        ] {
8023            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8024                panic!(
8025                    "RestartStrategy::from_wire({wire:?}) must accept every \
8026                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8027                     lifted canonical byte-string that RestartStrategy::{expected:?} \
8028                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8029                )
8030            });
8031            assert_eq!(
8032                parsed, expected,
8033                "RestartStrategy::from_wire({wire:?}) must return \
8034                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8035            );
8036        }
8037    }
8038
8039    #[test]
8040    fn restart_strategy_from_wire_round_trips_through_as_str() {
8041        // Fail-before-pass-after pin on the closed round-trip between
8042        // the forward [`RestartStrategy::as_str`] emitter and the
8043        // reverse [`RestartStrategy::from_wire`] parser: for every
8044        // variant in [`RestartStrategy::ALL`], parsing the emitter's
8045        // output must return exactly the same variant. Any per-arm
8046        // divergence — a future arm added to `as_str` but not
8047        // `from_wire`, an accidental copy-paste flip in one but not
8048        // the other — silently splits the emit and parse halves and
8049        // the failure surfaces at consumer parse time far from the
8050        // drift site. The `ALL`-iterating shape means a future arm
8051        // addition picks up the coverage by construction.
8052        //
8053        // Peer of the sibling
8054        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8055        // (18c7342) round-trip pin on
8056        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8057        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8058        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8059        for &variant in RestartStrategy::ALL {
8060            let wire = variant.as_str();
8061            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8062                panic!(
8063                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8064                     must be Some({variant:?}) — the two halves of the round-trip \
8065                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8066                     got None on wire byte-string {wire:?}"
8067                )
8068            });
8069            assert_eq!(
8070                parsed, variant,
8071                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8072                 must round-trip to the same variant; got {parsed:?}"
8073            );
8074        }
8075    }
8076
8077    #[test]
8078    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8079        // Fail-before-pass-after pin on the closed-set refusal
8080        // discipline of [`RestartStrategy::from_wire`]: every
8081        // byte-string outside the four-arm accept-set returns `None`
8082        // rather than silently collapsing onto the [`Default`]
8083        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8084        // exercised here sweeps the load-bearing drift shapes: the
8085        // empty string (a stripped serde-attribute drift), all-
8086        // whitespace strings (the canonical text-editor accidental
8087        // padding shape), the kebab-case dispatcher-catalog identities
8088        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8089        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8090        // derived [`std::str::FromStr`] accept-set, which parses the
8091        // *other* axis of this enum's two-axis split and must not leak
8092        // into the `from_wire` PascalCase-wire accept-set), the
8093        // lowercased single-word forms (`"oneforone"`), the padded
8094        // canonical scalar (`" OneForOne "`), the trailing-newline
8095        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8096        // (`"AllForOne"` — the canonical typo direction).
8097        //
8098        // Peer of the sibling
8099        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8100        // (2aa6d23) +
8101        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8102        // (18c7342) refusal pins on the peer closed-set typed-enum
8103        // axes.
8104        for bad in [
8105            "",
8106            " ",
8107            "\n",
8108            "\t",
8109            "one-for-one",
8110            "one-for-all",
8111            "rest-for-one",
8112            "simple-one-for-one",
8113            "oneforone",
8114            "OneForOnes",
8115            "one_for_one",
8116            "one for one",
8117            "ONEFORONE",
8118            "OneForOne ",
8119            " OneForOne",
8120            " SimpleOneForOne ",
8121            "OneForOne\n",
8122            "restforone",
8123            "REST_FOR_ONE",
8124            "AllForOne",
8125            "Simple",
8126            "?",
8127        ] {
8128            assert!(
8129                RestartStrategy::from_wire(bad).is_none(),
8130                "RestartStrategy::from_wire({bad:?}) must return None — the \
8131                 parser's accept-set is exactly the four RestartStrategy::as_str \
8132                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8133                 and this byte-string is outside that closed set"
8134            );
8135        }
8136    }
8137
8138    #[test]
8139    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8140        // Fail-before-pass-after pin on the fourth path of the four-path
8141        // convergence: `from_wire` (the reverse projection) inverts the
8142        // `Serialize` derive's wire byte-string on every variant.
8143        // Together with the pre-existing three-path convergence
8144        // (`Display` + `as_str` + `Serialize` all resolve to the same
8145        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8146        // pinned by
8147        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8148        // this closes the round-trip: the wire byte-string the
8149        // `Serialize` derive emits parses back to the same variant
8150        // through `from_wire`, so any future serde-attribute or variant-
8151        // rename drift on the emit half now surfaces as a matched drift
8152        // on the parse half at caixa-core build time — the two halves
8153        // migrate as a unit through the lifted consts on any future
8154        // rename, and the round-trip cannot silently split.
8155        //
8156        // Peer of the sibling
8157        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8158        // (18c7342) wire-format pin on
8159        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8160        for &variant in RestartStrategy::ALL {
8161            let wire = serde_json::to_string(&variant).unwrap();
8162            let unquoted = wire
8163                .strip_prefix('"')
8164                .and_then(|s| s.strip_suffix('"'))
8165                .expect("serialized RestartStrategy is a JSON string");
8166            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8167                panic!(
8168                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8169                     Serialize derive's wire byte-string for \
8170                     RestartStrategy::{variant:?} — the four-path convergence \
8171                     (Display + as_str + Serialize + from_wire) resolves through \
8172                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8173                )
8174            });
8175            assert_eq!(
8176                parsed, variant,
8177                "RestartStrategy::from_wire of the Serialize derive's wire \
8178                 byte-string for RestartStrategy::{variant:?} must round-trip \
8179                 to the same variant; got {parsed:?}"
8180            );
8181        }
8182    }
8183
8184    #[test]
8185    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8186        // Fail-before-pass-after byte-parity pin on the newly lifted
8187        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8188        // library trait impl and the substrate-primitive
8189        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8190        // the same four-arm accept-set across every arm the exhaustive
8191        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8192        // detour that routes the trait impl through a divergent projection
8193        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8194        // … }` re-inlining that opens a compile-time link to the un-
8195        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8196        // attribute drift that silently splits the wire byte-string from
8197        // every consumer that reaches for this typed dispatch, an
8198        // accidental swap onto the kebab-case dispatcher-catalog axis the
8199        // pre-existing [`std::str::FromStr`] impl parses through and which
8200        // would collide the two-axis wire/catalog split the sibling
8201        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8202        // trips at caixa-core test time under `assert_eq!` rather than at
8203        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8204        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8205        // carries so no arm's projection is covered only by the sibling
8206        // method-named `from_wire` path. Peer of the sibling
8207        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8208        // (3c83606),
8209        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8210        // (bf33136), and the M3
8211        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8212        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8213        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8214        // surface.
8215        for &variant in RestartStrategy::ALL {
8216            let wire = variant.as_str();
8217            assert_eq!(
8218                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8219                Ok(variant),
8220                "TryFrom<&str> impl on RestartStrategy must round-trip \
8221                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8222                 Ok(RestartStrategy::{variant:?}) — divergence from \
8223                 RestartStrategy::from_wire signals a silent detour off \
8224                 the substrate-primitive accessor"
8225            );
8226            assert_eq!(
8227                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8228                RestartStrategy::from_wire(wire),
8229                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8230                 RestartStrategy::from_wire on the same input"
8231            );
8232        }
8233    }
8234
8235    #[test]
8236    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8237        // Rejection witness on the `impl TryFrom<&str> for
8238        // RestartStrategy` — sweeps a candidate set of byte-strings
8239        // outside the four-arm PascalCase wire accept-set the sibling
8240        // [`RestartStrategy::as_str`] emits and asserts every one lands on
8241        // `Err(())`, so a future accidental widening of the trait impl's
8242        // accept-set (a stray additional
8243        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8244        // path, a silent inclusion of the kebab-case dispatcher-catalog
8245        // byte-string the pre-existing [`std::str::FromStr`] impl the
8246        // [`gen_platform::FromStrKind`] derive installs parses onto the
8247        // wire axis — which would collide the two-axis
8248        // wire/dispatcher-catalog split the sibling
8249        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8250        // an English-rebrand or plural-arm silent alias that would
8251        // widen the wire accept-set past the OTP-canonical four) trips at
8252        // caixa-core test time. The candidate set includes the empty
8253        // string, whitespace-only padding, the kebab-case dispatcher-
8254        // catalog byte-strings on the sibling axis (a caller who confuses
8255        // the two axes trips here rather than at a downstream consumer's
8256        // silent reject), a lowercase / uppercase / mixed-case fold of
8257        // each PascalCase arm (a caller who assumes case-fold acceptance
8258        // trips here), leading/trailing whitespace padding, the trailing-
8259        // newline shape, quote-wrapped candidates, and a residual set of
8260        // plausible-but-wrong English rebrand candidates. Peer of the
8261        // sibling
8262        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8263        // (3c83606) and
8264        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8265        // (6fd00cd) rejection witnesses.
8266        let rejected: &[&str] = &[
8267            "",
8268            " ",
8269            "\n",
8270            "\t",
8271            "one-for-one",
8272            "one-for-all",
8273            "rest-for-one",
8274            "simple-one-for-one",
8275            "oneforone",
8276            "one_for_one",
8277            "OneForOnes",
8278            "ONEFORONE",
8279            "oneforall",
8280            "restforone",
8281            "simpleoneforone",
8282            "OneForOne ",
8283            " OneForOne",
8284            " OneForAll ",
8285            "OneForOne\n",
8286            "RestForOne\t",
8287            "OneForEach",
8288            "AllForOne",
8289            "one for one",
8290            "\"OneForOne\"",
8291            "?",
8292        ];
8293        for &input in rejected {
8294            assert_eq!(
8295                <RestartStrategy as TryFrom<&str>>::try_from(input),
8296                Err(()),
8297                "TryFrom<&str> impl on RestartStrategy must reject the \
8298                 non-wire byte-string {input:?} — silent acceptance signals \
8299                 an accept-set widening off the paired \
8300                 RestartStrategy::from_wire resolver"
8301            );
8302        }
8303    }
8304
8305    #[test]
8306    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8307        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8308        // `from_wire` reverse projections must resolve identically on
8309        // *every* input, not just the ones [`RestartStrategy::ALL`]
8310        // enumerates. Sweeps a mixed candidate set spanning accepted
8311        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8312        // dispatcher-catalog byte-strings, empty, whitespace-padded,
8313        // quoted, English-rebrand candidates) inputs and asserts the
8314        // trait's `Result::ok()` projection byte-equals the method-named
8315        // resolver's `Option<Self>` return-shape on each, locking the two
8316        // paths together by construction so any future detour (a stray
8317        // `try_from` special-case that widens or narrows the accept-set
8318        // outside the paired `from_wire` resolver, an accidental swap
8319        // onto the kebab-case [`std::str::FromStr`] impl the
8320        // [`gen_platform::FromStrKind`] derive installs on the sibling
8321        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8322        // the sibling
8323        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8324        // pin — extends the round-trip discipline onto the M2-OTP-shape
8325        // sibling-restart axis.
8326        let candidates: &[&str] = &[
8327            "OneForOne",
8328            "OneForAll",
8329            "RestForOne",
8330            "SimpleOneForOne",
8331            "",
8332            "one-for-one",
8333            "one-for-all",
8334            "rest-for-one",
8335            "simple-one-for-one",
8336            "oneforone",
8337            "unknown",
8338            "OneForOne ",
8339            " OneForOne",
8340            "\"OneForOne\"",
8341            "OneForEach",
8342            "?",
8343        ];
8344        for &input in candidates {
8345            let via_trait: Option<RestartStrategy> =
8346                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8347            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8348            assert_eq!(
8349                via_trait, via_method,
8350                "TryFrom<&str> and from_wire must resolve identically on \
8351                 input {input:?} — divergence signals the two reverse-\
8352                 projection paths have drifted onto different accept-sets"
8353            );
8354        }
8355    }
8356
8357    #[test]
8358    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8359        // Fail-before-pass-after byte-parity pin on the newly lifted
8360        // `impl From<RestartStrategy> for &'static str` — asserts the
8361        // standard-library trait impl and the substrate-primitive
8362        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8363        // the same four-arm emit-set across every arm the exhaustive
8364        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8365        // detour that routes the trait impl through a divergent
8366        // projection (a per-arm inline `match strategy { OneForOne =>
8367        // "OneForOne", … }` re-inlining that opens a compile-time link to
8368        // the un-lifted arm-literal, an accidental swap onto the sibling
8369        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8370        // would collide the two-axis wire/catalog split the sibling
8371        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8372        // at caixa-core test time under `assert_eq!` rather than at a
8373        // downstream `impl Into<&'static str>`-bound consumer's silent
8374        // split. Sweeps every one of the four arms
8375        // [`RestartStrategy::ALL`] carries so no arm's projection is
8376        // covered only by the sibling method-named `as_str` /
8377        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8378        // `<&'static str as From<RestartStrategy>>::from` output in a
8379        // `const`-shape binding to make the `'static` lifetime promise a
8380        // build-time invariant — a future accidental downgrade of any of
8381        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8382        // constants to a non-`&'static str` (a `String::leak()`-produced
8383        // return, a `Box::leak`-cast) trips at caixa-core build time
8384        // rather than at a downstream `'static`-bound consumer.
8385        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8386        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8387        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8388        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8389        for &variant in RestartStrategy::ALL {
8390            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8391            let via_method: &'static str = variant.as_str();
8392            assert_eq!(
8393                via_trait, via_method,
8394                "From<RestartStrategy> for &'static str impl must round-trip \
8395                 RestartStrategy::{variant:?} to the same lifted \
8396                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8397                 divergence signals a silent detour off the substrate-primitive \
8398                 accessor"
8399            );
8400            let via_into: &'static str = variant.into();
8401            assert_eq!(
8402                via_into, via_method,
8403                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8404                 byte-equal RestartStrategy::as_str on the same input — the \
8405                 blanket-derived Into shape must resolve to the same as_str \
8406                 dispatch as the explicit From impl"
8407            );
8408        }
8409        assert_eq!(
8410            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8411            [
8412                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8413                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8414                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8415                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8416            ],
8417            "const-context RestartStrategy::as_str must resolve to the four \
8418             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8419             downgrade of any arm to a non-const or non-static byte-string \
8420             breaks the `&'static str`-lifetime promise the paired \
8421             From<RestartStrategy> for &'static str impl carries by \
8422             construction"
8423        );
8424    }
8425
8426    #[test]
8427    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8428        // Cross-axis partition pin: the paired trait-idiomatic
8429        // `From<RestartStrategy> for &'static str` forward projection and
8430        // the method-named [`RestartStrategy::as_str`] forward projection
8431        // must resolve identically on *every* arm, not just the ones
8432        // named in the primary byte-parity pin above. Sweeps every
8433        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8434        // output byte-equals the method-named accessor's return-value on
8435        // each, locking the two forward-projection paths together by
8436        // construction so any future detour (a stray `From` special-case
8437        // that lands on a divergent per-arm literal outside the paired
8438        // `as_str` dispatch, a hypothetical rebrand touching one axis
8439        // without the other) trips at caixa-core test time. Peer of the
8440        // sibling reverse-projection partition pin
8441        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8442        // — extends the round-trip discipline onto the trait-idiomatic
8443        // *forward* axis, closing the two-way `Self ↔ &'static str`
8444        // round-trip on the trait-idiomatic pair
8445        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8446        // well as the pre-existing method-named pair
8447        // (`as_str` + `from_wire`).
8448        for &variant in RestartStrategy::ALL {
8449            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8450            let via_method: &'static str = variant.as_str();
8451            assert_eq!(
8452                via_trait, via_method,
8453                "From<RestartStrategy> for &'static str and \
8454                 RestartStrategy::as_str must resolve identically on \
8455                 RestartStrategy::{variant:?} — divergence signals the \
8456                 two forward-projection paths have drifted onto different \
8457                 emit-sets"
8458            );
8459        }
8460        // Round-trip witness: every arm's forward `From` output re-parses
8461        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8462        // to the original variant. Closes the two-way `RestartStrategy ↔
8463        // &'static str` round-trip on the trait-idiomatic axis pair,
8464        // mirroring the pre-existing method-named `as_str` + `from_wire`
8465        // round-trip on the substrate-primitive axis pair.
8466        for &variant in RestartStrategy::ALL {
8467            let emitted: &'static str = variant.into();
8468            let re_parsed: Result<RestartStrategy, ()> =
8469                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8470            assert_eq!(
8471                re_parsed,
8472                Ok(variant),
8473                "trait-idiomatic axis pair must round-trip \
8474                 RestartStrategy::{variant:?} through `.into::<&'static \
8475                 str>()` and back through `TryFrom<&str>` — a break signals \
8476                 the forward-emit and reverse-parse axes have drifted onto \
8477                 different vocabularies"
8478            );
8479        }
8480    }
8481
8482    #[test]
8483    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8484        // Fail-before-pass-after byte-parity pin on the newly lifted
8485        // `impl From<&RestartStrategy> for &'static str` — asserts the
8486        // borrowed-input standard-library trait impl and the substrate-
8487        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8488        // resolve to the same four-arm emit-set across every arm the
8489        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8490        // `From` trait does not auto-derive the borrowed-input sibling
8491        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8492        // where T: Copy, U: From<T>` blanket in `core`), so the
8493        // borrowed-input axis is a distinct trait-idiomatic surface
8494        // that a `.iter().map(Into::into)` shape over
8495        // [`RestartStrategy::ALL`] (whose iterator yields
8496        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8497        // this impl and no other — the paired owned-input
8498        // [`From<RestartStrategy>`] impl requires an explicit
8499        // `.copied()` / dereference before the trait fires.
8500        // Materializes the `<&'static str as
8501        // From<&RestartStrategy>>::from` output in a `const`-shape
8502        // binding to make the `'static` lifetime promise a build-time
8503        // invariant.
8504        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8505        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8506        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8507        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8508        for variant in RestartStrategy::ALL {
8509            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8510            let via_method: &'static str = variant.as_str();
8511            assert_eq!(
8512                via_trait, via_method,
8513                "From<&RestartStrategy> for &'static str impl must \
8514                 round-trip &RestartStrategy::{variant:?} to the same \
8515                 lifted SUPERVISOR_ESTRATEGIA_* const \
8516                 RestartStrategy::as_str returns — divergence signals a \
8517                 silent detour off the substrate-primitive accessor"
8518            );
8519            let via_into: &'static str = variant.into();
8520            assert_eq!(
8521                via_into, via_method,
8522                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8523                 must byte-equal RestartStrategy::as_str on the same input — \
8524                 the blanket-derived Into shape must resolve to the same \
8525                 as_str dispatch as the explicit From impl"
8526            );
8527        }
8528        assert_eq!(
8529            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8530            [
8531                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8532                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8533                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8534                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8535            ],
8536            "const-context RestartStrategy::as_str must resolve to the \
8537             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8538             input From<&RestartStrategy> for &'static str impl inherits \
8539             its `'static` lifetime promise from the same accessor the \
8540             owned-input sibling routes through"
8541        );
8542    }
8543
8544    #[test]
8545    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8546        // Cross-axis partition pin: the paired trait-idiomatic
8547        // owned-input `From<RestartStrategy> for &'static str` (523157d
8548        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8549        // &'static str` (this lift) forward projections must resolve
8550        // identically on every arm, locking the two input-shape paths
8551        // together so any future detour trips at caixa-core test time.
8552        // Then a witness that a `.iter().map(Into::into)` pipe over
8553        // [`RestartStrategy::ALL`] (whose iterator yields
8554        // `&RestartStrategy`) materializes the four-arm accept-set
8555        // through the borrowed-input axis alone — the exact shape a
8556        // future wasm-operator per-supervisor sibling-restart-strategy
8557        // diagnostic line, a future substrate-wide per-arm diagnostic
8558        // column, or a
8559        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8560        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8561        // per-strategy lookup reaches through — closing the two-way
8562        // owned/borrowed input-shape symmetry on the forward-projection
8563        // trait-idiomatic axis. Peer of the sibling
8564        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8565        // (64aa742) /
8566        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8567        // (5ab993a) /
8568        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8569        // (807b0b5) partition pins on the sibling closed-set typed-enum
8570        // discriminator axes — extends the borrowed-input axis
8571        // discipline onto the first M2 OTP-shape sibling-restart
8572        // closed-set typed enum on the caixa surface. Also closes the
8573        // direct two-way `&Self → &'static str → Self` round-trip via
8574        // the paired [`TryFrom<&str>`] axis — unlike the peer
8575        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8576        // lowercase Portuguese diagnostic bytes while the reverse
8577        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8578        // trip through an intermediate wire-vocab hop), the
8579        // [`RestartStrategy::as_str`] emit and
8580        // [`RestartStrategy::from_wire`] parse share the same
8581        // `PascalCase` vocabulary by construction, so the borrowed-
8582        // input forward axis and the reverse axis compose directly.
8583        for &variant in RestartStrategy::ALL {
8584            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8585            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8586            assert_eq!(
8587                owned, borrowed,
8588                "From<RestartStrategy> and From<&RestartStrategy> for \
8589                 &'static str must resolve identically on \
8590                 RestartStrategy::{variant:?} — divergence signals the \
8591                 owned-input and borrowed-input forward-projection paths \
8592                 have drifted onto different emit-sets"
8593            );
8594        }
8595        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8596        let via_method: Vec<&'static str> =
8597            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8598        assert_eq!(
8599            via_iter, via_method,
8600            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8601             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8602             borrowed-input `From<&RestartStrategy> for &'static str` \
8603             axis is what makes the `.iter().map(Into::into)` shape route \
8604             through the substrate-primitive `RestartStrategy::as_str` \
8605             accessor rather than through a per-call-site `.copied()` / \
8606             dereference detour"
8607        );
8608        for variant in RestartStrategy::ALL {
8609            let emitted: &'static str = variant.into();
8610            let re_parsed: Result<RestartStrategy, ()> =
8611                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8612            assert_eq!(
8613                re_parsed,
8614                Ok(*variant),
8615                "trait-idiomatic borrowed-input forward-projection + \
8616                 reverse-projection axis pair must round-trip \
8617                 &RestartStrategy::{variant:?} through `.into::<&'static \
8618                 str>()` (via the borrowed-input axis) and back through \
8619                 `TryFrom<&str>` — a break signals the borrowed-input \
8620                 forward-emit and reverse-parse axes have drifted onto \
8621                 different vocabularies"
8622            );
8623        }
8624    }
8625
8626    #[test]
8627    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8628        // Fail-before-pass-after byte-parity pin on the newly lifted
8629        // `impl From<RestartStrategy> for String` — asserts the
8630        // owned-`String`-returning standard-library trait impl and the
8631        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8632        // accessor resolve to the same four-arm emit-set across every
8633        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8634        // Rust's standard library does not carry a blanket
8635        // `impl<T: AsRef<str>> From<T> for String` (nor an
8636        // `impl<T: fmt::Display> From<T> for String`), so the
8637        // owned-`String` forward-projection axis is a distinct
8638        // trait-idiomatic surface that a
8639        // `let key: String = strategy.into();`-shaped call site
8640        // reaches through this impl and no other — the paired sibling
8641        // `From<RestartStrategy> for &'static str` impl forces every
8642        // owned-`String` call site through an explicit
8643        // `.to_owned()` / `String::from` restatement.
8644        for &variant in RestartStrategy::ALL {
8645            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8646            let via_method: &'static str = variant.as_str();
8647            assert_eq!(
8648                via_trait.as_str(),
8649                via_method,
8650                "From<RestartStrategy> for String impl must round-trip \
8651                 RestartStrategy::{variant:?} to the same lifted \
8652                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8653                 returns — divergence signals a silent detour off the \
8654                 substrate-primitive accessor"
8655            );
8656            let via_into: String = variant.into();
8657            assert_eq!(
8658                via_into.as_str(),
8659                via_method,
8660                "Into<String>::into on RestartStrategy::{variant:?} must \
8661                 byte-equal RestartStrategy::as_str on the same input — the \
8662                 blanket-derived Into shape must resolve to the same as_str \
8663                 dispatch as the explicit From impl"
8664            );
8665        }
8666    }
8667
8668    #[test]
8669    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8670        // Cross-axis partition pin: the paired trait-idiomatic
8671        // owned-`String` `From<RestartStrategy> for String` (this lift)
8672        // and owned-`&'static str` `From<RestartStrategy> for &'static
8673        // str` (523157d) forward projections must resolve identically
8674        // on every arm, locking the two return-type-shape paths
8675        // together so any future detour trips at caixa-core test time.
8676        // Also byte-parity witness against the sibling
8677        // [`ToString::to_string`] surface routed through
8678        // [`std::fmt::Display`] — the three owned-heap-string paths
8679        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8680        // resolve identically on every arm so a future consumer that
8681        // picks any of the three lands on the same lifted
8682        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8683        // witness through the paired trait-idiomatic reverse
8684        // [`TryFrom<&str>`] axis on the owned-`String`'s
8685        // [`String::as_str`] borrow that closes the two-way
8686        // `Self → String → Self` round-trip on the trait-idiomatic
8687        // owned-`String` forward + reverse axis pair.
8688        for &variant in RestartStrategy::ALL {
8689            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8690            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8691            assert_eq!(
8692                owned_string.as_str(),
8693                owned_static,
8694                "From<RestartStrategy> for String and From<RestartStrategy> \
8695                 for &'static str must resolve identically on \
8696                 RestartStrategy::{variant:?} — divergence signals the \
8697                 owned-`String` and owned-`&'static str` forward-projection \
8698                 return-type-shape paths have drifted onto different \
8699                 emit-sets"
8700            );
8701            let via_to_string: String = variant.to_string();
8702            assert_eq!(
8703                owned_string, via_to_string,
8704                "From<RestartStrategy> for String must byte-equal \
8705                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8706                 divergence signals the trait-idiomatic owned-`String` \
8707                 forward-projection axis and the ToString-through-Display \
8708                 axis have drifted onto different emit-sets"
8709            );
8710        }
8711        let via_iter: Vec<String> = RestartStrategy::ALL
8712            .iter()
8713            .copied()
8714            .map(String::from)
8715            .collect();
8716        let via_method: Vec<String> = RestartStrategy::ALL
8717            .iter()
8718            .map(|s| s.as_str().to_owned())
8719            .collect();
8720        assert_eq!(
8721            via_iter, via_method,
8722            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8723             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8724             every arm — the owned-`String` `From<RestartStrategy> for \
8725             String` axis is what makes the `String::from` composition \
8726             route through the substrate-primitive `RestartStrategy::as_str` \
8727             accessor rather than through a per-call-site `.to_owned()` / \
8728             `String::from(strategy.as_str())` detour"
8729        );
8730        for &variant in RestartStrategy::ALL {
8731            let emitted: String = variant.into();
8732            let re_parsed: Result<RestartStrategy, ()> =
8733                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8734            assert_eq!(
8735                re_parsed,
8736                Ok(variant),
8737                "trait-idiomatic owned-`String` forward-projection + \
8738                 reverse-projection axis pair must round-trip \
8739                 RestartStrategy::{variant:?} through `.into::<String>()` \
8740                 and back through `TryFrom<&str>` on the owned-`String`'s \
8741                 String::as_str borrow — a break signals the owned-`String` \
8742                 forward-emit and reverse-parse axes have drifted onto \
8743                 different vocabularies"
8744            );
8745        }
8746    }
8747
8748    #[test]
8749    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8750        // Fail-before-pass-after byte-parity pin on the newly lifted
8751        // `impl From<&RestartStrategy> for String` — asserts the
8752        // borrowed-input owned-`String`-returning standard-library trait
8753        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8754        // `pub const fn` accessor resolve to the same four-arm emit-set
8755        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8756        // enumerates. Rust's standard library does not carry a blanket
8757        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8758        // `impl<T: fmt::Display> From<&T> for String`), so the
8759        // borrowed-input owned-`String` forward-projection axis is a
8760        // distinct trait-idiomatic surface that a
8761        // `let key: String = (&strategy).into();`-shaped call site
8762        // reaches through this impl and no other — the paired sibling
8763        // `From<RestartStrategy> for String` impl forces every
8764        // borrowed-input call site through an explicit `Copy` deref
8765        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8766        // `.to_string()` detour.
8767        for &variant in RestartStrategy::ALL {
8768            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8769            let via_method: &'static str = variant.as_str();
8770            assert_eq!(
8771                via_trait.as_str(),
8772                via_method,
8773                "From<&RestartStrategy> for String impl must round-trip \
8774                 &RestartStrategy::{variant:?} to the same lifted \
8775                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8776                 returns — divergence signals a silent detour off the \
8777                 substrate-primitive accessor"
8778            );
8779            let via_into: String = (&variant).into();
8780            assert_eq!(
8781                via_into.as_str(),
8782                via_method,
8783                "Into<String>::into on &RestartStrategy::{variant:?} must \
8784                 byte-equal RestartStrategy::as_str on the same input — the \
8785                 blanket-derived Into shape must resolve to the same as_str \
8786                 dispatch as the explicit From impl"
8787            );
8788        }
8789    }
8790
8791    #[test]
8792    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8793        // Cross-axis partition pin: the newly lifted trait-idiomatic
8794        // borrowed-input owned-`String` `From<&RestartStrategy> for
8795        // String` (this lift), the paired owned-input owned-`String`
8796        // `From<RestartStrategy> for String` (7baa18a), the paired
8797        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8798        // for &'static str` (e941836), and the paired owned-input
8799        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8800        // (523157d) — every corner of the `{Self, &Self} × {&'static
8801        // str, String}` 2×2 trait-idiomatic projection family — must
8802        // resolve identically on every arm, locking the four
8803        // return-shape × input-shape paths together so any future
8804        // detour trips at caixa-core test time. Also byte-parity
8805        // witness against the sibling [`ToString::to_string`] surface
8806        // routed through [`std::fmt::Display`] and a direct round-trip
8807        // witness through the paired trait-idiomatic reverse
8808        // [`TryFrom<&str>`] axis on the owned-`String`'s
8809        // [`String::as_str`] borrow that closes the two-way
8810        // `&Self → String → Self` round-trip on the trait-idiomatic
8811        // borrowed-input owned-`String` forward + reverse axis pair.
8812        for &variant in RestartStrategy::ALL {
8813            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8814            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8815            let borrowed_static: &'static str =
8816                <&'static str as From<&RestartStrategy>>::from(&variant);
8817            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8818            assert_eq!(
8819                borrowed_string, owned_string,
8820                "From<&RestartStrategy> for String and From<RestartStrategy> \
8821                 for String must resolve identically on \
8822                 RestartStrategy::{variant:?} — divergence signals the \
8823                 borrowed-input and owned-input owned-`String` \
8824                 forward-projection input-shape paths have drifted onto \
8825                 different emit-sets"
8826            );
8827            assert_eq!(
8828                borrowed_string.as_str(),
8829                borrowed_static,
8830                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8831                 for &'static str must resolve identically on \
8832                 RestartStrategy::{variant:?} — divergence signals the \
8833                 borrowed-input `&'static str` and owned-`String` \
8834                 return-shape paths have drifted onto different emit-sets"
8835            );
8836            assert_eq!(
8837                borrowed_string.as_str(),
8838                owned_static,
8839                "From<&RestartStrategy> for String and From<RestartStrategy> \
8840                 for &'static str must resolve identically on \
8841                 RestartStrategy::{variant:?} — divergence signals a break \
8842                 in the diagonal corner of the {{Self, &Self}} × \
8843                 {{&'static str, String}} 2×2 trait-idiomatic \
8844                 projection family"
8845            );
8846            let via_to_string: String = variant.to_string();
8847            assert_eq!(
8848                borrowed_string, via_to_string,
8849                "From<&RestartStrategy> for String must byte-equal \
8850                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8851                 divergence signals the trait-idiomatic borrowed-input \
8852                 owned-`String` forward-projection axis and the \
8853                 ToString-through-Display axis have drifted onto different \
8854                 emit-sets"
8855            );
8856        }
8857        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8858        let via_method: Vec<String> = RestartStrategy::ALL
8859            .iter()
8860            .map(|s| s.as_str().to_owned())
8861            .collect();
8862        assert_eq!(
8863            via_iter, via_method,
8864            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8865             call site whose iteration axis holds `&RestartStrategy` by \
8866             construction — must byte-equal `.iter().map(|s| \
8867             s.as_str().to_owned())` on every arm — the borrowed-input \
8868             owned-`String` `From<&RestartStrategy> for String` axis is \
8869             what makes the `String::from` composition route through the \
8870             substrate-primitive `RestartStrategy::as_str` accessor \
8871             without a spurious `Copy` deref (which would only be \
8872             reachable through the owned-input `From<RestartStrategy> for \
8873             String` axis by first calling `.copied()` on the iterator)"
8874        );
8875        for &variant in RestartStrategy::ALL {
8876            let emitted: String = (&variant).into();
8877            let re_parsed: Result<RestartStrategy, ()> =
8878                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8879            assert_eq!(
8880                re_parsed,
8881                Ok(variant),
8882                "trait-idiomatic borrowed-input owned-`String` \
8883                 forward-projection + reverse-projection axis pair must \
8884                 round-trip &RestartStrategy::{variant:?} through \
8885                 `.into::<String>()` on the borrowed-input surface and \
8886                 back through `TryFrom<&str>` on the owned-`String`'s \
8887                 String::as_str borrow — a break signals the \
8888                 borrowed-input owned-`String` forward-emit and \
8889                 reverse-parse axes have drifted onto different \
8890                 vocabularies"
8891            );
8892        }
8893    }
8894
8895    #[test]
8896    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8897        // Fail-before-pass-after byte-parity pin on the newly lifted
8898        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8899        // asserts the standard-library trait impl and the substrate-
8900        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8901        // accessor resolve to the same four-arm emit-set across every
8902        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8903        // enumerates. Rust's standard library does not carry a blanket
8904        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8905        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8906        // the `Cow<'static, str>` forward-projection axis is a
8907        // distinct trait-idiomatic surface that a
8908        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8909        // site reaches through this impl and no other — the paired
8910        // sibling `From<RestartStrategy> for &'static str` and
8911        // `From<RestartStrategy> for String` impls force every
8912        // `Cow<'static, str>`-parameterized call site through a
8913        // `Cow::Borrowed(strategy.as_str())` /
8914        // `Cow::Owned(strategy.to_string())` composition whose type
8915        // bounds have no compile-time link back to the substrate
8916        // primitive.
8917        //
8918        // Also asserts the projection lands on the zero-alloc
8919        // [`std::borrow::Cow::Borrowed`] arm (not the
8920        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8921        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8922        // return lifetime by construction makes the borrowed arm the
8923        // type-correct projection with no runtime allocation. Any
8924        // future silent detour that routes the impl through the owned
8925        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8926        // that would allocate on every call site where the
8927        // `&'static str` return of [`super::RestartStrategy::as_str`]
8928        // makes the zero-alloc borrowed projection type-correct) trips
8929        // at caixa-core test time under the
8930        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8931        // than at a downstream `Cow<'static, str>`-bound consumer's
8932        // silent allocation.
8933        //
8934        // First peer on the substrate-wide trait-idiomatic
8935        // [`std::borrow::Cow<'static, str>`] forward-projection family
8936        // to extend the axis off the top-level [`super::CaixaKind`]
8937        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8938        // first M2 OTP-shape closed-set fieldless typed enum on the
8939        // caixa surface.
8940        for &variant in RestartStrategy::ALL {
8941            let via_trait: std::borrow::Cow<'static, str> =
8942                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8943            let via_method: &'static str = variant.as_str();
8944            assert_eq!(
8945                via_trait.as_ref(),
8946                via_method,
8947                "From<RestartStrategy> for Cow<'static, str> impl must \
8948                 round-trip RestartStrategy::{variant:?} to the same \
8949                 lifted SUPERVISOR_ESTRATEGIA_* const \
8950                 RestartStrategy::as_str returns — divergence signals a \
8951                 silent detour off the substrate-primitive accessor"
8952            );
8953            assert!(
8954                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8955                "From<RestartStrategy> for Cow<'static, str> impl must \
8956                 land on the zero-alloc Cow::Borrowed arm on \
8957                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8958                 signals the projection has silently allocated where \
8959                 the substrate-primitive RestartStrategy::as_str \
8960                 `&'static str` return makes the borrowed arm the \
8961                 type-correct projection"
8962            );
8963            let via_into: std::borrow::Cow<'static, str> = variant.into();
8964            assert_eq!(
8965                via_into.as_ref(),
8966                via_method,
8967                "Into<Cow<'static, str>>::into on \
8968                 RestartStrategy::{variant:?} must byte-equal \
8969                 RestartStrategy::as_str on the same input — the \
8970                 blanket-derived Into shape must resolve to the same \
8971                 as_str dispatch as the explicit From impl"
8972            );
8973            assert!(
8974                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8975                "Into<Cow<'static, str>>::into on \
8976                 RestartStrategy::{variant:?} must land on the \
8977                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8978                 Into shape must resolve to the same Cow::Borrowed \
8979                 dispatch as the explicit From impl"
8980            );
8981        }
8982    }
8983
8984    #[test]
8985    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8986        // Cross-axis partition pin: the newly lifted trait-idiomatic
8987        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8988        // (this lift), the paired owned-input `From<RestartStrategy>
8989        // for &'static str` (523157d), and the paired owned-input
8990        // `From<RestartStrategy> for String` (7baa18a) forward
8991        // projections must resolve identically on every arm, locking
8992        // the three return-shape paths together by construction so any
8993        // future detour trips at caixa-core test time. Also byte-parity
8994        // witness against the sibling [`ToString::to_string`] surface
8995        // routed through [`std::fmt::Display`] — every owned-heap-
8996        // string path (the `Cow::Owned` promotion of this axis's
8997        // `.into_owned()`, `From<RestartStrategy> for String`, and
8998        // `.to_string()`) resolves to the same lifted
8999        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9000        //
9001        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9002        // witness over [`super::RestartStrategy::ALL`] that
9003        // materializes the four-arm accept-set through the
9004        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9005        // shape a future `axum::response::IntoResponse` per-strategy
9006        // rejection-body composer, a future M4 admission-webhook
9007        // per-strategy rejection-reason emitter whose typing rules out
9008        // the sibling [`AsRef<str>`] borrowed return, or a future
9009        // substrate-wide per-strategy diagnostic surface that binds
9010        // through a [`Cow<'static, str>`] boundary reaches through.
9011        // The pipe witness also pins the zero-alloc discipline: every
9012        // element in the collected vector satisfies the
9013        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9014        // accidental silent-allocation regression on the pipe's
9015        // iteration axis is a caixa-core-test-time failure.
9016        for &variant in RestartStrategy::ALL {
9017            let via_cow: std::borrow::Cow<'static, str> =
9018                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9019            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9020            let via_string: String = <String as From<RestartStrategy>>::from(variant);
9021            assert_eq!(
9022                via_cow.as_ref(),
9023                via_static,
9024                "From<RestartStrategy> for Cow<'static, str> and \
9025                 From<RestartStrategy> for &'static str must resolve \
9026                 identically on RestartStrategy::{variant:?} — \
9027                 divergence signals the Cow<'static, str> and \
9028                 &'static str return-shape paths have drifted onto \
9029                 different emit-sets"
9030            );
9031            assert_eq!(
9032                via_cow.as_ref(),
9033                via_string.as_str(),
9034                "From<RestartStrategy> for Cow<'static, str> and \
9035                 From<RestartStrategy> for String must resolve \
9036                 identically on RestartStrategy::{variant:?} — \
9037                 divergence signals the Cow<'static, str> and String \
9038                 return-shape paths have drifted onto different \
9039                 emit-sets"
9040            );
9041            let via_to_string: String = variant.to_string();
9042            assert_eq!(
9043                via_cow.as_ref(),
9044                via_to_string.as_str(),
9045                "From<RestartStrategy> for Cow<'static, str> must \
9046                 byte-equal RestartStrategy::to_string on \
9047                 RestartStrategy::{variant:?} — divergence signals the \
9048                 trait-idiomatic Cow<'static, str> forward-projection \
9049                 axis and the ToString-through-Display axis have \
9050                 drifted onto different emit-sets"
9051            );
9052        }
9053        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9054            .iter()
9055            .copied()
9056            .map(std::borrow::Cow::from)
9057            .collect();
9058        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9059            .iter()
9060            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9061            .collect();
9062        assert_eq!(
9063            via_iter, via_method,
9064            "`.iter().copied().map(Cow::from)` over \
9065             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9066             Cow::Borrowed(s.as_str()))` on every arm — the \
9067             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9068             str>` axis is what makes the `Cow::from` composition \
9069             route through the substrate-primitive \
9070             `RestartStrategy::as_str` accessor with the zero-alloc \
9071             Cow::Borrowed arm by construction, rather than a \
9072             per-call-site `Cow::Owned(strategy.to_string())` \
9073             allocation"
9074        );
9075        for cow in &via_iter {
9076            assert!(
9077                matches!(cow, std::borrow::Cow::Borrowed(_)),
9078                "every element of the \
9079                 .iter().copied().map(Cow::from) pipe over \
9080                 RestartStrategy::ALL must land on the zero-alloc \
9081                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9082                 signals the pipe's iteration axis has silently \
9083                 allocated where the substrate-primitive \
9084                 RestartStrategy::as_str `&'static str` return makes \
9085                 the borrowed arm the type-correct projection"
9086            );
9087        }
9088    }
9089
9090    #[test]
9091    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9092        // Fail-before-pass-after byte-parity pin on the newly lifted
9093        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9094        // asserts the borrowed-input standard-library trait impl and
9095        // the substrate-primitive [`super::RestartStrategy::as_str`]
9096        // `pub const fn` accessor resolve to the same four-arm emit-
9097        // set across every arm the exhaustive
9098        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9099        // standard library does not carry a blanket
9100        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9101        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9102        // the borrowed-input `Cow<'static, str>` forward-projection
9103        // axis is a distinct trait-idiomatic surface that a
9104        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9105        // call site or a
9106        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9107        // reaches through this impl and no other — the paired owned-
9108        // input `From<RestartStrategy> for Cow<'static, str>` impl
9109        // (7dd28b3) forces every borrowed-input call site through an
9110        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9111        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9112        // bounds have no compile-time link back to the substrate
9113        // primitive.
9114        //
9115        // Also asserts the projection lands on the zero-alloc
9116        // [`std::borrow::Cow::Borrowed`] arm (not the
9117        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9118        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9119        // return lifetime by construction makes the borrowed arm the
9120        // type-correct projection with no runtime allocation on the
9121        // borrowed-input surface just as on the paired owned-input
9122        // surface.
9123        //
9124        // Second peer on the substrate-wide trait-idiomatic
9125        // [`std::borrow::Cow<'static, str>`] forward-projection family
9126        // on this enum — closes the `{Self, &Self}` input-shape
9127        // corner of the [`Cow<'static, str>`] axis on the first M2
9128        // OTP-shape closed-set fieldless typed enum peer on the caixa
9129        // surface (`:supervisor :estrategia`), exactly as d45c409
9130        // closed it on the top-level [`super::CaixaKind`] one commit
9131        // after the owning half (99c1735) landed. Every future
9132        // closed-set fieldless typed enum peer on the substrate is a
9133        // future target of the campaign.
9134        for &variant in RestartStrategy::ALL {
9135            let via_trait: std::borrow::Cow<'static, str> =
9136                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9137            let via_method: &'static str = variant.as_str();
9138            assert_eq!(
9139                via_trait.as_ref(),
9140                via_method,
9141                "From<&RestartStrategy> for Cow<'static, str> impl must \
9142                 round-trip &RestartStrategy::{variant:?} to the same \
9143                 lifted SUPERVISOR_ESTRATEGIA_* const \
9144                 RestartStrategy::as_str returns — divergence signals a \
9145                 silent detour off the substrate-primitive accessor"
9146            );
9147            assert!(
9148                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9149                "From<&RestartStrategy> for Cow<'static, str> impl must \
9150                 land on the zero-alloc Cow::Borrowed arm on \
9151                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9152                 signals the projection has silently allocated where \
9153                 the substrate-primitive RestartStrategy::as_str \
9154                 `&'static str` return makes the borrowed arm the \
9155                 type-correct projection"
9156            );
9157            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9158            assert_eq!(
9159                via_into.as_ref(),
9160                via_method,
9161                "Into<Cow<'static, str>>::into on \
9162                 &RestartStrategy::{variant:?} must byte-equal \
9163                 RestartStrategy::as_str on the same input — the \
9164                 blanket-derived Into shape must resolve to the same \
9165                 as_str dispatch as the explicit From impl"
9166            );
9167            assert!(
9168                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9169                "Into<Cow<'static, str>>::into on \
9170                 &RestartStrategy::{variant:?} must land on the \
9171                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9172                 Into shape must resolve to the same Cow::Borrowed \
9173                 dispatch as the explicit From impl"
9174            );
9175        }
9176    }
9177
9178    #[test]
9179    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9180        // Cross-axis partition pin: the newly lifted trait-idiomatic
9181        // borrowed-input `From<&RestartStrategy> for
9182        // std::borrow::Cow<'static, str>` (this lift), the paired
9183        // owned-input `From<RestartStrategy> for
9184        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9185        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9186        // for &'static str`, and the paired borrowed-input owned-
9187        // `String` `From<&RestartStrategy> for String` must resolve
9188        // identically on every arm, locking the four
9189        // return-shape × input-shape paths together by construction so
9190        // any future detour trips at caixa-core test time. Also byte-
9191        // parity witness against the sibling [`ToString::to_string`]
9192        // surface routed through [`std::fmt::Display`] — every owned-
9193        // heap-string path (this axis's `.into_owned()` promotion, the
9194        // paired [`From<&RestartStrategy> for String`], and
9195        // `.to_string()`) resolves to the same lifted
9196        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9197        //
9198        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9199        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9200        // `&RestartStrategy` by construction, so the borrowed-input
9201        // [`Cow<'static, str>`] axis is what routes the pipe through
9202        // the substrate-primitive [`super::RestartStrategy::as_str`]
9203        // accessor without a spurious [`Copy`] deref (which would only
9204        // be reachable through the owned-input
9205        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9206        // first calling `.copied()` on the iterator). The pipe witness
9207        // also pins the zero-alloc discipline: every element in the
9208        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9209        // arm predicate, so a future accidental silent-allocation
9210        // regression on the pipe's iteration axis is a caixa-core-
9211        // test-time failure.
9212        for &strategy in RestartStrategy::ALL {
9213            let borrowed_cow: std::borrow::Cow<'static, str> =
9214                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9215            let owned_cow: std::borrow::Cow<'static, str> =
9216                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9217            let borrowed_static: &'static str =
9218                <&'static str as From<&RestartStrategy>>::from(&strategy);
9219            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9220            assert_eq!(
9221                borrowed_cow, owned_cow,
9222                "From<&RestartStrategy> for Cow<'static, str> and \
9223                 From<RestartStrategy> for Cow<'static, str> must \
9224                 resolve identically on RestartStrategy::{strategy:?} — \
9225                 divergence signals the borrowed-input and owned-input \
9226                 Cow<'static, str> forward-projection input-shape \
9227                 paths have drifted onto different emit-sets"
9228            );
9229            assert_eq!(
9230                borrowed_cow.as_ref(),
9231                borrowed_static,
9232                "From<&RestartStrategy> for Cow<'static, str> and \
9233                 From<&RestartStrategy> for &'static str must resolve \
9234                 identically on RestartStrategy::{strategy:?} — \
9235                 divergence signals the borrowed-input Cow<'static, \
9236                 str> and &'static str return-shape paths have drifted \
9237                 onto different emit-sets"
9238            );
9239            assert_eq!(
9240                borrowed_cow.as_ref(),
9241                borrowed_string.as_str(),
9242                "From<&RestartStrategy> for Cow<'static, str> and \
9243                 From<&RestartStrategy> for String must resolve \
9244                 identically on RestartStrategy::{strategy:?} — \
9245                 divergence signals the borrowed-input Cow<'static, \
9246                 str> and owned-`String` return-shape paths have \
9247                 drifted onto different emit-sets"
9248            );
9249            let via_to_string: String = strategy.to_string();
9250            assert_eq!(
9251                borrowed_cow.as_ref(),
9252                via_to_string.as_str(),
9253                "From<&RestartStrategy> for Cow<'static, str> must \
9254                 byte-equal RestartStrategy::to_string on \
9255                 RestartStrategy::{strategy:?} — divergence signals \
9256                 the trait-idiomatic borrowed-input Cow<'static, str> \
9257                 forward-projection axis and the ToString-through-\
9258                 Display axis have drifted onto different emit-sets"
9259            );
9260        }
9261        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9262            .iter()
9263            .map(std::borrow::Cow::from)
9264            .collect();
9265        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9266            .iter()
9267            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9268            .collect();
9269        assert_eq!(
9270            via_iter, via_method,
9271            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9272             call site whose iteration axis holds `&RestartStrategy` \
9273             by construction — must byte-equal `.iter().map(|s| \
9274             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9275             input Cow<'static, str> `From<&RestartStrategy> for \
9276             Cow<'static, str>` axis is what makes the `Cow::from` \
9277             composition route through the substrate-primitive \
9278             `RestartStrategy::as_str` accessor with the zero-alloc \
9279             Cow::Borrowed arm by construction and without a spurious \
9280             `Copy` deref (which would only be reachable through the \
9281             owned-input `From<RestartStrategy> for Cow<'static, str>` \
9282             axis by first calling `.copied()` on the iterator)"
9283        );
9284        for cow in &via_iter {
9285            assert!(
9286                matches!(cow, std::borrow::Cow::Borrowed(_)),
9287                "every element of the .iter().map(Cow::from) pipe \
9288                 over RestartStrategy::ALL must land on the zero-\
9289                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9290                 any arm signals the pipe's iteration axis has \
9291                 silently allocated where the substrate-primitive \
9292                 RestartStrategy::as_str `&'static str` return makes \
9293                 the borrowed arm the type-correct projection"
9294            );
9295        }
9296    }
9297
9298    #[test]
9299    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9300        // Fail-before-pass-after byte-parity pin on the newly lifted
9301        // `impl From<RestartStrategy> for Box<str>` — asserts the
9302        // owned-input standard-library trait impl and the
9303        // substrate-primitive [`super::RestartStrategy::as_str`]
9304        // `pub const fn` accessor resolve to the same four-arm emit-
9305        // set across every arm the exhaustive
9306        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9307        // substrate-wide `Box<str>` forward-projection campaign tier
9308        // on the first M2 OTP-shape closed-set fieldless typed enum
9309        // peer on the caixa surface (`:supervisor :estrategia`),
9310        // immediately after the paired `Cow<'static, str>` axis
9311        // (7dd28b3 / ee577fd) closed the
9312        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9313        // 2×3 corner on this enum. Rust's standard library carries
9314        // `impl From<&str> for Box<str>` and
9315        // `impl From<String> for Box<str>` but no blanket
9316        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9317        // a distinct trait-idiomatic surface that a
9318        // `let key: Box<str> = strategy.into();`-shaped call site
9319        // reaches through this impl and no other — a paired
9320        // `Box::from(strategy.as_str())` open-code has no compile-
9321        // time link back to the substrate primitive.
9322        for &variant in RestartStrategy::ALL {
9323            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9324            let via_method: &'static str = variant.as_str();
9325            assert_eq!(
9326                via_trait.as_ref(),
9327                via_method,
9328                "From<RestartStrategy> for Box<str> impl must round-\
9329                 trip RestartStrategy::{variant:?} to the same lifted \
9330                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9331                 returns — divergence signals a silent detour off the \
9332                 substrate-primitive accessor"
9333            );
9334            let via_into: Box<str> = variant.into();
9335            assert_eq!(
9336                via_into.as_ref(),
9337                via_method,
9338                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9339                 must byte-equal RestartStrategy::as_str on the same \
9340                 input — the blanket-derived Into shape must resolve \
9341                 to the same as_str dispatch as the explicit From impl"
9342            );
9343        }
9344    }
9345
9346    #[test]
9347    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9348        // Fail-before-pass-after byte-parity pin on the newly lifted
9349        // `impl From<&RestartStrategy> for Box<str>` — asserts the
9350        // borrowed-input standard-library trait impl and the
9351        // substrate-primitive [`super::RestartStrategy::as_str`]
9352        // `pub const fn` accessor resolve to the same four-arm emit-
9353        // set across every arm the exhaustive
9354        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9355        // standard library does not carry a blanket
9356        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9357        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9358        // so the borrowed-input `Box<str>` forward-projection axis
9359        // is a distinct trait-idiomatic surface that a
9360        // `let key: Box<str> = (&strategy).into();`-shaped call site
9361        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9362        // shaped pipe reaches through this impl and no other — the
9363        // paired owned-input `From<RestartStrategy> for Box<str>`
9364        // impl (69ef45c) forces every borrowed-input call site
9365        // through an explicit `Copy` deref
9366        // (`Box::<str>::from((*strategy).as_str())`) or a
9367        // `Box::<str>::from(strategy.as_str())` open-code whose
9368        // type bounds have no compile-time link back to the
9369        // substrate primitive.
9370        //
9371        // Second peer on the substrate-wide trait-idiomatic
9372        // [`Box<str>`] forward-projection family on this enum —
9373        // closes the `{Self, &Self}` input-shape corner of the
9374        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9375        // fieldless typed enum peer on the caixa surface
9376        // (`:supervisor :estrategia`), exactly as ee577fd closed
9377        // the paired [`Cow<'static, str>`] axis one commit after
9378        // its owning half (7dd28b3) landed. Every future closed-
9379        // set fieldless typed enum peer on the substrate is a
9380        // future target of the campaign.
9381        //
9382        // Also byte-parity witness against the paired owned-input
9383        // [`From<RestartStrategy> for Box<str>`] and the sibling
9384        // borrowed-input [`From<&RestartStrategy> for &'static str`],
9385        // [`From<&RestartStrategy> for String`], and
9386        // [`From<&RestartStrategy> for Cow<'static, str>`]
9387        // return-shape axes — locking the four
9388        // return-shape × input-shape paths together by construction
9389        // so any future detour trips at caixa-core test time. Then a
9390        // `.iter().map(Box::<str>::from)` pipe witness over
9391        // [`super::RestartStrategy::ALL`] — whose iterator yields
9392        // `&RestartStrategy` by construction, so the borrowed-input
9393        // [`Box<str>`] axis is what routes the pipe through the
9394        // substrate-primitive [`super::RestartStrategy::as_str`]
9395        // accessor without a spurious [`Copy`] deref (which would
9396        // only be reachable through the owned-input
9397        // [`From<RestartStrategy> for Box<str>`] axis by first
9398        // calling `.copied()` on the iterator).
9399        for &variant in RestartStrategy::ALL {
9400            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9401            let via_method: &'static str = variant.as_str();
9402            assert_eq!(
9403                via_trait.as_ref(),
9404                via_method,
9405                "From<&RestartStrategy> for Box<str> impl must \
9406                 round-trip &RestartStrategy::{variant:?} to the same \
9407                 lifted SUPERVISOR_ESTRATEGIA_* const \
9408                 RestartStrategy::as_str returns — divergence signals \
9409                 a silent detour off the substrate-primitive accessor"
9410            );
9411            let via_into: Box<str> = (&variant).into();
9412            assert_eq!(
9413                via_into.as_ref(),
9414                via_method,
9415                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9416                 must byte-equal RestartStrategy::as_str on the same \
9417                 input — the blanket-derived Into shape must resolve \
9418                 to the same as_str dispatch as the explicit From impl"
9419            );
9420            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9421            assert_eq!(
9422                via_trait, owned_box,
9423                "From<&RestartStrategy> for Box<str> and \
9424                 From<RestartStrategy> for Box<str> must resolve \
9425                 identically on RestartStrategy::{variant:?} — \
9426                 divergence signals the borrowed-input and owned-input \
9427                 Box<str> forward-projection input-shape paths have \
9428                 drifted onto different emit-sets"
9429            );
9430            let borrowed_static: &'static str =
9431                <&'static str as From<&RestartStrategy>>::from(&variant);
9432            assert_eq!(
9433                via_trait.as_ref(),
9434                borrowed_static,
9435                "From<&RestartStrategy> for Box<str> and \
9436                 From<&RestartStrategy> for &'static str must resolve \
9437                 identically on RestartStrategy::{variant:?} — \
9438                 divergence signals the borrowed-input Box<str> and \
9439                 &'static str return-shape paths have drifted onto \
9440                 different emit-sets"
9441            );
9442            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9443            assert_eq!(
9444                via_trait.as_ref(),
9445                borrowed_string.as_str(),
9446                "From<&RestartStrategy> for Box<str> and \
9447                 From<&RestartStrategy> for String must resolve \
9448                 identically on RestartStrategy::{variant:?} — \
9449                 divergence signals the borrowed-input Box<str> and \
9450                 owned-`String` return-shape paths have drifted onto \
9451                 different emit-sets"
9452            );
9453            let borrowed_cow: std::borrow::Cow<'static, str> =
9454                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9455            assert_eq!(
9456                via_trait.as_ref(),
9457                borrowed_cow.as_ref(),
9458                "From<&RestartStrategy> for Box<str> and \
9459                 From<&RestartStrategy> for Cow<'static, str> must \
9460                 resolve identically on RestartStrategy::{variant:?} — \
9461                 divergence signals the borrowed-input Box<str> and \
9462                 Cow<'static, str> return-shape paths have drifted \
9463                 onto different emit-sets"
9464            );
9465        }
9466        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9467        let via_method: Vec<Box<str>> = RestartStrategy::ALL
9468            .iter()
9469            .map(|s| Box::<str>::from(s.as_str()))
9470            .collect();
9471        assert_eq!(
9472            via_iter, via_method,
9473            "`.iter().map(Box::<str>::from)` over \
9474             RestartStrategy::ALL — a call site whose iteration axis \
9475             holds `&RestartStrategy` by construction — must byte-\
9476             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9477             on every arm — the borrowed-input Box<str> \
9478             `From<&RestartStrategy> for Box<str>` axis is what \
9479             makes the `Box::<str>::from` composition route through \
9480             the substrate-primitive `RestartStrategy::as_str` \
9481             accessor without a spurious `Copy` deref (which would \
9482             only be reachable through the owned-input \
9483             `From<RestartStrategy> for Box<str>` axis by first \
9484             calling `.copied()` on the iterator)"
9485        );
9486    }
9487
9488    #[test]
9489    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9490        // Fail-before-pass-after byte-parity pin on the newly lifted
9491        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9492        // the owned-input standard-library trait impl and the
9493        // substrate-primitive [`super::RestartStrategy::as_str`]
9494        // `pub const fn` accessor resolve to the same four-arm emit-
9495        // set across every arm the exhaustive
9496        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9497        // substrate-wide [`std::sync::Arc<str>`] forward-projection
9498        // campaign tier on the first M2 OTP-shape closed-set fieldless
9499        // typed enum peer on the caixa surface
9500        // (`:supervisor :estrategia`), immediately after the paired
9501        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9502        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9503        // Box<str>}` 2×4 corner on this enum. Rust's standard library
9504        // carries `impl From<&str> for std::sync::Arc<str>` and
9505        // `impl From<String> for std::sync::Arc<str>` but no blanket
9506        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9507        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9508        // so this axis is a distinct trait-idiomatic surface that a
9509        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9510        // site reaches through this impl and no other — a paired
9511        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9512        // has no compile-time link back to the substrate primitive,
9513        // and a two-step `std::sync::Arc::<str>::from(String::from(
9514        // strategy))` composition through the owned-`String` axis
9515        // allocates twice (once into the intermediate `String`, once
9516        // into the [`Arc<str>`] on the `From<String>` conversion)
9517        // where the single-step trait impl allocates once.
9518        //
9519        // Cross-axis byte-parity witness against the sibling owned-
9520        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9521        // return-shape axes — locking the five return-shape paths on
9522        // the owned-input surface together by construction so any
9523        // future detour off the substrate-primitive
9524        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9525        // core test time.
9526        for &variant in RestartStrategy::ALL {
9527            let via_trait: std::sync::Arc<str> =
9528                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9529            let via_method: &'static str = variant.as_str();
9530            assert_eq!(
9531                via_trait.as_ref(),
9532                via_method,
9533                "From<RestartStrategy> for std::sync::Arc<str> impl \
9534                 must round-trip RestartStrategy::{variant:?} to the \
9535                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9536                 RestartStrategy::as_str returns — divergence signals \
9537                 a silent detour off the substrate-primitive accessor"
9538            );
9539            let via_into: std::sync::Arc<str> = variant.into();
9540            assert_eq!(
9541                via_into.as_ref(),
9542                via_method,
9543                "Into<std::sync::Arc<str>>::into on \
9544                 RestartStrategy::{variant:?} must byte-equal \
9545                 RestartStrategy::as_str on the same input — the \
9546                 blanket-derived Into shape must resolve to the same \
9547                 as_str dispatch as the explicit From impl"
9548            );
9549            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9550            assert_eq!(
9551                via_trait.as_ref(),
9552                owned_static,
9553                "From<RestartStrategy> for std::sync::Arc<str> and \
9554                 From<RestartStrategy> for &'static str must resolve \
9555                 identically on RestartStrategy::{variant:?} — \
9556                 divergence signals the owned-input std::sync::Arc<str> \
9557                 and &'static str return-shape paths have drifted onto \
9558                 different emit-sets"
9559            );
9560            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9561            assert_eq!(
9562                via_trait.as_ref(),
9563                owned_string.as_str(),
9564                "From<RestartStrategy> for std::sync::Arc<str> and \
9565                 From<RestartStrategy> for String must resolve \
9566                 identically on RestartStrategy::{variant:?} — \
9567                 divergence signals the owned-input std::sync::Arc<str> \
9568                 and owned-`String` return-shape paths have drifted \
9569                 onto different emit-sets"
9570            );
9571            let owned_cow: std::borrow::Cow<'static, str> =
9572                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9573            assert_eq!(
9574                via_trait.as_ref(),
9575                owned_cow.as_ref(),
9576                "From<RestartStrategy> for std::sync::Arc<str> and \
9577                 From<RestartStrategy> for Cow<'static, str> must \
9578                 resolve identically on RestartStrategy::{variant:?} — \
9579                 divergence signals the owned-input std::sync::Arc<str> \
9580                 and Cow<'static, str> return-shape paths have drifted \
9581                 onto different emit-sets"
9582            );
9583            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9584            assert_eq!(
9585                via_trait.as_ref(),
9586                owned_box.as_ref(),
9587                "From<RestartStrategy> for std::sync::Arc<str> and \
9588                 From<RestartStrategy> for Box<str> must resolve \
9589                 identically on RestartStrategy::{variant:?} — \
9590                 divergence signals the owned-input std::sync::Arc<str> \
9591                 and Box<str> return-shape paths have drifted onto \
9592                 different emit-sets"
9593            );
9594        }
9595    }
9596
9597    #[test]
9598    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
9599        // Fail-before-pass-after byte-parity pin on the newly lifted
9600        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
9601        // asserts the borrowed-input standard-library trait impl and
9602        // the substrate-primitive [`super::RestartStrategy::as_str`]
9603        // `pub const fn` accessor resolve to the same four-arm emit-
9604        // set across every arm the exhaustive
9605        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9606        // standard library does not carry a blanket
9607        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
9608        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9609        // so the borrowed-input [`std::sync::Arc<str>`] forward-
9610        // projection axis is a distinct trait-idiomatic surface that a
9611        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
9612        // call site or a
9613        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
9614        // shaped pipe reaches through this impl and no other — the
9615        // paired owned-input
9616        // `From<RestartStrategy> for std::sync::Arc<str>` impl
9617        // (bca2ec8) forces every borrowed-input call site through an
9618        // explicit `Copy` deref
9619        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
9620        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9621        // whose type bounds have no compile-time link back to the
9622        // substrate primitive.
9623        //
9624        // Second peer on the substrate-wide trait-idiomatic
9625        // [`std::sync::Arc<str>`] forward-projection family on this
9626        // enum — closes the `{Self, &Self}` input-shape corner of
9627        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
9628        // closed-set fieldless typed enum peer on the caixa surface
9629        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
9630        // paired [`Box<str>`] axis one commit after its owning half
9631        // (69ef45c) landed. Every future closed-set fieldless typed
9632        // enum peer on the substrate is a future target of the
9633        // campaign.
9634        //
9635        // Also byte-parity witness against the paired owned-input
9636        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
9637        // sibling borrowed-input
9638        // [`From<&RestartStrategy> for &'static str`],
9639        // [`From<&RestartStrategy> for String`],
9640        // [`From<&RestartStrategy> for Cow<'static, str>`], and
9641        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
9642        // locking the five return-shape × input-shape paths together
9643        // by construction so any future detour trips at caixa-core
9644        // test time. Then a
9645        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
9646        // [`super::RestartStrategy::ALL`] — whose iterator yields
9647        // `&RestartStrategy` by construction, so the borrowed-input
9648        // [`std::sync::Arc<str>`] axis is what routes the pipe
9649        // through the substrate-primitive
9650        // [`super::RestartStrategy::as_str`] accessor without a
9651        // spurious [`Copy`] deref (which would only be reachable
9652        // through the owned-input
9653        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
9654        // first calling `.copied()` on the iterator).
9655        for &variant in RestartStrategy::ALL {
9656            let via_trait: std::sync::Arc<str> =
9657                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
9658            let via_method: &'static str = variant.as_str();
9659            assert_eq!(
9660                via_trait.as_ref(),
9661                via_method,
9662                "From<&RestartStrategy> for std::sync::Arc<str> impl \
9663                 must round-trip &RestartStrategy::{variant:?} to the \
9664                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9665                 RestartStrategy::as_str returns — divergence signals \
9666                 a silent detour off the substrate-primitive accessor"
9667            );
9668            let via_into: std::sync::Arc<str> = (&variant).into();
9669            assert_eq!(
9670                via_into.as_ref(),
9671                via_method,
9672                "Into<std::sync::Arc<str>>::into on \
9673                 &RestartStrategy::{variant:?} must byte-equal \
9674                 RestartStrategy::as_str on the same input — the \
9675                 blanket-derived Into shape must resolve to the same \
9676                 as_str dispatch as the explicit From impl"
9677            );
9678            let owned_arc: std::sync::Arc<str> =
9679                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9680            assert_eq!(
9681                via_trait, owned_arc,
9682                "From<&RestartStrategy> for std::sync::Arc<str> and \
9683                 From<RestartStrategy> for std::sync::Arc<str> must \
9684                 resolve identically on RestartStrategy::{variant:?} — \
9685                 divergence signals the borrowed-input and owned-input \
9686                 std::sync::Arc<str> forward-projection input-shape \
9687                 paths have drifted onto different emit-sets"
9688            );
9689            let borrowed_static: &'static str =
9690                <&'static str as From<&RestartStrategy>>::from(&variant);
9691            assert_eq!(
9692                via_trait.as_ref(),
9693                borrowed_static,
9694                "From<&RestartStrategy> for std::sync::Arc<str> and \
9695                 From<&RestartStrategy> for &'static str must resolve \
9696                 identically on RestartStrategy::{variant:?} — \
9697                 divergence signals the borrowed-input \
9698                 std::sync::Arc<str> and &'static str return-shape \
9699                 paths have drifted onto different emit-sets"
9700            );
9701            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9702            assert_eq!(
9703                via_trait.as_ref(),
9704                borrowed_string.as_str(),
9705                "From<&RestartStrategy> for std::sync::Arc<str> and \
9706                 From<&RestartStrategy> for String must resolve \
9707                 identically on RestartStrategy::{variant:?} — \
9708                 divergence signals the borrowed-input \
9709                 std::sync::Arc<str> and owned-`String` return-shape \
9710                 paths have drifted onto different emit-sets"
9711            );
9712            let borrowed_cow: std::borrow::Cow<'static, str> =
9713                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9714            assert_eq!(
9715                via_trait.as_ref(),
9716                borrowed_cow.as_ref(),
9717                "From<&RestartStrategy> for std::sync::Arc<str> and \
9718                 From<&RestartStrategy> for Cow<'static, str> must \
9719                 resolve identically on RestartStrategy::{variant:?} — \
9720                 divergence signals the borrowed-input \
9721                 std::sync::Arc<str> and Cow<'static, str> return-shape \
9722                 paths have drifted onto different emit-sets"
9723            );
9724            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9725            assert_eq!(
9726                via_trait.as_ref(),
9727                borrowed_box.as_ref(),
9728                "From<&RestartStrategy> for std::sync::Arc<str> and \
9729                 From<&RestartStrategy> for Box<str> must resolve \
9730                 identically on RestartStrategy::{variant:?} — \
9731                 divergence signals the borrowed-input \
9732                 std::sync::Arc<str> and Box<str> return-shape paths \
9733                 have drifted onto different emit-sets"
9734            );
9735        }
9736        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9737            .iter()
9738            .map(std::sync::Arc::<str>::from)
9739            .collect();
9740        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9741            .iter()
9742            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
9743            .collect();
9744        assert_eq!(
9745            via_iter, via_method,
9746            "`.iter().map(std::sync::Arc::<str>::from)` over \
9747             RestartStrategy::ALL — a call site whose iteration axis \
9748             holds `&RestartStrategy` by construction — must byte-\
9749             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
9750             on every arm — the borrowed-input std::sync::Arc<str> \
9751             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
9752             what makes the `std::sync::Arc::<str>::from` composition \
9753             route through the substrate-primitive \
9754             `RestartStrategy::as_str` accessor without a spurious \
9755             `Copy` deref (which would only be reachable through the \
9756             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
9757             axis by first calling `.copied()` on the iterator)"
9758        );
9759    }
9760
9761    #[test]
9762    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9763        // Fail-before-pass-after byte-parity pin on the newly lifted
9764        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9765        // library trait impl and the substrate-primitive
9766        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9767        // the same three-arm accept-set across every arm the exhaustive
9768        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9769        // detour that routes the trait impl through a divergent
9770        // projection (a per-arm inline `match s { "Permanent" =>
9771        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9772        // link to the un-lifted arm-literal, a hypothetical
9773        // `#[serde(rename_all = "…")]` attribute drift that silently
9774        // splits the wire byte-string from every consumer that reaches
9775        // for this typed dispatch, an accidental swap onto the kebab-case
9776        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9777        // impl parses through and which would collide the two-axis
9778        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9779        // doc block makes load-bearing) trips at caixa-core test time
9780        // under `assert_eq!` rather than at a downstream
9781        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9782        // every one of the three arms [`RestartPolicy::ALL`] carries so
9783        // no arm's projection is covered only by the sibling method-
9784        // named `from_wire` path. Peer of the sibling
9785        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9786        // (5b828ed) — extends the trait-idiomatic reverse-projection
9787        // axis onto the third and final M2-OTP-shape closed-set typed
9788        // enum on the caixa surface (the paired per-child restart-
9789        // decision-policy sibling on the same M2 `:supervisor` slot).
9790        for &variant in RestartPolicy::ALL {
9791            let wire = variant.as_str();
9792            assert_eq!(
9793                <RestartPolicy as TryFrom<&str>>::try_from(wire),
9794                Ok(variant),
9795                "TryFrom<&str> impl on RestartPolicy must round-trip \
9796                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9797                 Ok(RestartPolicy::{variant:?}) — divergence from \
9798                 RestartPolicy::from_wire signals a silent detour off \
9799                 the substrate-primitive accessor"
9800            );
9801            assert_eq!(
9802                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9803                RestartPolicy::from_wire(wire),
9804                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9805                 equal RestartPolicy::from_wire on the same input"
9806            );
9807        }
9808    }
9809
9810    #[test]
9811    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9812        // Rejection witness on the `impl TryFrom<&str> for
9813        // RestartPolicy` — sweeps a candidate set of byte-strings
9814        // outside the three-arm PascalCase wire accept-set the sibling
9815        // [`RestartPolicy::as_str`] emits and asserts every one lands on
9816        // `Err(())`, so a future accidental widening of the trait impl's
9817        // accept-set (a stray additional
9818        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9819        // path, a silent inclusion of the kebab-case dispatcher-catalog
9820        // byte-string the pre-existing [`std::str::FromStr`] impl the
9821        // [`gen_platform::FromStrKind`] derive installs parses onto the
9822        // wire axis — which would collide the two-axis
9823        // wire/dispatcher-catalog split the sibling
9824        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9825        // an English-rebrand or plural-arm silent alias that would widen
9826        // the wire accept-set past the OTP-canonical three) trips at
9827        // caixa-core test time. The candidate set includes the empty
9828        // string, whitespace-only padding, the kebab-case dispatcher-
9829        // catalog byte-strings on the sibling axis (a caller who
9830        // confuses the two axes trips here rather than at a downstream
9831        // consumer's silent reject), a lowercase / uppercase / mixed-case
9832        // fold of each PascalCase arm (a caller who assumes case-fold
9833        // acceptance trips here), leading/trailing whitespace padding,
9834        // the trailing-newline shape, quote-wrapped candidates, and a
9835        // residual set of plausible-but-wrong English rebrand
9836        // candidates. Peer of the sibling
9837        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9838        // (5b828ed) rejection witness.
9839        let rejected: &[&str] = &[
9840            "",
9841            " ",
9842            "\n",
9843            "\t",
9844            "permanent",
9845            "temporary",
9846            "transient",
9847            "PERMANENT",
9848            "TEMPORARY",
9849            "TRANSIENT",
9850            "Permanents",
9851            "Permanent ",
9852            " Permanent",
9853            " Temporary ",
9854            "Permanent\n",
9855            "Transient\t",
9856            "\"Permanent\"",
9857            "Ephemeral",
9858            "Always",
9859            "Never",
9860            "OnAbnormalExit",
9861            "intrinsic",
9862            "?",
9863        ];
9864        for &input in rejected {
9865            assert_eq!(
9866                <RestartPolicy as TryFrom<&str>>::try_from(input),
9867                Err(()),
9868                "TryFrom<&str> impl on RestartPolicy must reject the \
9869                 non-wire byte-string {input:?} — silent acceptance \
9870                 signals an accept-set widening off the paired \
9871                 RestartPolicy::from_wire resolver"
9872            );
9873        }
9874    }
9875
9876    #[test]
9877    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9878        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9879        // `from_wire` reverse projections must resolve identically on
9880        // *every* input, not just the ones [`RestartPolicy::ALL`]
9881        // enumerates. Sweeps a mixed candidate set spanning accepted
9882        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9883        // case dispatcher-catalog byte-strings, empty, whitespace-
9884        // padded, quoted, English-rebrand candidates) inputs and asserts
9885        // the trait's `Result::ok()` projection byte-equals the method-
9886        // named resolver's `Option<Self>` return-shape on each, locking
9887        // the two paths together by construction so any future detour
9888        // (a stray `try_from` special-case that widens or narrows the
9889        // accept-set outside the paired `from_wire` resolver, an
9890        // accidental swap onto the kebab-case [`std::str::FromStr`]
9891        // impl the [`gen_platform::FromStrKind`] derive installs on the
9892        // sibling dispatcher-catalog axis) trips at caixa-core test
9893        // time. Peer of the sibling
9894        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9895        // pin — extends the round-trip discipline onto the M2-OTP-shape
9896        // per-child restart-policy axis.
9897        let candidates: &[&str] = &[
9898            "Permanent",
9899            "Temporary",
9900            "Transient",
9901            "",
9902            "permanent",
9903            "temporary",
9904            "transient",
9905            "PERMANENT",
9906            "unknown",
9907            "Permanent ",
9908            " Permanent",
9909            "\"Permanent\"",
9910            "Ephemeral",
9911            "OnAbnormalExit",
9912            "?",
9913        ];
9914        for &input in candidates {
9915            let via_trait: Option<RestartPolicy> =
9916                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9917            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9918            assert_eq!(
9919                via_trait, via_method,
9920                "TryFrom<&str> and from_wire must resolve identically on \
9921                 input {input:?} — divergence signals the two reverse-\
9922                 projection paths have drifted onto different accept-sets"
9923            );
9924        }
9925    }
9926
9927    #[test]
9928    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9929        // Fail-before-pass-after byte-parity pin on the newly lifted
9930        // `impl From<RestartPolicy> for &'static str` — asserts the
9931        // standard-library trait impl and the substrate-primitive
9932        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9933        // the same three-arm emit-set across every arm the exhaustive
9934        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9935        // detour that routes the trait impl through a divergent
9936        // projection (a per-arm inline `match policy { Permanent =>
9937        // "Permanent", … }` re-inlining that opens a compile-time link
9938        // to the un-lifted arm-literal, an accidental swap onto the
9939        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9940        // axis that would collide the two-axis wire/catalog split the
9941        // sibling [`RestartPolicy::from_wire`] doc block makes
9942        // load-bearing) trips at caixa-core test time under
9943        // `assert_eq!` rather than at a downstream
9944        // `impl Into<&'static str>`-bound consumer's silent split.
9945        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9946        // carries so no arm's projection is covered only by the sibling
9947        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9948        // paths. Materializes the `<&'static str as
9949        // From<RestartPolicy>>::from` output in a `const`-shape binding
9950        // to make the `'static` lifetime promise a build-time invariant
9951        // — a future accidental downgrade of any of the three arms'
9952        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9953        // non-`&'static str` (a `String::leak()`-produced return, a
9954        // `Box::leak`-cast) trips at caixa-core build time rather than
9955        // at a downstream `'static`-bound consumer. Peer of the sibling
9956        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9957        // (523157d) — extends the trait-idiomatic forward-projection
9958        // axis onto the second (and second-of-two-in-M2) closed-set
9959        // typed enum on the caixa surface (the paired per-child
9960        // restart-decision-policy sibling on the same M2 `:supervisor`
9961        // slot).
9962        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9963        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9964        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9965        for &variant in RestartPolicy::ALL {
9966            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9967            let via_method: &'static str = variant.as_str();
9968            assert_eq!(
9969                via_trait, via_method,
9970                "From<RestartPolicy> for &'static str impl must round-trip \
9971                 RestartPolicy::{variant:?} to the same lifted \
9972                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9973                 divergence signals a silent detour off the substrate-primitive \
9974                 accessor"
9975            );
9976            let via_into: &'static str = variant.into();
9977            assert_eq!(
9978                via_into, via_method,
9979                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9980                 byte-equal RestartPolicy::as_str on the same input — the \
9981                 blanket-derived Into shape must resolve to the same as_str \
9982                 dispatch as the explicit From impl"
9983            );
9984        }
9985        assert_eq!(
9986            [PERMANENT, TEMPORARY, TRANSIENT],
9987            [
9988                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9989                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9990                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9991            ],
9992            "const-context RestartPolicy::as_str must resolve to the three \
9993             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9994             downgrade of any arm to a non-const or non-static byte-string \
9995             breaks the `&'static str`-lifetime promise the paired \
9996             From<RestartPolicy> for &'static str impl carries by \
9997             construction"
9998        );
9999    }
10000
10001    #[test]
10002    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10003        // Cross-axis partition pin: the paired trait-idiomatic
10004        // `From<RestartPolicy> for &'static str` forward projection and
10005        // the method-named [`RestartPolicy::as_str`] forward projection
10006        // must resolve identically on *every* arm, not just the ones
10007        // named in the primary byte-parity pin above. Sweeps every
10008        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10009        // output byte-equals the method-named accessor's return-value on
10010        // each, locking the two forward-projection paths together by
10011        // construction so any future detour (a stray `From` special-case
10012        // that lands on a divergent per-arm literal outside the paired
10013        // `as_str` dispatch, a hypothetical rebrand touching one axis
10014        // without the other) trips at caixa-core test time. Peer of the
10015        // sibling forward-projection partition pin
10016        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10017        // (523157d) — extends the round-trip discipline onto the
10018        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10019        // surface, closing the two-way `Self ↔ &'static str` round-trip
10020        // on the trait-idiomatic pair (`From<Self> for &'static str` +
10021        // `TryFrom<&str> for Self`) as well as the pre-existing method-
10022        // named pair (`as_str` + `from_wire`).
10023        for &variant in RestartPolicy::ALL {
10024            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10025            let via_method: &'static str = variant.as_str();
10026            assert_eq!(
10027                via_trait, via_method,
10028                "From<RestartPolicy> for &'static str and \
10029                 RestartPolicy::as_str must resolve identically on \
10030                 RestartPolicy::{variant:?} — divergence signals the \
10031                 two forward-projection paths have drifted onto different \
10032                 emit-sets"
10033            );
10034        }
10035        // Round-trip witness: every arm's forward `From` output re-parses
10036        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10037        // to the original variant. Closes the two-way `RestartPolicy ↔
10038        // &'static str` round-trip on the trait-idiomatic axis pair,
10039        // mirroring the pre-existing method-named `as_str` + `from_wire`
10040        // round-trip on the substrate-primitive axis pair.
10041        for &variant in RestartPolicy::ALL {
10042            let emitted: &'static str = variant.into();
10043            let re_parsed: Result<RestartPolicy, ()> =
10044                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10045            assert_eq!(
10046                re_parsed,
10047                Ok(variant),
10048                "trait-idiomatic axis pair must round-trip \
10049                 RestartPolicy::{variant:?} through `.into::<&'static \
10050                 str>()` and back through `TryFrom<&str>` — a break signals \
10051                 the forward-emit and reverse-parse axes have drifted onto \
10052                 different vocabularies"
10053            );
10054        }
10055    }
10056
10057    #[test]
10058    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10059        // Fail-before-pass-after byte-parity pin on the newly lifted
10060        // `impl From<&RestartPolicy> for &'static str` — asserts the
10061        // borrowed-input standard-library trait impl and the substrate-
10062        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10063        // resolve to the same three-arm emit-set across every arm the
10064        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10065        // `From` trait does not auto-derive the borrowed-input sibling
10066        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10067        // where T: Copy, U: From<T>` blanket in `core`), so the
10068        // borrowed-input axis is a distinct trait-idiomatic surface
10069        // that a `.iter().map(Into::into)` shape over
10070        // [`RestartPolicy::ALL`] (whose iterator yields
10071        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10072        // impl and no other — the paired owned-input
10073        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10074        // / dereference before the trait fires. Materializes the
10075        // `<&'static str as From<&RestartPolicy>>::from` output in a
10076        // `const`-shape binding to make the `'static` lifetime promise
10077        // a build-time invariant.
10078        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10079        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10080        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10081        for variant in RestartPolicy::ALL {
10082            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10083            let via_method: &'static str = variant.as_str();
10084            assert_eq!(
10085                via_trait, via_method,
10086                "From<&RestartPolicy> for &'static str impl must round-trip \
10087                 &RestartPolicy::{variant:?} to the same lifted \
10088                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10089                 returns — divergence signals a silent detour off the \
10090                 substrate-primitive accessor"
10091            );
10092            let via_into: &'static str = variant.into();
10093            assert_eq!(
10094                via_into, via_method,
10095                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10096                 must byte-equal RestartPolicy::as_str on the same input — \
10097                 the blanket-derived Into shape must resolve to the same \
10098                 as_str dispatch as the explicit From impl"
10099            );
10100        }
10101        assert_eq!(
10102            [PERMANENT, TEMPORARY, TRANSIENT],
10103            [
10104                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10105                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10106                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10107            ],
10108            "const-context RestartPolicy::as_str must resolve to the three \
10109             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10110             From<&RestartPolicy> for &'static str impl inherits its \
10111             `'static` lifetime promise from the same accessor the \
10112             owned-input sibling routes through"
10113        );
10114    }
10115
10116    #[test]
10117    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10118        // Cross-axis partition pin: the paired trait-idiomatic
10119        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10120        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10121        // &'static str` (this lift) forward projections must resolve
10122        // identically on every arm, locking the two input-shape paths
10123        // together so any future detour trips at caixa-core test time.
10124        // Then a witness that a `.iter().map(Into::into)` pipe over
10125        // [`RestartPolicy::ALL`] (whose iterator yields
10126        // `&RestartPolicy`) materializes the three-arm accept-set
10127        // through the borrowed-input axis alone — the exact shape a
10128        // future wasm-operator per-child post-exit restart-decision
10129        // diagnostic line, a future substrate-wide per-arm diagnostic
10130        // column, or a
10131        // `HashMap::<&'static str, RestartPolicy>::from_iter(
10132        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10133        // per-policy lookup reaches through — closing the two-way
10134        // owned/borrowed input-shape symmetry on the forward-projection
10135        // trait-idiomatic axis. Peer of the sibling
10136        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10137        // (64aa742) /
10138        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10139        // (5ab993a) /
10140        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10141        // (807b0b5) /
10142        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10143        // (e941836) partition pins on the sibling closed-set typed-enum
10144        // discriminator axes — extends the borrowed-input axis
10145        // discipline onto the second-of-two M2 OTP-shape closed-set
10146        // typed enum on the caixa surface (per-child restart-decision
10147        // policy). Also closes the direct two-way `&Self → &'static
10148        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10149        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10150        // forward `From` emits lowercase Portuguese diagnostic bytes
10151        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10152        // forcing the round-trip through an intermediate wire-vocab
10153        // hop), the [`RestartPolicy::as_str`] emit and
10154        // [`RestartPolicy::from_wire`] parse share the same
10155        // `PascalCase` vocabulary by construction, so the borrowed-
10156        // input forward axis and the reverse axis compose directly.
10157        for &variant in RestartPolicy::ALL {
10158            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10159            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10160            assert_eq!(
10161                owned, borrowed,
10162                "From<RestartPolicy> and From<&RestartPolicy> for \
10163                 &'static str must resolve identically on \
10164                 RestartPolicy::{variant:?} — divergence signals the \
10165                 owned-input and borrowed-input forward-projection paths \
10166                 have drifted onto different emit-sets"
10167            );
10168        }
10169        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10170        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10171        assert_eq!(
10172            via_iter, via_method,
10173            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10174             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10175             borrowed-input `From<&RestartPolicy> for &'static str` axis \
10176             is what makes the `.iter().map(Into::into)` shape route \
10177             through the substrate-primitive `RestartPolicy::as_str` \
10178             accessor rather than through a per-call-site `.copied()` / \
10179             dereference detour"
10180        );
10181        for variant in RestartPolicy::ALL {
10182            let emitted: &'static str = variant.into();
10183            let re_parsed: Result<RestartPolicy, ()> =
10184                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10185            assert_eq!(
10186                re_parsed,
10187                Ok(*variant),
10188                "trait-idiomatic borrowed-input forward-projection + \
10189                 reverse-projection axis pair must round-trip \
10190                 &RestartPolicy::{variant:?} through `.into::<&'static \
10191                 str>()` (via the borrowed-input axis) and back through \
10192                 `TryFrom<&str>` — a break signals the borrowed-input \
10193                 forward-emit and reverse-parse axes have drifted onto \
10194                 different vocabularies"
10195            );
10196        }
10197    }
10198
10199    #[test]
10200    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10201        // Fail-before-pass-after byte-parity pin on the newly lifted
10202        // `impl From<RestartPolicy> for String` — asserts the
10203        // owned-`String`-returning standard-library trait impl and the
10204        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10205        // accessor resolve to the same three-arm emit-set across every
10206        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10207        // Rust's standard library does not carry a blanket
10208        // `impl<T: AsRef<str>> From<T> for String` (nor an
10209        // `impl<T: fmt::Display> From<T> for String`), so the
10210        // owned-`String` forward-projection axis is a distinct
10211        // trait-idiomatic surface that a `let key: String =
10212        // policy.into();`-shaped call site reaches through this impl
10213        // and no other — the paired sibling `From<RestartPolicy> for
10214        // &'static str` impl forces every owned-`String` call site
10215        // through an explicit `.to_owned()` / `String::from`
10216        // restatement. Peer of the first-mover
10217        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10218        // (7baa18a) — extends the trait-idiomatic owned-`String`
10219        // forward-projection axis onto the second-of-two M2 OTP-shape
10220        // closed-set typed enums on the caixa surface (per-child
10221        // restart-decision-policy sibling on the same M2 `:supervisor`
10222        // slot).
10223        for &variant in RestartPolicy::ALL {
10224            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10225            let via_method: &'static str = variant.as_str();
10226            assert_eq!(
10227                via_trait.as_str(),
10228                via_method,
10229                "From<RestartPolicy> for String impl must round-trip \
10230                 RestartPolicy::{variant:?} to the same lifted \
10231                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10232                 returns — divergence signals a silent detour off the \
10233                 substrate-primitive accessor"
10234            );
10235            let via_into: String = variant.into();
10236            assert_eq!(
10237                via_into.as_str(),
10238                via_method,
10239                "Into<String>::into on RestartPolicy::{variant:?} must \
10240                 byte-equal RestartPolicy::as_str on the same input — the \
10241                 blanket-derived Into shape must resolve to the same as_str \
10242                 dispatch as the explicit From impl"
10243            );
10244        }
10245    }
10246
10247    #[test]
10248    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10249        // Cross-axis partition pin: the paired trait-idiomatic
10250        // owned-`String` `From<RestartPolicy> for String` (this lift)
10251        // and owned-`&'static str` `From<RestartPolicy> for &'static
10252        // str` (9fb37d0) forward projections must resolve identically
10253        // on every arm, locking the two return-type-shape paths
10254        // together so any future detour trips at caixa-core test time.
10255        // Also byte-parity witness against the sibling
10256        // [`ToString::to_string`] surface routed through
10257        // [`std::fmt::Display`] — the three owned-heap-string paths
10258        // (`.into::<String>()`, `String::from`, `.to_string()`) must
10259        // resolve identically on every arm so a future consumer that
10260        // picks any of the three lands on the same lifted
10261        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10262        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10263        // that materializes the three-arm accept-set through the
10264        // owned-`String` axis alone — the exact shape a future
10265        // wasm-operator per-child post-exit restart-decision
10266        // diagnostic line composer or a
10267        // `HashMap::<String, RestartPolicy>::from_iter(
10268        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10269        // owned-key per-policy lookup reaches through — closing the
10270        // owned-`String` forward-projection axis's iterator-pipe
10271        // shape. Then a direct round-trip witness through the paired
10272        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10273        // owned-`String`'s [`String::as_str`] borrow that closes the
10274        // two-way `Self → String → Self` round-trip on the trait-
10275        // idiomatic owned-`String` forward + reverse axis pair —
10276        // unlike the peer [`crate::CaixaKind`] axis pair (whose
10277        // forward `From` emits lowercase Portuguese diagnostic bytes
10278        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10279        // forcing the round-trip through an intermediate wire-vocab
10280        // hop), the [`RestartPolicy::as_str`] emit and
10281        // [`RestartPolicy::from_wire`] parse share the same
10282        // `PascalCase` vocabulary by construction, so the owned-
10283        // `String` forward axis and the reverse axis compose directly.
10284        for &variant in RestartPolicy::ALL {
10285            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10286            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10287            assert_eq!(
10288                owned_string.as_str(),
10289                owned_static,
10290                "From<RestartPolicy> for String and From<RestartPolicy> \
10291                 for &'static str must resolve identically on \
10292                 RestartPolicy::{variant:?} — divergence signals the \
10293                 owned-`String` and owned-`&'static str` forward-projection \
10294                 return-type-shape paths have drifted onto different \
10295                 emit-sets"
10296            );
10297            let via_to_string: String = variant.to_string();
10298            assert_eq!(
10299                owned_string, via_to_string,
10300                "From<RestartPolicy> for String must byte-equal \
10301                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10302                 divergence signals the trait-idiomatic owned-`String` \
10303                 forward-projection axis and the ToString-through-Display \
10304                 axis have drifted onto different emit-sets"
10305            );
10306        }
10307        let via_iter: Vec<String> = RestartPolicy::ALL
10308            .iter()
10309            .copied()
10310            .map(String::from)
10311            .collect();
10312        let via_method: Vec<String> = RestartPolicy::ALL
10313            .iter()
10314            .map(|p| p.as_str().to_owned())
10315            .collect();
10316        assert_eq!(
10317            via_iter, via_method,
10318            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10319             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10320             every arm — the owned-`String` `From<RestartPolicy> for \
10321             String` axis is what makes the `String::from` composition \
10322             route through the substrate-primitive `RestartPolicy::as_str` \
10323             accessor rather than through a per-call-site `.to_owned()` / \
10324             `String::from(policy.as_str())` detour"
10325        );
10326        for &variant in RestartPolicy::ALL {
10327            let emitted: String = variant.into();
10328            let re_parsed: Result<RestartPolicy, ()> =
10329                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10330            assert_eq!(
10331                re_parsed,
10332                Ok(variant),
10333                "trait-idiomatic owned-`String` forward-projection + \
10334                 reverse-projection axis pair must round-trip \
10335                 RestartPolicy::{variant:?} through `.into::<String>()` \
10336                 and back through `TryFrom<&str>` on the owned-`String`'s \
10337                 String::as_str borrow — a break signals the owned-`String` \
10338                 forward-emit and reverse-parse axes have drifted onto \
10339                 different vocabularies"
10340            );
10341        }
10342    }
10343
10344    #[test]
10345    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10346        // Fail-before-pass-after byte-parity pin on the newly lifted
10347        // `impl From<&RestartPolicy> for String` — asserts the
10348        // borrowed-input owned-`String`-returning standard-library
10349        // trait impl and the substrate-primitive
10350        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10351        // the same three-arm emit-set across every arm the exhaustive
10352        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10353        // library does not carry a blanket `impl<T: AsRef<str>>
10354        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10355        // for String`), so the borrowed-input owned-`String` forward-
10356        // projection axis is a distinct trait-idiomatic surface that a
10357        // `let key: String = (&policy).into();`-shaped call site
10358        // reaches through this impl and no other — the paired sibling
10359        // `From<RestartPolicy> for String` impl forces every borrowed-
10360        // input call site through an explicit `Copy` deref
10361        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10362        // `.to_string()` detour. Peer of the first-mover
10363        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10364        // (579385f) — extends the trait-idiomatic borrowed-input
10365        // owned-`String` forward-projection axis onto the second-of-
10366        // two M2 OTP-shape closed-set typed enums on the caixa surface
10367        // (per-child restart-decision-policy sibling on the same M2
10368        // `:supervisor` slot).
10369        for &variant in RestartPolicy::ALL {
10370            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10371            let via_method: &'static str = variant.as_str();
10372            assert_eq!(
10373                via_trait.as_str(),
10374                via_method,
10375                "From<&RestartPolicy> for String impl must round-trip \
10376                 &RestartPolicy::{variant:?} to the same lifted \
10377                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10378                 returns — divergence signals a silent detour off the \
10379                 substrate-primitive accessor"
10380            );
10381            let via_into: String = (&variant).into();
10382            assert_eq!(
10383                via_into.as_str(),
10384                via_method,
10385                "Into<String>::into on &RestartPolicy::{variant:?} must \
10386                 byte-equal RestartPolicy::as_str on the same input — \
10387                 the blanket-derived Into shape must resolve to the \
10388                 same as_str dispatch as the explicit From impl"
10389            );
10390        }
10391    }
10392
10393    #[test]
10394    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10395        // Cross-axis partition pin: the newly lifted trait-idiomatic
10396        // borrowed-input owned-`String` `From<&RestartPolicy> for
10397        // String` (this lift), the paired owned-input owned-`String`
10398        // `From<RestartPolicy> for String` (7851725), the paired
10399        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10400        // for &'static str` (842c7f3), and the paired owned-input
10401        // owned-`&'static str` `From<RestartPolicy> for &'static str`
10402        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10403        // str, String}` 2×2 trait-idiomatic projection family — must
10404        // resolve identically on every arm, locking the four
10405        // return-shape × input-shape paths together so any future
10406        // detour trips at caixa-core test time. Also byte-parity
10407        // witness against the sibling [`ToString::to_string`] surface
10408        // routed through [`std::fmt::Display`] and a direct round-trip
10409        // witness through the paired trait-idiomatic reverse
10410        // [`TryFrom<&str>`] axis on the owned-`String`'s
10411        // [`String::as_str`] borrow that closes the two-way
10412        // `&Self → String → Self` round-trip on the trait-idiomatic
10413        // borrowed-input owned-`String` forward + reverse axis pair.
10414        // Peer of the first-mover
10415        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10416        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10417        // String}` 2×2 projection corner on both M2 OTP-shape sibling
10418        // peers.
10419        for &variant in RestartPolicy::ALL {
10420            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10421            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10422            let borrowed_static: &'static str =
10423                <&'static str as From<&RestartPolicy>>::from(&variant);
10424            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10425            assert_eq!(
10426                borrowed_string, owned_string,
10427                "From<&RestartPolicy> for String and From<RestartPolicy> \
10428                 for String must resolve identically on \
10429                 RestartPolicy::{variant:?} — divergence signals the \
10430                 borrowed-input and owned-input owned-`String` \
10431                 forward-projection input-shape paths have drifted onto \
10432                 different emit-sets"
10433            );
10434            assert_eq!(
10435                borrowed_string.as_str(),
10436                borrowed_static,
10437                "From<&RestartPolicy> for String and From<&RestartPolicy> \
10438                 for &'static str must resolve identically on \
10439                 RestartPolicy::{variant:?} — divergence signals the \
10440                 borrowed-input `&'static str` and owned-`String` \
10441                 return-shape paths have drifted onto different \
10442                 emit-sets"
10443            );
10444            assert_eq!(
10445                borrowed_string.as_str(),
10446                owned_static,
10447                "From<&RestartPolicy> for String and From<RestartPolicy> \
10448                 for &'static str must resolve identically on \
10449                 RestartPolicy::{variant:?} — divergence signals a \
10450                 break in the diagonal corner of the {{Self, &Self}} × \
10451                 {{&'static str, String}} 2×2 trait-idiomatic \
10452                 projection family"
10453            );
10454            let via_to_string: String = variant.to_string();
10455            assert_eq!(
10456                borrowed_string, via_to_string,
10457                "From<&RestartPolicy> for String must byte-equal \
10458                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10459                 — divergence signals the trait-idiomatic borrowed-input \
10460                 owned-`String` forward-projection axis and the \
10461                 ToString-through-Display axis have drifted onto \
10462                 different emit-sets"
10463            );
10464        }
10465        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10466        let via_method: Vec<String> = RestartPolicy::ALL
10467            .iter()
10468            .map(|p| p.as_str().to_owned())
10469            .collect();
10470        assert_eq!(
10471            via_iter, via_method,
10472            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10473             call site whose iteration axis holds `&RestartPolicy` by \
10474             construction — must byte-equal `.iter().map(|p| \
10475             p.as_str().to_owned())` on every arm — the borrowed-input \
10476             owned-`String` `From<&RestartPolicy> for String` axis is \
10477             what makes the `String::from` composition route through \
10478             the substrate-primitive `RestartPolicy::as_str` accessor \
10479             without a spurious `Copy` deref (which would only be \
10480             reachable through the owned-input `From<RestartPolicy> \
10481             for String` axis by first calling `.copied()` on the \
10482             iterator)"
10483        );
10484        for &variant in RestartPolicy::ALL {
10485            let emitted: String = (&variant).into();
10486            let re_parsed: Result<RestartPolicy, ()> =
10487                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10488            assert_eq!(
10489                re_parsed,
10490                Ok(variant),
10491                "trait-idiomatic borrowed-input owned-`String` \
10492                 forward-projection + reverse-projection axis pair must \
10493                 round-trip &RestartPolicy::{variant:?} through \
10494                 `.into::<String>()` on the borrowed-input surface and \
10495                 back through `TryFrom<&str>` on the owned-`String`'s \
10496                 String::as_str borrow — a break signals the \
10497                 borrowed-input owned-`String` forward-emit and \
10498                 reverse-parse axes have drifted onto different \
10499                 vocabularies"
10500            );
10501        }
10502    }
10503
10504    #[test]
10505    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10506        // Fail-before-pass-after byte-parity pin on the newly lifted
10507        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10508        // asserts the standard-library trait impl and the substrate-
10509        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10510        // accessor resolve to the same three-arm emit-set across every
10511        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10512        // enumerates. Rust's standard library does not carry a blanket
10513        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10514        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10515        // the `Cow<'static, str>` forward-projection axis is a
10516        // distinct trait-idiomatic surface that a
10517        // `let key: Cow<'static, str> = policy.into();`-shaped call
10518        // site reaches through this impl and no other — the paired
10519        // sibling `From<RestartPolicy> for &'static str` and
10520        // `From<RestartPolicy> for String` impls force every
10521        // `Cow<'static, str>`-parameterized call site through a
10522        // `Cow::Borrowed(policy.as_str())` /
10523        // `Cow::Owned(policy.to_string())` composition whose type
10524        // bounds have no compile-time link back to the substrate
10525        // primitive.
10526        //
10527        // Also asserts the projection lands on the zero-alloc
10528        // [`std::borrow::Cow::Borrowed`] arm (not the
10529        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10530        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10531        // return lifetime by construction makes the borrowed arm the
10532        // type-correct projection with no runtime allocation. Any
10533        // future silent detour that routes the impl through the owned
10534        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10535        // that would allocate on every call site where the
10536        // `&'static str` return of [`super::RestartPolicy::as_str`]
10537        // makes the zero-alloc borrowed projection type-correct) trips
10538        // at caixa-core test time under the
10539        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10540        // than at a downstream `Cow<'static, str>`-bound consumer's
10541        // silent allocation.
10542        //
10543        // Second peer on the substrate-wide trait-idiomatic
10544        // [`std::borrow::Cow<'static, str>`] forward-projection family
10545        // to extend the axis off the top-level [`super::CaixaKind`]
10546        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10547        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10548        // fieldless typed enum peer on the caixa surface — closes the
10549        // M2 OTP-shape tier of the campaign on the owned-input axis
10550        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10551        // now carry the owned-input Cow<'static, str> forward
10552        // projection).
10553        for &variant in RestartPolicy::ALL {
10554            let via_trait: std::borrow::Cow<'static, str> =
10555                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10556            let via_method: &'static str = variant.as_str();
10557            assert_eq!(
10558                via_trait.as_ref(),
10559                via_method,
10560                "From<RestartPolicy> for Cow<'static, str> impl must \
10561                 round-trip RestartPolicy::{variant:?} to the same \
10562                 lifted SUPERVISOR_CHILD_RESTART_* const \
10563                 RestartPolicy::as_str returns — divergence signals a \
10564                 silent detour off the substrate-primitive accessor"
10565            );
10566            assert!(
10567                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10568                "From<RestartPolicy> for Cow<'static, str> impl must \
10569                 land on the zero-alloc Cow::Borrowed arm on \
10570                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10571                 signals the projection has silently allocated where \
10572                 the substrate-primitive RestartPolicy::as_str \
10573                 `&'static str` return makes the borrowed arm the \
10574                 type-correct projection"
10575            );
10576            let via_into: std::borrow::Cow<'static, str> = variant.into();
10577            assert_eq!(
10578                via_into.as_ref(),
10579                via_method,
10580                "Into<Cow<'static, str>>::into on \
10581                 RestartPolicy::{variant:?} must byte-equal \
10582                 RestartPolicy::as_str on the same input — the \
10583                 blanket-derived Into shape must resolve to the same \
10584                 as_str dispatch as the explicit From impl"
10585            );
10586            assert!(
10587                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10588                "Into<Cow<'static, str>>::into on \
10589                 RestartPolicy::{variant:?} must land on the \
10590                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10591                 Into shape must resolve to the same Cow::Borrowed \
10592                 dispatch as the explicit From impl"
10593            );
10594        }
10595    }
10596
10597    #[test]
10598    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10599        // Cross-axis partition pin: the newly lifted trait-idiomatic
10600        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10601        // (this lift), the paired owned-input `From<RestartPolicy>
10602        // for &'static str` (9fb37d0), and the paired owned-input
10603        // `From<RestartPolicy> for String` (7851725) forward
10604        // projections must resolve identically on every arm, locking
10605        // the three return-shape paths together by construction so any
10606        // future detour trips at caixa-core test time. Also byte-parity
10607        // witness against the sibling [`ToString::to_string`] surface
10608        // routed through [`std::fmt::Display`] — every owned-heap-
10609        // string path (the `Cow::Owned` promotion of this axis's
10610        // `.into_owned()`, `From<RestartPolicy> for String`, and
10611        // `.to_string()`) resolves to the same lifted
10612        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10613        //
10614        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10615        // witness over [`super::RestartPolicy::ALL`] that
10616        // materializes the three-arm accept-set through the
10617        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10618        // shape a future `axum::response::IntoResponse` per-policy
10619        // rejection-body composer, a future M4 admission-webhook
10620        // per-policy rejection-reason emitter whose typing rules out
10621        // the sibling [`AsRef<str>`] borrowed return, or a future
10622        // substrate-wide per-policy diagnostic surface that binds
10623        // through a [`Cow<'static, str>`] boundary reaches through.
10624        // The pipe witness also pins the zero-alloc discipline: every
10625        // element in the collected vector satisfies the
10626        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10627        // accidental silent-allocation regression on the pipe's
10628        // iteration axis is a caixa-core-test-time failure. Peer of
10629        // the first-mover
10630        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10631        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10632        // — closes the whole owned-input `Cow<'static, str>` +
10633        // paired `{&'static str, String}` cross-axis-parity corner on
10634        // both M2 OTP-shape sibling peers.
10635        for &variant in RestartPolicy::ALL {
10636            let via_cow: std::borrow::Cow<'static, str> =
10637                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10638            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10639            let via_string: String = <String as From<RestartPolicy>>::from(variant);
10640            assert_eq!(
10641                via_cow.as_ref(),
10642                via_static,
10643                "From<RestartPolicy> for Cow<'static, str> and \
10644                 From<RestartPolicy> for &'static str must resolve \
10645                 identically on RestartPolicy::{variant:?} — \
10646                 divergence signals the Cow<'static, str> and \
10647                 &'static str return-shape paths have drifted onto \
10648                 different emit-sets"
10649            );
10650            assert_eq!(
10651                via_cow.as_ref(),
10652                via_string.as_str(),
10653                "From<RestartPolicy> for Cow<'static, str> and \
10654                 From<RestartPolicy> for String must resolve \
10655                 identically on RestartPolicy::{variant:?} — \
10656                 divergence signals the Cow<'static, str> and String \
10657                 return-shape paths have drifted onto different \
10658                 emit-sets"
10659            );
10660            let via_to_string: String = variant.to_string();
10661            assert_eq!(
10662                via_cow.as_ref(),
10663                via_to_string.as_str(),
10664                "From<RestartPolicy> for Cow<'static, str> must \
10665                 byte-equal RestartPolicy::to_string on \
10666                 RestartPolicy::{variant:?} — divergence signals the \
10667                 trait-idiomatic Cow<'static, str> forward-projection \
10668                 axis and the ToString-through-Display axis have \
10669                 drifted onto different emit-sets"
10670            );
10671        }
10672        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10673            .iter()
10674            .copied()
10675            .map(std::borrow::Cow::from)
10676            .collect();
10677        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10678            .iter()
10679            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10680            .collect();
10681        assert_eq!(
10682            via_iter, via_method,
10683            "`.iter().copied().map(Cow::from)` over \
10684             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10685             Cow::Borrowed(p.as_str()))` on every arm — the \
10686             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10687             str>` axis is what makes the `Cow::from` composition \
10688             route through the substrate-primitive \
10689             `RestartPolicy::as_str` accessor with the zero-alloc \
10690             Cow::Borrowed arm by construction, rather than a \
10691             per-call-site `Cow::Owned(policy.to_string())` \
10692             allocation"
10693        );
10694        for cow in &via_iter {
10695            assert!(
10696                matches!(cow, std::borrow::Cow::Borrowed(_)),
10697                "every element of the \
10698                 .iter().copied().map(Cow::from) pipe over \
10699                 RestartPolicy::ALL must land on the zero-alloc \
10700                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10701                 signals the pipe's iteration axis has silently \
10702                 allocated where the substrate-primitive \
10703                 RestartPolicy::as_str `&'static str` return makes \
10704                 the borrowed arm the type-correct projection"
10705            );
10706        }
10707    }
10708
10709    #[test]
10710    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10711        // Fail-before-pass-after byte-parity pin on the newly lifted
10712        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10713        // asserts the borrowed-input standard-library trait impl and
10714        // the substrate-primitive [`super::RestartPolicy::as_str`]
10715        // `pub const fn` accessor resolve to the same three-arm emit-
10716        // set across every arm the exhaustive
10717        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10718        // standard library does not carry a blanket
10719        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10720        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10721        // the borrowed-input `Cow<'static, str>` forward-projection
10722        // axis is a distinct trait-idiomatic surface that a
10723        // `let key: Cow<'static, str> = (&policy).into();`-shaped
10724        // call site or a
10725        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10726        // reaches through this impl and no other — the paired owned-
10727        // input `From<RestartPolicy> for Cow<'static, str>` impl
10728        // (0612398) forces every borrowed-input call site through an
10729        // explicit `Copy` deref (`Cow::from(*policy)`) or a
10730        // `Cow::Borrowed(policy.as_str())` open-code whose type
10731        // bounds have no compile-time link back to the substrate
10732        // primitive.
10733        //
10734        // Also asserts the projection lands on the zero-alloc
10735        // [`std::borrow::Cow::Borrowed`] arm (not the
10736        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10737        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10738        // return lifetime by construction makes the borrowed arm the
10739        // type-correct projection with no runtime allocation on the
10740        // borrowed-input surface just as on the paired owned-input
10741        // surface.
10742        //
10743        // Closes the `{Self, &Self}` input-shape corner on the M2
10744        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10745        // the second-of-two-in-M2 closed-set fieldless typed enum peer
10746        // on the caixa surface (`:supervisor :children :restart`),
10747        // exactly as d45c409 closed it on the top-level
10748        // [`super::CaixaKind`] one commit after the owning half
10749        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10750        // M2 OTP-shape [`super::RestartStrategy`] one commit after
10751        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10752        // tier of the substrate-wide Cow<'static, str> forward-
10753        // projection campaign on both input-shape corners
10754        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10755        for &variant in RestartPolicy::ALL {
10756            let via_trait: std::borrow::Cow<'static, str> =
10757                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10758            let via_method: &'static str = variant.as_str();
10759            assert_eq!(
10760                via_trait.as_ref(),
10761                via_method,
10762                "From<&RestartPolicy> for Cow<'static, str> impl must \
10763                 round-trip &RestartPolicy::{variant:?} to the same \
10764                 lifted SUPERVISOR_CHILD_RESTART_* const \
10765                 RestartPolicy::as_str returns — divergence signals a \
10766                 silent detour off the substrate-primitive accessor"
10767            );
10768            assert!(
10769                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10770                "From<&RestartPolicy> for Cow<'static, str> impl must \
10771                 land on the zero-alloc Cow::Borrowed arm on \
10772                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10773                 signals the projection has silently allocated where \
10774                 the substrate-primitive RestartPolicy::as_str \
10775                 `&'static str` return makes the borrowed arm the \
10776                 type-correct projection"
10777            );
10778            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10779            assert_eq!(
10780                via_into.as_ref(),
10781                via_method,
10782                "Into<Cow<'static, str>>::into on \
10783                 &RestartPolicy::{variant:?} must byte-equal \
10784                 RestartPolicy::as_str on the same input — the \
10785                 blanket-derived Into shape must resolve to the same \
10786                 as_str dispatch as the explicit From impl"
10787            );
10788            assert!(
10789                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10790                "Into<Cow<'static, str>>::into on \
10791                 &RestartPolicy::{variant:?} must land on the \
10792                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10793                 Into shape must resolve to the same Cow::Borrowed \
10794                 dispatch as the explicit From impl"
10795            );
10796        }
10797    }
10798
10799    #[test]
10800    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10801        // Cross-axis partition pin: the newly lifted trait-idiomatic
10802        // borrowed-input `From<&RestartPolicy> for
10803        // std::borrow::Cow<'static, str>` (this lift), the paired
10804        // owned-input `From<RestartPolicy> for
10805        // std::borrow::Cow<'static, str>` (0612398), the paired
10806        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10807        // for &'static str`, and the paired borrowed-input owned-
10808        // `String` `From<&RestartPolicy> for String` must resolve
10809        // identically on every arm, locking the four
10810        // return-shape × input-shape paths together by construction so
10811        // any future detour trips at caixa-core test time. Also byte-
10812        // parity witness against the sibling [`ToString::to_string`]
10813        // surface routed through [`std::fmt::Display`] — every owned-
10814        // heap-string path (this axis's `.into_owned()` promotion, the
10815        // paired [`From<&RestartPolicy> for String`], and
10816        // `.to_string()`) resolves to the same lifted
10817        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10818        //
10819        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10820        // over [`super::RestartPolicy::ALL`] — whose iterator yields
10821        // `&RestartPolicy` by construction, so the borrowed-input
10822        // [`Cow<'static, str>`] axis is what routes the pipe through
10823        // the substrate-primitive [`super::RestartPolicy::as_str`]
10824        // accessor without a spurious [`Copy`] deref (which would only
10825        // be reachable through the owned-input
10826        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10827        // calling `.copied()` on the iterator). The pipe witness also
10828        // pins the zero-alloc discipline: every element in the
10829        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10830        // arm predicate, so a future accidental silent-allocation
10831        // regression on the pipe's iteration axis is a caixa-core-
10832        // test-time failure. Peer of the sibling
10833        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10834        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10835        // the whole borrowed-input `Cow<'static, str>` +
10836        // paired `{&'static str, String}` cross-axis-parity corner on
10837        // both M2 OTP-shape sibling peers.
10838        for &policy in RestartPolicy::ALL {
10839            let borrowed_cow: std::borrow::Cow<'static, str> =
10840                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10841            let owned_cow: std::borrow::Cow<'static, str> =
10842                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10843            let borrowed_static: &'static str =
10844                <&'static str as From<&RestartPolicy>>::from(&policy);
10845            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10846            assert_eq!(
10847                borrowed_cow, owned_cow,
10848                "From<&RestartPolicy> for Cow<'static, str> and \
10849                 From<RestartPolicy> for Cow<'static, str> must \
10850                 resolve identically on RestartPolicy::{policy:?} — \
10851                 divergence signals the borrowed-input and owned-input \
10852                 Cow<'static, str> forward-projection input-shape \
10853                 paths have drifted onto different emit-sets"
10854            );
10855            assert_eq!(
10856                borrowed_cow.as_ref(),
10857                borrowed_static,
10858                "From<&RestartPolicy> for Cow<'static, str> and \
10859                 From<&RestartPolicy> for &'static str must resolve \
10860                 identically on RestartPolicy::{policy:?} — \
10861                 divergence signals the borrowed-input Cow<'static, \
10862                 str> and &'static str return-shape paths have drifted \
10863                 onto different emit-sets"
10864            );
10865            assert_eq!(
10866                borrowed_cow.as_ref(),
10867                borrowed_string.as_str(),
10868                "From<&RestartPolicy> for Cow<'static, str> and \
10869                 From<&RestartPolicy> for String must resolve \
10870                 identically on RestartPolicy::{policy:?} — \
10871                 divergence signals the borrowed-input Cow<'static, \
10872                 str> and owned-`String` return-shape paths have \
10873                 drifted onto different emit-sets"
10874            );
10875            let via_to_string: String = policy.to_string();
10876            assert_eq!(
10877                borrowed_cow.as_ref(),
10878                via_to_string.as_str(),
10879                "From<&RestartPolicy> for Cow<'static, str> must \
10880                 byte-equal RestartPolicy::to_string on \
10881                 RestartPolicy::{policy:?} — divergence signals \
10882                 the trait-idiomatic borrowed-input Cow<'static, str> \
10883                 forward-projection axis and the ToString-through-\
10884                 Display axis have drifted onto different emit-sets"
10885            );
10886        }
10887        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10888            .iter()
10889            .map(std::borrow::Cow::from)
10890            .collect();
10891        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10892            .iter()
10893            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10894            .collect();
10895        assert_eq!(
10896            via_iter, via_method,
10897            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10898             call site whose iteration axis holds `&RestartPolicy` \
10899             by construction — must byte-equal `.iter().map(|p| \
10900             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10901             input Cow<'static, str> `From<&RestartPolicy> for \
10902             Cow<'static, str>` axis is what makes the `Cow::from` \
10903             composition route through the substrate-primitive \
10904             `RestartPolicy::as_str` accessor with the zero-alloc \
10905             Cow::Borrowed arm by construction and without a spurious \
10906             `Copy` deref (which would only be reachable through the \
10907             owned-input `From<RestartPolicy> for Cow<'static, str>` \
10908             axis by first calling `.copied()` on the iterator)"
10909        );
10910        for cow in &via_iter {
10911            assert!(
10912                matches!(cow, std::borrow::Cow::Borrowed(_)),
10913                "every element of the .iter().map(Cow::from) pipe \
10914                 over RestartPolicy::ALL must land on the zero-\
10915                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10916                 any arm signals the pipe's iteration axis has \
10917                 silently allocated where the substrate-primitive \
10918                 RestartPolicy::as_str `&'static str` return makes \
10919                 the borrowed arm the type-correct projection"
10920            );
10921        }
10922    }
10923
10924    #[test]
10925    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
10926        // Fail-before-pass-after byte-parity pin on the newly lifted
10927        // `impl From<RestartPolicy> for Box<str>` — asserts the
10928        // owned-input standard-library trait impl and the
10929        // substrate-primitive [`super::RestartPolicy::as_str`]
10930        // `pub const fn` accessor resolve to the same three-arm emit-
10931        // set across every arm the exhaustive
10932        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
10933        // substrate-wide `Box<str>` forward-projection campaign tier
10934        // opened one commit prior (69ef45c) on the paired sibling-
10935        // restart [`RestartStrategy`] onto the second (and third-and-
10936        // final) M2 OTP-shape closed-set fieldless typed enum peer on
10937        // the caixa surface (`:children :restart`), immediately after
10938        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
10939        // closed the
10940        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10941        // 2×3 corner on this enum. Rust's standard library carries
10942        // `impl From<&str> for Box<str>` and
10943        // `impl From<String> for Box<str>` but no blanket
10944        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10945        // a distinct trait-idiomatic surface that a
10946        // `let key: Box<str> = policy.into();`-shaped call site
10947        // reaches through this impl and no other — a paired
10948        // `Box::from(policy.as_str())` open-code has no compile-time
10949        // link back to the substrate primitive. Peer of the sibling
10950        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
10951        // (69ef45c) — extends the trait-idiomatic owned-input
10952        // [`Box<str>`] forward-projection axis onto the third and
10953        // final M2-OTP-shape closed-set typed enum on the caixa
10954        // surface.
10955        for &variant in RestartPolicy::ALL {
10956            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10957            let via_method: &'static str = variant.as_str();
10958            assert_eq!(
10959                via_trait.as_ref(),
10960                via_method,
10961                "From<RestartPolicy> for Box<str> impl must round-\
10962                 trip RestartPolicy::{variant:?} to the same lifted \
10963                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10964                 returns — divergence signals a silent detour off the \
10965                 substrate-primitive accessor"
10966            );
10967            let via_into: Box<str> = variant.into();
10968            assert_eq!(
10969                via_into.as_ref(),
10970                via_method,
10971                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
10972                 must byte-equal RestartPolicy::as_str on the same \
10973                 input — the blanket-derived Into shape must resolve \
10974                 to the same as_str dispatch as the explicit From impl"
10975            );
10976        }
10977    }
10978
10979    #[test]
10980    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10981        // Fail-before-pass-after byte-parity pin on the newly lifted
10982        // `impl From<&RestartPolicy> for Box<str>` — asserts the
10983        // borrowed-input standard-library trait impl and the
10984        // substrate-primitive [`super::RestartPolicy::as_str`]
10985        // `pub const fn` accessor resolve to the same three-arm emit-
10986        // set across every arm the exhaustive
10987        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10988        // standard library does not carry a blanket
10989        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10990        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10991        // so the borrowed-input `Box<str>` forward-projection axis
10992        // is a distinct trait-idiomatic surface that a
10993        // `let key: Box<str> = (&policy).into();`-shaped call site
10994        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
10995        // shaped pipe reaches through this impl and no other — the
10996        // paired owned-input `From<RestartPolicy> for Box<str>`
10997        // impl (0a1b313) forces every borrowed-input call site
10998        // through an explicit `Copy` deref
10999        // (`Box::<str>::from((*policy).as_str())`) or a
11000        // `Box::<str>::from(policy.as_str())` open-code whose
11001        // type bounds have no compile-time link back to the
11002        // substrate primitive.
11003        //
11004        // Fourth (and closing) peer on the substrate-wide trait-
11005        // idiomatic [`Box<str>`] forward-projection family on the
11006        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11007        // shape corner of the [`Box<str>`] axis on the second (and
11008        // third-and-final) M2 OTP-shape closed-set fieldless typed
11009        // enum peer on the caixa surface (`:children :restart`),
11010        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11011        // axis one commit after its owning half (0612398) landed
11012        // on this enum. Every remaining closed-set fieldless typed
11013        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11014        // render-side / outside-caixa-core tiers is a future
11015        // target of the campaign.
11016        //
11017        // Also byte-parity witness against the paired owned-input
11018        // [`From<RestartPolicy> for Box<str>`] and the sibling
11019        // borrowed-input [`From<&RestartPolicy> for &'static str`],
11020        // [`From<&RestartPolicy> for String`], and
11021        // [`From<&RestartPolicy> for Cow<'static, str>`]
11022        // return-shape axes — locking the four
11023        // return-shape × input-shape paths together by construction
11024        // so any future detour trips at caixa-core test time. Then a
11025        // `.iter().map(Box::<str>::from)` pipe witness over
11026        // [`super::RestartPolicy::ALL`] — whose iterator yields
11027        // `&RestartPolicy` by construction, so the borrowed-input
11028        // [`Box<str>`] axis is what routes the pipe through the
11029        // substrate-primitive [`super::RestartPolicy::as_str`]
11030        // accessor without a spurious [`Copy`] deref (which would
11031        // only be reachable through the owned-input
11032        // [`From<RestartPolicy> for Box<str>`] axis by first
11033        // calling `.copied()` on the iterator).
11034        for &variant in RestartPolicy::ALL {
11035            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11036            let via_method: &'static str = variant.as_str();
11037            assert_eq!(
11038                via_trait.as_ref(),
11039                via_method,
11040                "From<&RestartPolicy> for Box<str> impl must round-\
11041                 trip &RestartPolicy::{variant:?} to the same lifted \
11042                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11043                 returns — divergence signals a silent detour off the \
11044                 substrate-primitive accessor"
11045            );
11046            let via_into: Box<str> = (&variant).into();
11047            assert_eq!(
11048                via_into.as_ref(),
11049                via_method,
11050                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11051                 must byte-equal RestartPolicy::as_str on the same \
11052                 input — the blanket-derived Into shape must resolve \
11053                 to the same as_str dispatch as the explicit From impl"
11054            );
11055            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11056            assert_eq!(
11057                via_trait, owned_box,
11058                "From<&RestartPolicy> for Box<str> and \
11059                 From<RestartPolicy> for Box<str> must resolve \
11060                 identically on RestartPolicy::{variant:?} — \
11061                 divergence signals the borrowed-input and owned-input \
11062                 Box<str> forward-projection input-shape paths have \
11063                 drifted onto different emit-sets"
11064            );
11065            let borrowed_static: &'static str =
11066                <&'static str as From<&RestartPolicy>>::from(&variant);
11067            assert_eq!(
11068                via_trait.as_ref(),
11069                borrowed_static,
11070                "From<&RestartPolicy> for Box<str> and \
11071                 From<&RestartPolicy> for &'static str must resolve \
11072                 identically on RestartPolicy::{variant:?} — \
11073                 divergence signals the borrowed-input Box<str> and \
11074                 &'static str return-shape paths have drifted onto \
11075                 different emit-sets"
11076            );
11077            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11078            assert_eq!(
11079                via_trait.as_ref(),
11080                borrowed_string.as_str(),
11081                "From<&RestartPolicy> for Box<str> and \
11082                 From<&RestartPolicy> for String must resolve \
11083                 identically on RestartPolicy::{variant:?} — \
11084                 divergence signals the borrowed-input Box<str> and \
11085                 owned-`String` return-shape paths have drifted onto \
11086                 different emit-sets"
11087            );
11088            let borrowed_cow: std::borrow::Cow<'static, str> =
11089                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11090            assert_eq!(
11091                via_trait.as_ref(),
11092                borrowed_cow.as_ref(),
11093                "From<&RestartPolicy> for Box<str> and \
11094                 From<&RestartPolicy> for Cow<'static, str> must \
11095                 resolve identically on RestartPolicy::{variant:?} — \
11096                 divergence signals the borrowed-input Box<str> and \
11097                 Cow<'static, str> return-shape paths have drifted \
11098                 onto different emit-sets"
11099            );
11100        }
11101        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11102        let via_method: Vec<Box<str>> = RestartPolicy::ALL
11103            .iter()
11104            .map(|p| Box::<str>::from(p.as_str()))
11105            .collect();
11106        assert_eq!(
11107            via_iter, via_method,
11108            "`.iter().map(Box::<str>::from)` over \
11109             RestartPolicy::ALL — a call site whose iteration axis \
11110             holds `&RestartPolicy` by construction — must byte-\
11111             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11112             on every arm — the borrowed-input Box<str> \
11113             `From<&RestartPolicy> for Box<str>` axis is what \
11114             makes the `Box::<str>::from` composition route through \
11115             the substrate-primitive `RestartPolicy::as_str` \
11116             accessor without a spurious `Copy` deref (which would \
11117             only be reachable through the owned-input \
11118             `From<RestartPolicy> for Box<str>` axis by first \
11119             calling `.copied()` on the iterator)"
11120        );
11121    }
11122
11123    #[test]
11124    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11125        // Fail-before-pass-after byte-parity pin on the newly lifted
11126        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11127        // the owned-input standard-library trait impl and the
11128        // substrate-primitive [`super::RestartPolicy::as_str`]
11129        // `pub const fn` accessor resolve to the same three-arm emit-
11130        // set across every arm the exhaustive
11131        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11132        // substrate-wide [`std::sync::Arc<str>`] forward-projection
11133        // campaign tier opened one projection tier prior (bca2ec8) on
11134        // the paired sibling-restart [`RestartStrategy`] owned-input
11135        // first-mover onto the second (and third-and-final) M2 OTP-
11136        // shape closed-set fieldless typed enum peer on the caixa
11137        // surface (`:children :restart`), immediately after the paired
11138        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11139        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11140        // Box<str>}` 2×4 corner on this enum. Rust's standard library
11141        // carries `impl From<&str> for std::sync::Arc<str>` and
11142        // `impl From<String> for std::sync::Arc<str>` but no blanket
11143        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11144        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11145        // so this axis is a distinct trait-idiomatic surface that a
11146        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11147        // site reaches through this impl and no other — a paired
11148        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11149        // has no compile-time link back to the substrate primitive,
11150        // and a two-step `std::sync::Arc::<str>::from(String::from(
11151        // policy))` composition through the owned-`String` axis
11152        // allocates twice (once into the intermediate `String`, once
11153        // into the [`Arc<str>`] on the `From<String>` conversion)
11154        // where the single-step trait impl allocates once.
11155        //
11156        // Cross-axis byte-parity witness against the sibling owned-
11157        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11158        // return-shape axes — locking the five return-shape paths on
11159        // the owned-input surface together by construction so any
11160        // future detour off the substrate-primitive
11161        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11162        // core test time.
11163        for &variant in RestartPolicy::ALL {
11164            let via_trait: std::sync::Arc<str> =
11165                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11166            let via_method: &'static str = variant.as_str();
11167            assert_eq!(
11168                via_trait.as_ref(),
11169                via_method,
11170                "From<RestartPolicy> for std::sync::Arc<str> impl \
11171                 must round-trip RestartPolicy::{variant:?} to the \
11172                 same lifted SUPERVISOR_CHILD_RESTART_* const \
11173                 RestartPolicy::as_str returns — divergence signals \
11174                 a silent detour off the substrate-primitive accessor"
11175            );
11176            let via_into: std::sync::Arc<str> = variant.into();
11177            assert_eq!(
11178                via_into.as_ref(),
11179                via_method,
11180                "Into<std::sync::Arc<str>>::into on \
11181                 RestartPolicy::{variant:?} must byte-equal \
11182                 RestartPolicy::as_str on the same input — the \
11183                 blanket-derived Into shape must resolve to the same \
11184                 as_str dispatch as the explicit From impl"
11185            );
11186            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11187            assert_eq!(
11188                via_trait.as_ref(),
11189                owned_static,
11190                "From<RestartPolicy> for std::sync::Arc<str> and \
11191                 From<RestartPolicy> for &'static str must resolve \
11192                 identically on RestartPolicy::{variant:?} — \
11193                 divergence signals the owned-input std::sync::Arc<str> \
11194                 and &'static str return-shape paths have drifted onto \
11195                 different emit-sets"
11196            );
11197            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11198            assert_eq!(
11199                via_trait.as_ref(),
11200                owned_string.as_str(),
11201                "From<RestartPolicy> for std::sync::Arc<str> and \
11202                 From<RestartPolicy> for String must resolve \
11203                 identically on RestartPolicy::{variant:?} — \
11204                 divergence signals the owned-input std::sync::Arc<str> \
11205                 and owned-`String` return-shape paths have drifted \
11206                 onto different emit-sets"
11207            );
11208            let owned_cow: std::borrow::Cow<'static, str> =
11209                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11210            assert_eq!(
11211                via_trait.as_ref(),
11212                owned_cow.as_ref(),
11213                "From<RestartPolicy> for std::sync::Arc<str> and \
11214                 From<RestartPolicy> for Cow<'static, str> must \
11215                 resolve identically on RestartPolicy::{variant:?} — \
11216                 divergence signals the owned-input std::sync::Arc<str> \
11217                 and Cow<'static, str> return-shape paths have drifted \
11218                 onto different emit-sets"
11219            );
11220            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11221            assert_eq!(
11222                via_trait.as_ref(),
11223                owned_box.as_ref(),
11224                "From<RestartPolicy> for std::sync::Arc<str> and \
11225                 From<RestartPolicy> for Box<str> must resolve \
11226                 identically on RestartPolicy::{variant:?} — \
11227                 divergence signals the owned-input std::sync::Arc<str> \
11228                 and Box<str> return-shape paths have drifted onto \
11229                 different emit-sets"
11230            );
11231        }
11232    }
11233
11234    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
11235
11236    #[test]
11237    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
11238        // The fail-before-pass-after pin: pre-lift there was no
11239        // single-source binding between the [`RestartPolicy`] variant
11240        // name the un-`rename`d `Serialize` derive emits under
11241        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
11242        // byte-string every downstream cluster-side dispatcher (the
11243        // future wasm-operator's per-child post-exit restart-decision
11244        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
11245        // materializer's admission-time enum-arm bind, the
11246        // `caixa-operator`'s hierarchical reconciliation scheduler's
11247        // per-child-policy fan-out) probes verbatim. A future
11248        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
11249        // or a per-variant `#[serde(rename = "…")]` override, or a
11250        // variant rename in the source — would silently rebrand the
11251        // emitted scalar under one spelling while every downstream
11252        // dispatcher still probed the other, with the failure surfacing
11253        // at the operator's reconcile posture (children coming up under
11254        // the `default()` `Permanent` arm rather than the typed slot's
11255        // declared policy — a `:temporary` `oneShot` child would be
11256        // restarted on clean exit, treating the successful-completion
11257        // signal as failure and re-running the completion-terminal
11258        // one-shot indefinitely; a `:transient` child that clean-exited
11259        // would be restarted, masking the clean-completion contract)
11260        // far from the source rebrand commit and with no field naming
11261        // the drift. Pinning the two paths (the `Serialize` derive's
11262        // serialized string AND the [`RestartPolicy::as_str`] helper)
11263        // to the same three lifted
11264        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
11265        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
11266        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
11267        // byte-strings makes any future drift on either endpoint fail
11268        // here at caixa-core build time. Peer of the sibling
11269        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
11270        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11271        // and the M3
11272        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
11273        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
11274        // same three-path-convergence discipline, extended to close the
11275        // third OTP-shaped closed-enum discriminator axis on the caixa
11276        // typed surface (per-child restart-decision policy).
11277        for (variant, expected) in [
11278            (
11279                RestartPolicy::Permanent,
11280                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11281            ),
11282            (
11283                RestartPolicy::Temporary,
11284                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11285            ),
11286            (
11287                RestartPolicy::Transient,
11288                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11289            ),
11290        ] {
11291            let json = serde_json::to_string(&variant).unwrap();
11292            assert_eq!(
11293                json,
11294                format!("\"{expected}\""),
11295                "RestartPolicy::{variant:?} must serialize to {expected:?}"
11296            );
11297            assert_eq!(
11298                variant.as_str(),
11299                expected,
11300                "RestartPolicy::{variant:?}.as_str() must return the lifted \
11301                 SUPERVISOR_CHILD_RESTART_* constant"
11302            );
11303        }
11304    }
11305
11306    #[test]
11307    fn supervisor_child_restart_consts_are_pairwise_distinct() {
11308        // Cross-arm drift-detection pin: a future collapse of two
11309        // canonical variant byte-strings onto the same value (e.g. an
11310        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
11311        // to also read `"Permanent"`) would silently reroute every
11312        // downstream operator's per-child-policy dispatch onto the
11313        // sibling arm's reconcile branch and pass every propagation-probe
11314        // test that expected only the stale arm's value — a `:transient`
11315        // child would come up under the `:permanent` restart-decision
11316        // posture on every subsequent clean exit, so a completion-terminal
11317        // child would be restarted indefinitely against its declared
11318        // policy. Peer of the sibling
11319        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
11320        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11321        // and the four-way distinct pin
11322        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
11323        // top-level `SUPERVISOR_KEY_*` axis.
11324        let all = [
11325            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11326            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11327            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11328        ];
11329        for (i, a) in all.iter().enumerate() {
11330            for (j, b) in all.iter().enumerate() {
11331                if i != j {
11332                    assert_ne!(
11333                        a, b,
11334                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
11335                         — got duplicate {a:?} at indices {i} and {j}",
11336                    );
11337                }
11338            }
11339        }
11340    }
11341
11342    #[test]
11343    fn restart_policy_display_routes_through_as_str_helper() {
11344        // The fail-before-pass-after pin on the first half of the
11345        // three-path convergence: pre-convergence [`RestartPolicy`]
11346        // carried a [`std::fmt::Display`] surface via its
11347        // `#[discriminant(also_display)]` gen-platform derive route,
11348        // which arrived kebab-case as `"permanent"` / `"temporary"`
11349        // / `"transient"` on this three-arm enum (whose variant
11350        // names each collapse to their own lowercase form under the
11351        // kebab-case transform) while the wire format ran as
11352        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
11353        // through the un-`rename`d serde derive. Every consumer
11354        // reaching for a policy byte-string past the wire format had
11355        // to pick between three paths ([`RestartPolicy::as_str`],
11356        // the `Serialize` derive's serialized string, or
11357        // `format!("{v}")` on the discriminant-Display route), any
11358        // two of which a future variant rename or
11359        // `#[serde(rename_all = "kebab-case")]` attribute would
11360        // silently desynchronize. Wiring [`std::fmt::Display`]
11361        // through [`RestartPolicy::as_str`] closes the third path:
11362        // every `format!("{v}")` call reaches the same lifted
11363        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
11364        // wire format and the [`RestartPolicy::as_str`] helper
11365        // already route through, so a future variant rename lands at
11366        // exactly one place. Pin the routing here so a future
11367        // `impl std::fmt::Display for RestartPolicy`
11368        // reimplementation that hand-rolls the arms instead of
11369        // delegating to [`RestartPolicy::as_str`] fails at
11370        // caixa-core build time. Peer of the sibling
11371        // [`restart_strategy_display_routes_through_as_str_helper`]
11372        // on the per-supervisor sibling-restart-strategy axis and
11373        // the M3
11374        // `placement_strategy_display_routes_through_as_str_helper`
11375        // (cc8f749) — the third of three OTP-shape closed-enum
11376        // discriminator axes on the caixa typed surface now
11377        // converged onto the same three-path
11378        // (Display → as_str → lifted const) discipline.
11379        for variant in [
11380            RestartPolicy::Permanent,
11381            RestartPolicy::Temporary,
11382            RestartPolicy::Transient,
11383        ] {
11384            assert_eq!(
11385                variant.to_string(),
11386                variant.as_str(),
11387                "RestartPolicy::{variant:?} Display must route through \
11388                 RestartPolicy::as_str (single source of truth: the lifted \
11389                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
11390            );
11391        }
11392    }
11393
11394    #[test]
11395    fn restart_policy_display_matches_serialized_wire_byte_string() {
11396        // The fail-before-pass-after pin on the second half of the
11397        // three-path convergence: `Display` (user-facing text) agrees
11398        // byte-for-byte with the `Serialize` derive's wire format
11399        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
11400        // scalar) on every variant. Pre-convergence the two paths
11401        // were structurally independent — a future
11402        // `#[serde(rename_all = "kebab-case")]` attribute on the
11403        // enum would silently rebrand the emitted wire scalar
11404        // (`permanent`, `temporary`, `transient`) while every
11405        // consumer that pretty-prints the policy (the future
11406        // wasm-operator's per-child post-exit restart-decision
11407        // diagnostic line, the future `feira app graph` per-child
11408        // restart column, the future M4
11409        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
11410        // per-child admission-webhook rejection body) would still
11411        // emit the PascalCase form the `as_str` / `Display` route
11412        // returns, with the mismatch surfacing at consumer parse
11413        // time / operator dispatch time far from the source rebrand
11414        // commit. Pin the two paths byte-for-byte here so any future
11415        // serde-attribute or variant-rename drift is a
11416        // caixa-core-build-time test failure at this call, not a
11417        // silent per-consumer dispatch miss. Peer of the sibling
11418        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
11419        // on the per-supervisor sibling-restart-strategy axis and
11420        // the M3
11421        // `placement_strategy_display_matches_serialized_wire_byte_string`
11422        // (cc8f749).
11423        for variant in [
11424            RestartPolicy::Permanent,
11425            RestartPolicy::Temporary,
11426            RestartPolicy::Transient,
11427        ] {
11428            let wire = serde_json::to_string(&variant).unwrap();
11429            let unquoted = wire
11430                .strip_prefix('"')
11431                .and_then(|s| s.strip_suffix('"'))
11432                .expect("serialized RestartPolicy is a JSON string");
11433            assert_eq!(
11434                variant.to_string(),
11435                unquoted,
11436                "RestartPolicy::{variant:?} Display byte-string must match the \
11437                 Serialize derive's wire byte-string (three-path convergence: \
11438                 Display + as_str + Serialize all resolve to the same \
11439                 SUPERVISOR_CHILD_RESTART_* const)"
11440            );
11441        }
11442    }
11443
11444    #[test]
11445    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11446        // Fail-before-pass-after byte-parity pin on the lifted
11447        // `impl AsRef<str> for RestartPolicy` — asserts the
11448        // standard-library trait impl and the substrate-primitive
11449        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11450        // to the same `&str` per instance across the three-arm
11451        // closed set, so any future silent detour that routes the
11452        // impl through a divergent projection (a per-arm inline
11453        // `match self { RestartPolicy::Permanent => "Permanent", … }`
11454        // re-inlining that opens a compile-time link to the un-lifted
11455        // arm-literal, a swap onto the kebab-case
11456        // [`gen_platform::Discriminant`] catalog identity that would
11457        // collide the wire axis with the dispatcher-catalog axis) trips
11458        // at caixa-core test time under `PartialEq` rather than at a
11459        // downstream `impl AsRef<str>`-bound consumer's silent split.
11460        // Sweeps every one of the three arms
11461        // [`RestartPolicy::ALL`] carries so no arm's projection is
11462        // covered only by the sibling wire-format `Serialize` derive
11463        // path. Peer of the sibling
11464        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11465        // (63eb1a4) on the paired per-supervisor sibling-restart-
11466        // strategy axis and the [`crate::CaixaVersion`]
11467        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11468        // top-level `:versao` typed newtype — the three pins together
11469        // cover the substrate primitive's `AsRef<str>` projection axis
11470        // on the paired newtype + M2 closed-set-typed-enum surface.
11471        for &variant in RestartPolicy::ALL {
11472            assert_eq!(
11473                <RestartPolicy as AsRef<str>>::as_ref(&variant),
11474                variant.as_str(),
11475                "AsRef<str> impl on RestartPolicy::{variant:?} must \
11476                 byte-equal RestartPolicy::as_str on the same instance \
11477                 — divergence signals a silent detour off the substrate-\
11478                 primitive accessor"
11479            );
11480        }
11481    }
11482
11483    #[test]
11484    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11485        // Fail-before-pass-after byte-parity pin on the three-path
11486        // convergence discipline the M2 per-child-restart-policy
11487        // primitive now carries on the `&str`-projection axis:
11488        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11489        // lifted impl), `format!("{v}")` (the pre-existing
11490        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
11491        // primitive `pub const fn` accessor both trait impls delegate
11492        // through) must resolve to the same byte-string on every
11493        // instance across the three-arm closed set. Refuses any future
11494        // divergence between the two trait impls (a stray
11495        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
11496        // rather than delegating through the shared accessor; a
11497        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
11498        // literal cascade) that would silently split the two
11499        // projection paths of the same closed-set typed enum. Mirrors
11500        // the sibling three-path-convergence discipline the peer
11501        // [`RestartStrategy`] typed enum carries on its
11502        // `AsRef<str>` / `Display` / `as_str` triple
11503        // (supervisor.rs pin
11504        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
11505        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
11506        // carries on the same triple (version.rs pin
11507        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
11508        // 16d5c7e).
11509        for &variant in RestartPolicy::ALL {
11510            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
11511            let via_display: String = format!("{variant}");
11512            let via_accessor: &str = variant.as_str();
11513            assert_eq!(via_as_ref, via_accessor);
11514            assert_eq!(via_display, via_accessor);
11515            assert_eq!(via_as_ref, via_display.as_str());
11516        }
11517    }
11518
11519    #[test]
11520    fn restart_policy_all_enumerates_every_variant_exactly_once() {
11521        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
11522        // exhaustive-iteration surface: every variant appears exactly
11523        // once, and the slice length matches the arm count of the
11524        // closed set. Every consumer that walks the accepted-policy
11525        // set (a future `feira supervisor --restart …` CLI-side
11526        // arg-parse's "did you mean" hint, a future M4 admission-
11527        // webhook's per-child rejection body naming the accepted-
11528        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
11529        // projection consumers that iterate the accept-set for
11530        // diagnostic rendering) reads through this slice, so a future
11531        // arm addition that grows the enum but forgets to grow
11532        // [`Self::ALL`] silently truncates every downstream consumer's
11533        // accept-set at the same pre-addition boundary — this pin
11534        // fails at caixa-core build time on the pairwise-distinct +
11535        // arm-count invariants.
11536        //
11537        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
11538        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
11539        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
11540        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
11541        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
11542        // pins on the peer closed-set typed-enum axes.
11543        let all: &[RestartPolicy] = RestartPolicy::ALL;
11544        assert_eq!(
11545            all.len(),
11546            3,
11547            "RestartPolicy::ALL must enumerate every variant of the \
11548             three-arm closed set (Permanent, Temporary, Transient); \
11549             got {all:?}"
11550        );
11551        for (i, a) in all.iter().enumerate() {
11552            for (j, b) in all.iter().enumerate() {
11553                if i != j {
11554                    assert_ne!(
11555                        a, b,
11556                        "RestartPolicy::ALL must carry every variant exactly \
11557                         once — got duplicate {a:?} at indices {i} and {j}"
11558                    );
11559                }
11560            }
11561        }
11562        for variant in [
11563            RestartPolicy::Permanent,
11564            RestartPolicy::Temporary,
11565            RestartPolicy::Transient,
11566        ] {
11567            assert!(
11568                all.contains(&variant),
11569                "RestartPolicy::ALL must contain {variant:?} — a future arm \
11570                 addition that grows the enum but forgets to grow the ALL slice \
11571                 silently truncates every downstream consumer's accept-set at \
11572                 the pre-addition boundary"
11573            );
11574        }
11575    }
11576
11577    #[test]
11578    fn restart_policy_from_wire_accepts_every_lifted_constant() {
11579        // Fail-before-pass-after pin on the forward accept-set of the
11580        // [`RestartPolicy::from_wire`] reverse projection: every
11581        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
11582        // constant the [`RestartPolicy::as_str`] emitter walks parses
11583        // back to its paired variant. Any future arm addition that
11584        // grows the emitter's `as_str` match but forgets to grow the
11585        // parser's `from_wire` match silently splits the two halves of
11586        // the round-trip — the wire byte-string one non-serde consumer
11587        // parses from the one the emitter wrote — with the failure
11588        // surfacing at the operator's reconcile posture (a `:temporary`
11589        // `oneShot` child restarted on clean exit, a `:transient` child
11590        // restarted after clean completion) far from the rebrand
11591        // commit. Pinning the three-arm accept-set here catches the
11592        // drift at caixa-core build time.
11593        //
11594        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
11595        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
11596        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
11597        // accept-set pins on the peer closed-set typed-enum `str → Self`
11598        // axes.
11599        for (wire, expected) in [
11600            (
11601                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11602                RestartPolicy::Permanent,
11603            ),
11604            (
11605                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11606                RestartPolicy::Temporary,
11607            ),
11608            (
11609                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11610                RestartPolicy::Transient,
11611            ),
11612        ] {
11613            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11614                panic!(
11615                    "RestartPolicy::from_wire({wire:?}) must accept every \
11616                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
11617                     lifted canonical byte-string that RestartPolicy::{expected:?} \
11618                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
11619                )
11620            });
11621            assert_eq!(
11622                parsed, expected,
11623                "RestartPolicy::from_wire({wire:?}) must return \
11624                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
11625            );
11626        }
11627    }
11628
11629    #[test]
11630    fn restart_policy_from_wire_round_trips_through_as_str() {
11631        // Fail-before-pass-after pin on the closed round-trip between
11632        // the forward [`RestartPolicy::as_str`] emitter and the
11633        // reverse [`RestartPolicy::from_wire`] parser: for every
11634        // variant in [`RestartPolicy::ALL`], parsing the emitter's
11635        // output must return exactly the same variant. Any per-arm
11636        // divergence — a future arm added to `as_str` but not
11637        // `from_wire`, an accidental copy-paste flip in one but not
11638        // the other — silently splits the emit and parse halves and
11639        // the failure surfaces at consumer parse time far from the
11640        // drift site. The `ALL`-iterating shape means a future arm
11641        // addition picks up the coverage by construction.
11642        //
11643        // Peer of the sibling
11644        // [`restart_strategy_from_wire_round_trips_through_as_str`]
11645        // (4eec29c) round-trip pin on
11646        // [`RestartStrategy::from_wire`] and the M3
11647        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11648        // (18c7342) round-trip pin on
11649        // [`crate::aplicacao::PlacementStrategy::from_wire`].
11650        for &variant in RestartPolicy::ALL {
11651            let wire = variant.as_str();
11652            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11653                panic!(
11654                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11655                     must be Some({variant:?}) — the two halves of the round-trip \
11656                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11657                     got None on wire byte-string {wire:?}"
11658                )
11659            });
11660            assert_eq!(
11661                parsed, variant,
11662                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11663                 must round-trip to the same variant; got {parsed:?}"
11664            );
11665        }
11666    }
11667
11668    #[test]
11669    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11670        // Fail-before-pass-after pin on the closed-set refusal
11671        // discipline of [`RestartPolicy::from_wire`]: every
11672        // byte-string outside the three-arm accept-set returns `None`
11673        // rather than silently collapsing onto the [`Default`]
11674        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11675        // exercised here sweeps the load-bearing drift shapes: the
11676        // empty string (a stripped serde-attribute drift), all-
11677        // whitespace strings (the canonical text-editor accidental
11678        // padding shape), the kebab-case dispatcher-catalog identities
11679        // (`"permanent"` / `"temporary"` / `"transient"` — the
11680        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11681        // accept-set, which parses the *other* axis of this enum's
11682        // two-axis split and must not leak into the `from_wire`
11683        // PascalCase-wire accept-set — a lowercase leak here would
11684        // silently accept the operator's kebab-case
11685        // dispatcher-catalog probe under the wire-axis parser and mis-
11686        // route a `:permanent` intent), the padded canonical scalar
11687        // (`" Permanent "`), the trailing-newline shapes
11688        // (`"Permanent\n"`), the uppercase-single-word forms
11689        // (`"PERMANENT"`), and neighboring-but-unknown arms
11690        // (`"Restart"` — the canonical typo direction toward the
11691        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11692        //
11693        // Peer of the sibling
11694        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11695        // (4eec29c) +
11696        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11697        // (2aa6d23) +
11698        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11699        // (18c7342) refusal pins on the peer closed-set typed-enum
11700        // axes.
11701        for bad in [
11702            "",
11703            " ",
11704            "\n",
11705            "\t",
11706            "permanent",
11707            "temporary",
11708            "transient",
11709            "PERMANENT",
11710            "TEMPORARY",
11711            "TRANSIENT",
11712            "Permanents",
11713            "Permanent ",
11714            " Permanent",
11715            " Transient ",
11716            "Permanent\n",
11717            "perma",
11718            "Trans",
11719            "OneForOne",
11720            "Restart",
11721            "?",
11722        ] {
11723            assert!(
11724                RestartPolicy::from_wire(bad).is_none(),
11725                "RestartPolicy::from_wire({bad:?}) must return None — the \
11726                 parser's accept-set is exactly the three RestartPolicy::as_str \
11727                 outputs (Permanent, Temporary, Transient), and this \
11728                 byte-string is outside that closed set"
11729            );
11730        }
11731    }
11732
11733    #[test]
11734    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11735        // Fail-before-pass-after pin on the fourth path of the four-path
11736        // convergence: `from_wire` (the reverse projection) inverts the
11737        // `Serialize` derive's wire byte-string on every variant.
11738        // Together with the pre-existing three-path convergence
11739        // (`Display` + `as_str` + `Serialize` all resolve to the same
11740        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11741        // pinned by
11742        // [`restart_policy_display_matches_serialized_wire_byte_string`])
11743        // this closes the round-trip: the wire byte-string the
11744        // `Serialize` derive emits parses back to the same variant
11745        // through `from_wire`, so any future serde-attribute or variant-
11746        // rename drift on the emit half now surfaces as a matched drift
11747        // on the parse half at caixa-core build time — the two halves
11748        // migrate as a unit through the lifted consts on any future
11749        // rename, and the round-trip cannot silently split.
11750        //
11751        // Peer of the sibling
11752        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11753        // (4eec29c) wire-format pin on
11754        // [`RestartStrategy::from_wire`] and the M3
11755        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11756        // (18c7342) wire-format pin on
11757        // [`crate::aplicacao::PlacementStrategy::from_wire`].
11758        for &variant in RestartPolicy::ALL {
11759            let wire = serde_json::to_string(&variant).unwrap();
11760            let unquoted = wire
11761                .strip_prefix('"')
11762                .and_then(|s| s.strip_suffix('"'))
11763                .expect("serialized RestartPolicy is a JSON string");
11764            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
11765                panic!(
11766                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
11767                     Serialize derive's wire byte-string for \
11768                     RestartPolicy::{variant:?} — the four-path convergence \
11769                     (Display + as_str + Serialize + from_wire) resolves through \
11770                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
11771                )
11772            });
11773            assert_eq!(
11774                parsed, variant,
11775                "RestartPolicy::from_wire of the Serialize derive's wire \
11776                 byte-string for RestartPolicy::{variant:?} must round-trip \
11777                 to the same variant; got {parsed:?}"
11778            );
11779        }
11780    }
11781
11782    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
11783    //
11784    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
11785    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
11786    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
11787    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
11788    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
11789    // the peer per-`:upgrade-from :from` axis. The three pins jointly
11790    // brace the accessor against every future silent detour that would
11791    // desynchronize it from the raw `.caixa` field access every consumer
11792    // previously open-coded.
11793
11794    #[test]
11795    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
11796        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
11797        // [`ChildSpec::nome`] must return the `:children :caixa` field
11798        // byte-for-byte across every DNS-1123-label value the upstream
11799        // [`crate::render::require_valid_dns_1123_label`] gate at
11800        // `SupervisorSpec::validate` admits. Peer of the sibling
11801        // `membro_nome_returns_caixa_byte_equal_across_permutations`
11802        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
11803        // substrate-primitive accessor must byte-equal the raw field
11804        // access verbatim across every author-declared value" discipline
11805        // extended to the M2 supervisor-tree per-`:children` arm. Pins
11806        // against a future silent detour that re-normalized the child
11807        // identity (an accidental `.to_lowercase()` — every `:children
11808        // :caixa` is validated as a DNS-1123 label upstream, so any
11809        // re-normalization is redundant + a drift surface between the
11810        // validator and the accessor), a namespace-prefix rewrite (an
11811        // accidental `format!("{namespace}/{caixa}")` per-CR
11812        // fully-qualified rewrite that didn't land on the peer axes), or
11813        // a per-cluster alias stamp the future wasm-operator's
11814        // hierarchical reconciliation scheduler authors on one consumer
11815        // without the others. Five values sweep the accept-set the
11816        // DNS-1123 gate upstream admits (short single-word / dashed /
11817        // v-suffixed / mixed-digit child names).
11818        for name in [
11819            "worker",
11820            "cache-server",
11821            "scratch-job",
11822            "orders-v2",
11823            "session-8080",
11824        ] {
11825            let c = ChildSpec {
11826                caixa: name.into(),
11827                versao: "^0.1".into(),
11828                restart: RestartPolicy::Permanent,
11829            };
11830            assert_eq!(
11831                c.nome(),
11832                name,
11833                "ChildSpec::nome must return :children :caixa verbatim \
11834                 (got {:?}, expected {name:?})",
11835                c.nome(),
11836            );
11837            assert_eq!(
11838                c.nome(),
11839                c.caixa.as_str(),
11840                "ChildSpec::nome must byte-equal the .caixa field access",
11841            );
11842        }
11843    }
11844
11845    #[test]
11846    fn child_spec_nome_borrows_from_caixa_storage() {
11847        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
11848        // `&str` slice that borrows from the typed slot's own [`String`]
11849        // storage — same-address invariant with `c.caixa.as_str()`. Pins
11850        // against a future silent detour that allocated a fresh `String`
11851        // (`self.caixa.clone()` in the body would type-check but silently
11852        // drop the borrow, and every downstream consumer that assumed
11853        // the returned slice outlives `&self` would break on a stale-
11854        // reference use-after-free — the [`crate::render::insert_first_seen`]
11855        // dedup key at [`SupervisorSpec::validate`], the
11856        // [`validate_no_self_supervision`] equality check against the
11857        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
11858        // borrow — each would silently misbehave if this accessor
11859        // produced a detached copy). Peer of the sibling
11860        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
11861        // M3 per-`:membros` axis and the
11862        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
11863        // first M2 slot scalar accessor.
11864        let c = ChildSpec {
11865            caixa: "worker".into(),
11866            versao: "^0.1".into(),
11867            restart: RestartPolicy::Permanent,
11868        };
11869        let name = c.nome();
11870        let caixa_slice = c.caixa.as_str();
11871        assert_eq!(
11872            name.as_ptr(),
11873            caixa_slice.as_ptr(),
11874            "ChildSpec::nome must borrow from the .caixa String's backing \
11875             storage — a fresh allocation here means the accessor no \
11876             longer names the substrate-primitive typed dispatch and \
11877             every downstream consumer would silently carry a detached \
11878             copy",
11879        );
11880        assert_eq!(
11881            name.len(),
11882            caixa_slice.len(),
11883            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
11884             as well as in address",
11885        );
11886    }
11887
11888    #[test]
11889    fn validate_gates_child_nome_through_lifted_accessor() {
11890        // Bilateral coherence pin: every `:children :caixa` that
11891        // [`SupervisorSpec::validate`] accepts is one
11892        // [`crate::render::require_valid_dns_1123_label`] accepts on the
11893        // accessor-projected value, and vice versa on the reject side.
11894        // This closes the "the validator reads through the accessor"
11895        // contract structurally — a future silent detour that made the
11896        // accessor return a different byte-string than the validator
11897        // gates against would surface here as a coverage mismatch, not
11898        // as an apply-time DNS-1123 rejection at
11899        // `metadata.name: Invalid value` far from the caixa.lisp source.
11900        // Peer of the M2 sibling
11901        // `validate_parses_prior_versao_through_lifted_accessor`
11902        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
11903        // `validate_membros` peer discipline.
11904        //
11905        // Accept-set sweep: five DNS-1123-label values the upstream gate
11906        // admits.
11907        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
11908            let s = SupervisorSpec {
11909                children: vec![ChildSpec {
11910                    caixa: ok_name.into(),
11911                    versao: "^0.1".into(),
11912                    restart: RestartPolicy::Permanent,
11913                }],
11914                ..SupervisorSpec::default()
11915            };
11916            s.validate().unwrap_or_else(|e| {
11917                panic!(
11918                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
11919                     (upstream DNS-1123 gate accepts it): got {e:?}",
11920                );
11921            });
11922            let c = ChildSpec {
11923                caixa: ok_name.into(),
11924                versao: "^0.1".into(),
11925                restart: RestartPolicy::Permanent,
11926            };
11927            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
11928                .unwrap_or_else(|()| {
11929                    panic!(
11930                        "require_valid_dns_1123_label must accept the accessor-projected \
11931                     :children :caixa {ok_name:?}",
11932                    );
11933                });
11934        }
11935        // Reject-set sweep: five DNS-1123-label-violating shapes the
11936        // upstream gate refuses (empty / uppercase / underscore / dot /
11937        // leading-hyphen). Every rejection at the validator must
11938        // correspond to a rejection when the accessor's projected value
11939        // is fed back through the shared gate.
11940        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
11941            let s = SupervisorSpec {
11942                children: vec![ChildSpec {
11943                    caixa: bad_name.into(),
11944                    versao: "^0.1".into(),
11945                    restart: RestartPolicy::Permanent,
11946                }],
11947                ..SupervisorSpec::default()
11948            };
11949            let err = s.validate().unwrap_err();
11950            assert!(
11951                matches!(
11952                    err,
11953                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
11954                ),
11955                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
11956                 via the DNS-1123 gate: got {err:?}",
11957            );
11958            let c = ChildSpec {
11959                caixa: bad_name.into(),
11960                versao: "^0.1".into(),
11961                restart: RestartPolicy::Permanent,
11962            };
11963            assert!(
11964                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
11965                    .is_err(),
11966                "require_valid_dns_1123_label must reject the accessor-projected \
11967                 :children :caixa {bad_name:?}",
11968            );
11969        }
11970    }
11971
11972    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
11973    //
11974    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
11975    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
11976    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
11977    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
11978    // trio on the peer per-`:children` `String`-carry axis. The three pins
11979    // jointly brace the accessor against every future silent detour that
11980    // would desynchronize it from the raw `.versao` field access the
11981    // requirement gate + error carrier previously open-coded.
11982    //
11983    // Closes the last unlifted per-`:children` `String`-carry axis: the
11984    // pair (`nome`, `versao_requirement`) now jointly projects the
11985    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
11986    // consumer that fans on per-child identity + version pin reads,
11987    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
11988    // pair discipline verbatim.
11989    #[test]
11990    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
11991        // The canonical per-`:children` child-`:versao`-scalar pin:
11992        // [`ChildSpec::versao_requirement`] must return the `:children
11993        // :versao` field byte-for-byte across every Cargo-shaped semver
11994        // requirement value the upstream
11995        // [`crate::render::require_valid_versao_requirement`] gate admits.
11996        // Peer of the sibling
11997        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
11998        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
11999        // substrate-primitive accessor must byte-equal the raw field
12000        // access verbatim across every author-declared value" discipline
12001        // extended to the M2 supervisor-tree per-`:children` arm. Pins
12002        // against a future silent detour that re-canonicalized the
12003        // requirement (an accidental `.to_string()` via
12004        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
12005        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
12006        // silently drifted the error carrier's quoted requirement away
12007        // from the source `caixa.lisp`, an accidental whitespace trim on
12008        // `"^ 0.1"` that no consumer ever produced from the field-access
12009        // side, an accidental per-cluster lacre-projected concrete-version
12010        // rewrite that didn't land on the peer requirement-gate call).
12011        // Five values sweep the accept-set the shared
12012        // [`crate::render::require_valid_versao_requirement`] gate admits
12013        // (caret / tilde / exact / wildcard / bare-major).
12014        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12015            let c = ChildSpec {
12016                caixa: "worker".into(),
12017                versao: req.into(),
12018                restart: RestartPolicy::Permanent,
12019            };
12020            assert_eq!(
12021                c.versao_requirement(),
12022                req,
12023                "ChildSpec::versao_requirement must return :children :versao \
12024                 verbatim (got {:?}, expected {req:?})",
12025                c.versao_requirement(),
12026            );
12027            assert_eq!(
12028                c.versao_requirement(),
12029                c.versao.as_str(),
12030                "ChildSpec::versao_requirement must byte-equal the .versao \
12031                 field access",
12032            );
12033        }
12034    }
12035
12036    #[test]
12037    fn child_spec_versao_requirement_borrows_from_versao_storage() {
12038        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
12039        // return a `&str` slice that borrows from the typed slot's own
12040        // [`String`] storage — same-address invariant with
12041        // `c.versao.as_str()`. Pins against a future silent detour that
12042        // allocated a fresh `String` (`self.versao.clone()` in the body
12043        // would type-check but silently drop the borrow, and every
12044        // downstream consumer that assumed the returned slice outlives
12045        // `&self` — the [`crate::render::require_valid_versao_requirement`]
12046        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
12047        // `.to_string()` carrier's byte-length assumption — would silently
12048        // misbehave if this accessor produced a detached copy). Peer of
12049        // the sibling `child_spec_nome_borrows_from_caixa_storage`
12050        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
12051        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
12052        // pin on the peer per-`:membros` `:versao` axis.
12053        let c = ChildSpec {
12054            caixa: "worker".into(),
12055            versao: "^0.1".into(),
12056            restart: RestartPolicy::Permanent,
12057        };
12058        let req = c.versao_requirement();
12059        let versao_slice = c.versao.as_str();
12060        assert_eq!(
12061            req.as_ptr(),
12062            versao_slice.as_ptr(),
12063            "ChildSpec::versao_requirement must borrow from the .versao \
12064             String's backing storage — a fresh allocation here means the \
12065             accessor no longer names the substrate-primitive typed \
12066             dispatch and every downstream consumer would silently carry \
12067             a detached copy",
12068        );
12069        assert_eq!(
12070            req.len(),
12071            versao_slice.len(),
12072            "ChildSpec::versao_requirement and .versao.as_str() must \
12073             byte-equal in length as well as in address",
12074        );
12075    }
12076
12077    #[test]
12078    fn validate_gates_child_versao_through_lifted_accessor() {
12079        // Bilateral coherence pin: every `:children :versao` that
12080        // [`SupervisorSpec::validate`] accepts is one
12081        // [`crate::render::require_valid_versao_requirement`] accepts on
12082        // the accessor-projected value, and vice versa on the reject side.
12083        // This closes the "the validator reads through the accessor"
12084        // contract structurally — a future silent detour that made the
12085        // accessor return a different byte-string than the validator gates
12086        // against would surface here as a coverage mismatch, not as a
12087        // resolver-time semver-parse rejection at lacre-closure time far
12088        // from the caixa.lisp source. Peer of the sibling
12089        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
12090        // the per-`:children :caixa` axis and the M2
12091        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
12092        // on the peer per-`:upgrade-from :from` axis.
12093        //
12094        // Accept-set sweep: five Cargo-shaped semver requirement values
12095        // the upstream gate admits (caret / tilde / exact / wildcard /
12096        // bare-major).
12097        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12098            let s = SupervisorSpec {
12099                children: vec![ChildSpec {
12100                    caixa: "worker".into(),
12101                    versao: ok_req.into(),
12102                    restart: RestartPolicy::Permanent,
12103                }],
12104                ..SupervisorSpec::default()
12105            };
12106            s.validate().unwrap_or_else(|e| {
12107                panic!(
12108                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
12109                     (upstream versao-requirement gate accepts it): got {e:?}",
12110                );
12111            });
12112            let c = ChildSpec {
12113                caixa: "worker".into(),
12114                versao: ok_req.into(),
12115                restart: RestartPolicy::Permanent,
12116            };
12117            crate::render::require_valid_versao_requirement(
12118                c.versao_requirement(),
12119                || (),
12120                |_reason| (),
12121            )
12122            .unwrap_or_else(|()| {
12123                panic!(
12124                    "require_valid_versao_requirement must accept the accessor-projected \
12125                     :children :versao {ok_req:?}",
12126                );
12127            });
12128        }
12129        // Reject-set sweep: five requirement-violating shapes the upstream
12130        // gate refuses. The empty string closes the empty-first arm of the
12131        // shared [`crate::render::require_valid_versao_requirement`]
12132        // cascade; the four non-empty arms exercise distinct semver-parse
12133        // failure modes the M3 peer per-`:membros` reject-set already pins
12134        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
12135        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
12136        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
12137        // shared parser routing means the same reject-set must fail
12138        // identically at the M2 supervisor-tree per-`:children` accessor
12139        // arm here. Every rejection at the validator must correspond to a
12140        // rejection when the accessor's projected value is fed back
12141        // through the shared gate.
12142        //
12143        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
12144        // `"not-a-semver"` are intentionally *not* in the reject-set: the
12145        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
12146        // and the identifier-tail arm's grammar admits some non-canonical
12147        // shapes — matching what the M3 peer test suite already documents
12148        // as the shared parser's accept-set edges.)
12149        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
12150            let s = SupervisorSpec {
12151                children: vec![ChildSpec {
12152                    caixa: "worker".into(),
12153                    versao: bad_req.into(),
12154                    restart: RestartPolicy::Permanent,
12155                }],
12156                ..SupervisorSpec::default()
12157            };
12158            let err = s.validate().unwrap_err();
12159            assert!(
12160                matches!(
12161                    err,
12162                    SupervisorError::EmptyChildVersion { .. }
12163                        | SupervisorError::ChildVersaoInvalid { .. }
12164                ),
12165                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
12166                 via the versao-requirement gate: got {err:?}",
12167            );
12168            let c = ChildSpec {
12169                caixa: "worker".into(),
12170                versao: bad_req.into(),
12171                restart: RestartPolicy::Permanent,
12172            };
12173            assert!(
12174                crate::render::require_valid_versao_requirement(
12175                    c.versao_requirement(),
12176                    || (),
12177                    |_reason| (),
12178                )
12179                .is_err(),
12180                "require_valid_versao_requirement must reject the accessor-projected \
12181                 :children :versao {bad_req:?}",
12182            );
12183        }
12184    }
12185
12186    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
12187    //
12188    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
12189    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
12190    // already project the `String`-carry `(caixa, versao)` fields; the
12191    // `Copy`-composite-enum `restart` field is the third and final axis).
12192    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
12193    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
12194    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
12195    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
12196    // strategy scalar accessor — same "one typed dispatch on the substrate
12197    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
12198    // extended onto the M2 supervisor-slot per-`:children` restart-decision
12199    // axis. The pin below covers the accessor's byte-equal projection
12200    // against the raw field access across every variant in the closed
12201    // accept-set (`Permanent`, `Transient`, `Temporary`).
12202
12203    #[test]
12204    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
12205        // The canonical per-`:children` restart-decision-policy-scalar
12206        // pin: [`ChildSpec::restart`] must return the `:children :restart`
12207        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
12208        // typed slot's own [`RestartPolicy`] storage across every variant
12209        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
12210        // Pins against a future silent detour that re-derived the policy
12211        // from a peer axis (an accidental fallback to
12212        // `if is_supervisor_child { Permanent } else { Temporary }` that
12213        // collapsed the child's kind axis into the restart discriminator),
12214        // a variant remap the operator authors on one consumer without the
12215        // other, or a stale-derive detour that substituted
12216        // [`RestartPolicy::default`] when the field held any explicit
12217        // variant (which would silently collapse the distinction between
12218        // "author explicitly declared `:restart Permanent`" and "author
12219        // omitted the slot and inherited the default" the future
12220        // per-cluster restart-decision override slot depends on).
12221        //
12222        // Peer of the sibling per-`:supervisor`
12223        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12224        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
12225        // axis and the M3
12226        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12227        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
12228        // — same "the substrate-primitive accessor must byte-equal the raw
12229        // field access verbatim across every author-declared value"
12230        // discipline extended onto the M2 supervisor-slot per-`:children`
12231        // restart-decision-policy axis, closing the last unlifted axis on
12232        // the per-`:children` [`ChildSpec`] type.
12233        for restart in [
12234            RestartPolicy::Permanent,
12235            RestartPolicy::Transient,
12236            RestartPolicy::Temporary,
12237        ] {
12238            let c = ChildSpec {
12239                caixa: "worker".into(),
12240                versao: "^0.1".into(),
12241                restart,
12242            };
12243            assert_eq!(
12244                c.restart(),
12245                restart,
12246                "ChildSpec::restart must return :children :restart \
12247                 verbatim (got {:?}, expected {restart:?})",
12248                c.restart(),
12249            );
12250            assert_eq!(
12251                c.restart(),
12252                c.restart,
12253                "ChildSpec::restart accessor and .restart field access \
12254                 must byte-equal — the accessor is the substrate-primitive \
12255                 typed dispatch every downstream per-child restart-\
12256                 decision consumer must route through",
12257            );
12258        }
12259    }
12260
12261    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
12262    //
12263    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
12264    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
12265    // distribution-strategy accessor discipline onto the M2 supervisor-slot
12266    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
12267    // scalar axis. The two pins below cover (1) the accessor's byte-equal
12268    // projection against the raw field access across every variant in the
12269    // closed accept-set, and (2) the two-consumer coherence between the
12270    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
12271    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
12272    // carrier's `estrategia:` field — peer of the sibling M3
12273    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12274    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
12275    // pair on the per-`:placement` distribution-strategy axis.
12276
12277    #[test]
12278    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
12279        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
12280        // pin: [`SupervisorSpec::estrategia`] must return the
12281        // `:supervisor :estrategia` field verbatim as a
12282        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
12283        // [`RestartStrategy`] storage across every variant in the closed
12284        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
12285        // `SimpleOneForOne`). Pins against a future silent detour that
12286        // re-derived the strategy from a peer axis (an accidental
12287        // fallback to `if children.is_empty() { SimpleOneForOne } else {
12288        // OneForOne }` collapse that read the children-count axis into
12289        // the strategy discriminator), a variant remap the operator
12290        // authors on one consumer without the other, or a stale-derive
12291        // detour that substituted [`RestartStrategy::default`] when the
12292        // field held any explicit variant (which would silently collapse
12293        // the distinction between "author explicitly declared
12294        // `:estrategia OneForOne`" and "author omitted the slot and
12295        // inherited the default" the future per-cluster strategy override
12296        // slot depends on). Peer of the sibling M3
12297        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12298        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
12299        // axis — same "the substrate-primitive accessor must byte-equal
12300        // the raw field access verbatim across every author-declared
12301        // value" discipline extended onto the M2 supervisor-slot
12302        // per-`:supervisor` sibling-restart-strategy axis.
12303        for &estrategia in RestartStrategy::ALL {
12304            // `SimpleOneForOne` requires `children.is_empty()`; the peer
12305            // three strategies require a non-empty static children list.
12306            // Build each shape coherently so the pin's fixture would
12307            // itself pass [`SupervisorSpec::validate`] once fed through
12308            // the sibling coherence pin below — the byte-equal projection
12309            // asserted here is a strictly weaker property (a `Copy` field
12310            // read) that does not depend on `validate` running, but
12311            // keeping the fixture validate-clean means a future extension
12312            // of the pin to exercise `validate` end-to-end does not have
12313            // to re-author the children shape.
12314            //
12315            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
12316            // shape partition through the [`gen_platform::IsVariant`]
12317            // derive-generated
12318            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
12319            // than the raw `matches!(estrategia, RestartStrategy::
12320            // SimpleOneForOne)` open-coded pattern-match — same closed-
12321            // set-typed-enum arm-discriminator dispatch discipline the
12322            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
12323            // convergence (915a934) extended onto its two paired positive
12324            // / negated `matches!` sites and the peer
12325            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
12326            // predicate convergence (766ec63) extended onto the M3 mesh-
12327            // slot per-`:placement` distribution-strategy discriminator
12328            // axis. See the sibling `round_trip_all_strategies` and the
12329            // peer `manifest::tests::
12330            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
12331            // fixture for the two peer sites the same lift closes on.
12332            let children = if estrategia.is_simple_one_for_one() {
12333                Vec::new()
12334            } else {
12335                vec![ChildSpec {
12336                    caixa: "worker".into(),
12337                    versao: "^0.1".into(),
12338                    restart: RestartPolicy::Permanent,
12339                }]
12340            };
12341            let s = SupervisorSpec {
12342                estrategia,
12343                children,
12344                ..SupervisorSpec::default()
12345            };
12346            assert_eq!(
12347                s.estrategia(),
12348                estrategia,
12349                "SupervisorSpec::estrategia must return :supervisor :estrategia \
12350                 verbatim (got {:?}, expected {estrategia:?})",
12351                s.estrategia(),
12352            );
12353            assert_eq!(
12354                s.estrategia(),
12355                s.estrategia,
12356                "SupervisorSpec::estrategia accessor and .estrategia field \
12357                 access must byte-equal — the accessor is the substrate-\
12358                 primitive typed dispatch every downstream sibling-restart-\
12359                 strategy consumer must route through",
12360            );
12361        }
12362    }
12363
12364    #[test]
12365    fn validate_reads_through_lifted_estrategia_accessor() {
12366        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
12367        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
12368        // dispatch (which reads through [`SupervisorSpec::estrategia`]
12369        // to fan across the strategy-arm shape-gate cascades) and the
12370        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
12371        // error carrier's `estrategia:` field (which reads through
12372        // [`SupervisorSpec::estrategia`] to name the strategy the empty
12373        // `:children` list was declared against) must both key off the
12374        // lifted accessor, so any future rebrand on the typed slot's
12375        // reader shape lands at exactly one place. Pins the two-site
12376        // coherence by exercising the `NoChildren` error surface end-to-
12377        // end across every non-`SimpleOneForOne` variant and asserting
12378        // the surfaced `estrategia:` field byte-equals the accessor's
12379        // return. Peer of the sibling M3
12380        // `validate_placement_reads_through_lifted_estrategia_accessor`
12381        // (921fe1b) three-consumer coherence pin on the per-`:placement`
12382        // distribution-strategy axis.
12383        for estrategia in [
12384            RestartStrategy::OneForOne,
12385            RestartStrategy::OneForAll,
12386            RestartStrategy::RestForOne,
12387        ] {
12388            let s = SupervisorSpec {
12389                estrategia,
12390                children: Vec::new(),
12391                ..SupervisorSpec::default()
12392            };
12393            let err = s.validate().unwrap_err();
12394            match err {
12395                SupervisorError::NoChildren { estrategia: e } => {
12396                    assert_eq!(
12397                        e,
12398                        s.estrategia(),
12399                        "NoChildren.estrategia must byte-equal \
12400                         SupervisorSpec::estrategia() — the empty-`:children` \
12401                         refusal reads through the lifted accessor",
12402                    );
12403                    assert_eq!(
12404                        e, estrategia,
12405                        "NoChildren.estrategia must carry the author-declared \
12406                         :supervisor :estrategia variant verbatim (got {e:?}, \
12407                         expected {estrategia:?})",
12408                    );
12409                }
12410                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
12411            }
12412        }
12413    }
12414
12415    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
12416    //
12417    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
12418    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
12419    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
12420    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
12421    // The two pins below cover (1) the accessor's byte-equal projection
12422    // against the raw field access across every representative value in
12423    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
12424    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
12425    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
12426    // zero-floor / cap composition — the validate gate and the accessor
12427    // must route through the same substrate-primitive typed dispatch, so
12428    // any future silent detour that had the accessor perform a
12429    // bounds-collapsing clamp would fail here at caixa-core build time.
12430    // Peer of the sibling M3
12431    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12432    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
12433
12434    #[test]
12435    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
12436        // The canonical per-`:supervisor` restart-budget-count scalar pin:
12437        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
12438        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
12439        // typed slot's own `u32` storage, byte-equal to the raw field
12440        // access across every representative value in the accept-set —
12441        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
12442        // accept-set the surrounding [`SupervisorSpec::validate`] gate
12443        // carves out on the sibling `ZeroMaxRestarts` refusal),
12444        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
12445        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
12446        // (a past-the-guard sentinel that pins the accessor doesn't
12447        // perform a silent bounds-collapse into `1` on the zero arm —
12448        // validate rejects zero but the accessor must ship the raw slot
12449        // verbatim so a validate-time gate regression surfaces at the
12450        // emit boundary rather than being silently absorbed), `u32::MAX`
12451        // (a past-the-guard sentinel that pins the accessor doesn't
12452        // perform a silent bounds-collapse through
12453        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
12454        //
12455        // Peer of the sibling M3
12456        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12457        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
12458        // required-scalar axis — same "the substrate-primitive accessor
12459        // must byte-equal the raw field access verbatim across every
12460        // value in the `u32` accept-set" discipline extended onto the M2
12461        // supervisor-slot per-`:supervisor` restart-budget-count axis.
12462        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
12463            let s = SupervisorSpec {
12464                max_restarts,
12465                ..SupervisorSpec::default()
12466            };
12467            assert_eq!(
12468                s.max_restarts(),
12469                max_restarts,
12470                "SupervisorSpec::max_restarts must return :supervisor \
12471                 :max-restarts verbatim (got {}, expected {max_restarts})",
12472                s.max_restarts(),
12473            );
12474            assert_eq!(
12475                s.max_restarts(),
12476                s.max_restarts,
12477                "SupervisorSpec::max_restarts accessor and .max_restarts \
12478                 field access must byte-equal — the accessor is the \
12479                 substrate-primitive typed dispatch every downstream \
12480                 restart-budget-count consumer must route through",
12481            );
12482        }
12483    }
12484
12485    #[test]
12486    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
12487        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
12488        // zero-floor + upper-cap bracket must key off
12489        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
12490        // field access. Structurally: a `SupervisorSpec { max_restarts:
12491        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
12492        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
12493        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
12494        // (with the offending count carried verbatim from the accessor
12495        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
12496        // lower boundary of the accept-set) plus a `SupervisorSpec {
12497        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
12498        // boundary) must pass validate. The four together jointly pin the
12499        // accessor + validate-gate composition: any future silent detour
12500        // that had the accessor return a fresh `1` on the zero arm (a
12501        // `.max_restarts().max(1)` collapse) would silently absorb the
12502        // `ZeroMaxRestarts` refusal at the accessor boundary and the
12503        // validate gate would accept a struct-literal `SupervisorSpec {
12504        // max_restarts: 0, .. }` — the composition pin catches that at
12505        // caixa-core build time.
12506        //
12507        // Peer of the sibling M3
12508        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
12509        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
12510        // composition axis — same "the validate / shape-gate predicate
12511        // must route through the substrate-primitive typed dispatch"
12512        // discipline extended onto the peer M2 supervisor-slot
12513        // required-`u32` composition axis.
12514        let child = ChildSpec {
12515            caixa: "worker".into(),
12516            versao: "^0.1".into(),
12517            restart: RestartPolicy::Permanent,
12518        };
12519        // Zero-floor arm.
12520        let s = SupervisorSpec {
12521            max_restarts: 0,
12522            children: vec![child.clone()],
12523            ..SupervisorSpec::default()
12524        };
12525        assert_eq!(
12526            s.validate().unwrap_err(),
12527            SupervisorError::ZeroMaxRestarts,
12528            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
12529             — the accessor and the validate gate must route through the \
12530             same substrate-primitive typed dispatch on the zero-floor arm",
12531        );
12532        // Cap arm — the surfaced `max_restarts:` field must byte-equal
12533        // the accessor's return so a future rebrand on the accessor
12534        // lands in the diagnostic without a coordinated rewrite.
12535        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12536        let s = SupervisorSpec {
12537            max_restarts: over_cap,
12538            children: vec![child.clone()],
12539            ..SupervisorSpec::default()
12540        };
12541        match s.validate().unwrap_err() {
12542            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
12543                assert_eq!(
12544                    max_restarts,
12545                    s.max_restarts(),
12546                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
12547                     SupervisorSpec::max_restarts() — the cap-arm refusal \
12548                     reads through the lifted accessor",
12549                );
12550                assert_eq!(
12551                    max_restarts, over_cap,
12552                    "MaxRestartsExceedsCap.max_restarts must carry the \
12553                     author-declared :supervisor :max-restarts value \
12554                     verbatim (got {max_restarts}, expected {over_cap})",
12555                );
12556            }
12557            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
12558        }
12559        // Lower + upper accept-set boundaries.
12560        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
12561            let s = SupervisorSpec {
12562                max_restarts,
12563                children: vec![child.clone()],
12564                ..SupervisorSpec::default()
12565            };
12566            assert!(
12567                s.validate().is_ok(),
12568                "validate must accept max_restarts == {max_restarts} \
12569                 (an accept-set boundary of \
12570                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
12571            );
12572        }
12573    }
12574
12575    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
12576    //
12577    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
12578    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
12579    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
12580    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
12581    // supervisor-slot per-`:supervisor` restart-intensity-denominator
12582    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
12583    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
12584    // per-`:supervisor` scalar-value axis. The three pins below cover
12585    // (1) the accessor's byte-equal projection against the raw field
12586    // access across every representative value in the `Option<Duration>`
12587    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
12588    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
12589    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
12590    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
12591    // `if let Some(w) = self.restart_window() { … }` bracket-arm
12592    // composition — the validate gate and the accessor must route through
12593    // the same substrate-primitive typed dispatch, so any future silent
12594    // detour that had the accessor perform a bounds-collapsing clamp
12595    // would fail here at caixa-core build time, and (3) the accessor's
12596    // by-copy idempotence pin — the returned `Option<Duration>` must
12597    // outlive `&self` and two successive calls must return byte-equal
12598    // values. Peer of the sibling M2
12599    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12600    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
12601    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12602    // (7073d0f) pin on the per-`:politicas :timeout` axis.
12603
12604    #[test]
12605    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
12606        // The canonical per-`:supervisor` restart-intensity-denominator
12607        // scalar pin: [`SupervisorSpec::restart_window`] must return the
12608        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
12609        // `Option<Duration>`, `Copy`-projected from the typed slot's own
12610        // `Option<Duration>` storage, byte-equal to the raw field access
12611        // across every representative value in the accept-set — `None`
12612        // (the "never reset — every restart across the supervisor's
12613        // lifetime counts against the sibling `:max-restarts` budget"
12614        // sentinel the field's own docstring names and the peer
12615        // `validate_accepts_none_restart_window` pin locks in on the
12616        // [`SupervisorSpec::validate`] entry-side),
12617        // `Some(Duration::from_millis(1))` (the structural minimum a
12618        // validated `:restart-window` may carry, the integer-millisecond
12619        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
12620        // everything sub-ms; `Duration::ZERO` is separately rejected by
12621        // [`SupervisorError::RestartWindowZero`]),
12622        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
12623        // surrounding [`SupervisorSpec::validate`] gate carves out on the
12624        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
12625        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
12626        // accessor doesn't perform a silent bounds-collapse into `None` on
12627        // the zero-Duration arm — validate rejects zero but the accessor
12628        // must ship the raw slot verbatim so a validate-time gate
12629        // regression surfaces at the emit boundary rather than being
12630        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12631        // sentinel that pins the accessor doesn't perform a silent
12632        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12633        // return path).
12634        //
12635        // Peer of the sibling M2
12636        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12637        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12638        // sibling M3
12639        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12640        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12641        // substrate-primitive accessor must byte-equal the raw field
12642        // access verbatim across every value in the `Option<Duration>`
12643        // accept-set" discipline extended onto the M2 supervisor-slot
12644        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12645        // silent detour that re-derived the restart-window from a peer
12646        // axis (an accidental `.max_restarts.into()` collapse that read
12647        // the restart-budget-count as a duration — the two axes serve
12648        // different halves of the `MaxIntensity / Period` restart-
12649        // intensity ratio, and confusing them silently inverts the
12650        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12651        // "zero means never reset" collapse (the canonical
12652        // `Option<Duration>` → `Duration` collapse footgun the
12653        // [`SupervisorError::RestartWindowZero`] validate arm guards on
12654        // the peer zero-floor axis; a zero period either trips on the
12655        // first failure or never trips depending on operator
12656        // interpretation, neither of which is the author's "never reset"
12657        // intent that `None` expresses structurally), or a per-arm
12658        // variant swap that landed on one consumer without the other.
12659        for restart_window in [
12660            None,
12661            Some(Duration::from_millis(1)),
12662            Some(SUPERVISOR_RESTART_WINDOW_MAX),
12663            Some(Duration::ZERO),
12664            Some(Duration::MAX),
12665        ] {
12666            let s = SupervisorSpec {
12667                restart_window,
12668                ..SupervisorSpec::default()
12669            };
12670            assert_eq!(
12671                s.restart_window(),
12672                restart_window,
12673                "SupervisorSpec::restart_window must return :supervisor \
12674                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12675                s.restart_window(),
12676            );
12677            assert_eq!(
12678                s.restart_window(),
12679                s.restart_window,
12680                "SupervisorSpec::restart_window accessor and \
12681                 .restart_window field access must byte-equal — the \
12682                 accessor is the substrate-primitive typed dispatch every \
12683                 downstream restart-intensity-denominator consumer must \
12684                 route through",
12685            );
12686        }
12687    }
12688
12689    #[test]
12690    fn validate_restart_window_bracket_arm_routes_through_accessor() {
12691        // Composition pin: [`SupervisorSpec::validate`]'s
12692        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12693        // zero-floor + integer-millisecond canonical-form + upper-cap
12694        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12695        // the raw `.restart_window` field access. Structurally: a
12696        // `SupervisorSpec { restart_window: None, .. }` must pass the
12697        // arm gate structurally (the `if let Some(_)` shape returns
12698        // early on the `None` arm — the accessor and the validate gate
12699        // must agree on `None → skip the bracket cascade` so an authored
12700        // `:restart-window ()` structurally routes through the "never
12701        // reset" sentinel path), a `SupervisorSpec { restart_window:
12702        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12703        // refusal exactly, a `SupervisorSpec { restart_window:
12704        // Some(Duration::from_micros(1500)), .. }` must surface the
12705        // `RestartWindowNotCanonical` refusal exactly (with the offending
12706        // duration carried verbatim from the accessor return), a
12707        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12708        // + Duration::from_millis(1)), .. }` must surface the
12709        // `RestartWindowExceedsCap` refusal exactly (with the offending
12710        // duration carried verbatim from the accessor return), and a
12711        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12712        // .. }` (the lower boundary of the accept-set) plus a
12713        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12714        // .. }` (the upper boundary) must pass validate. The six together
12715        // jointly pin the accessor + validate-gate composition: any future
12716        // silent detour that had the accessor return a fresh `None` on any
12717        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12718        // collapse) would silently absorb the `RestartWindowZero` refusal
12719        // at the accessor boundary and the validate gate would accept a
12720        // struct-literal `SupervisorSpec { restart_window:
12721        // Some(Duration::ZERO), .. }` — the composition pin catches that
12722        // at caixa-core build time.
12723        //
12724        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12725        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12726        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12727        // accessor-composition pin on the per-`:politicas :timeout` axis —
12728        // same "the validate / shape-gate predicate must route through
12729        // the substrate-primitive typed dispatch" discipline extended
12730        // onto the peer M2 supervisor-slot optional-`Duration` axis.
12731        let child = ChildSpec {
12732            caixa: "worker".into(),
12733            versao: "^0.1".into(),
12734            restart: RestartPolicy::Permanent,
12735        };
12736        // None arm — must not surface any :restart-window-shaped refusal;
12737        // the `if let Some(_)` bracket returns early on `None` structurally.
12738        let s = SupervisorSpec {
12739            restart_window: None,
12740            children: vec![child.clone()],
12741            ..SupervisorSpec::default()
12742        };
12743        assert!(
12744            s.validate().is_ok(),
12745            "validate must accept restart_window: None (the never-reset \
12746             sentinel) — the `if let Some(_)` bracket returns early on \
12747             the None arm and the accessor must agree",
12748        );
12749        // Zero-floor arm.
12750        let s = SupervisorSpec {
12751            restart_window: Some(Duration::ZERO),
12752            children: vec![child.clone()],
12753            ..SupervisorSpec::default()
12754        };
12755        assert_eq!(
12756            s.validate().unwrap_err(),
12757            SupervisorError::RestartWindowZero,
12758            "validate must reject restart_window == Some(Duration::ZERO) \
12759             with RestartWindowZero — the accessor and the validate gate \
12760             must route through the same substrate-primitive typed \
12761             dispatch on the zero-floor arm",
12762        );
12763        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
12764        // byte-equal the accessor's return so a future rebrand on the
12765        // accessor lands in the diagnostic without a coordinated rewrite.
12766        let sub_ms = Duration::from_micros(1500);
12767        let s = SupervisorSpec {
12768            restart_window: Some(sub_ms),
12769            children: vec![child.clone()],
12770            ..SupervisorSpec::default()
12771        };
12772        match s.validate().unwrap_err() {
12773            SupervisorError::RestartWindowNotCanonical { window } => {
12774                assert_eq!(
12775                    Some(window),
12776                    s.restart_window(),
12777                    "RestartWindowNotCanonical.window must byte-equal \
12778                     SupervisorSpec::restart_window().unwrap() — the \
12779                     non-canonical-arm refusal reads through the lifted \
12780                     accessor",
12781                );
12782                assert_eq!(
12783                    window, sub_ms,
12784                    "RestartWindowNotCanonical.window must carry the \
12785                     author-declared :supervisor :restart-window value \
12786                     verbatim (got {window:?}, expected {sub_ms:?})",
12787                );
12788            }
12789            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
12790        }
12791        // Cap arm — the surfaced `window:` field must byte-equal the
12792        // accessor's return.
12793        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12794        let s = SupervisorSpec {
12795            restart_window: Some(over_cap),
12796            children: vec![child.clone()],
12797            ..SupervisorSpec::default()
12798        };
12799        match s.validate().unwrap_err() {
12800            SupervisorError::RestartWindowExceedsCap { window } => {
12801                assert_eq!(
12802                    Some(window),
12803                    s.restart_window(),
12804                    "RestartWindowExceedsCap.window must byte-equal \
12805                     SupervisorSpec::restart_window().unwrap() — the \
12806                     cap-arm refusal reads through the lifted accessor",
12807                );
12808                assert_eq!(
12809                    window, over_cap,
12810                    "RestartWindowExceedsCap.window must carry the \
12811                     author-declared :supervisor :restart-window value \
12812                     verbatim (got {window:?}, expected {over_cap:?})",
12813                );
12814            }
12815            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
12816        }
12817        // Lower + upper accept-set boundaries.
12818        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
12819            let s = SupervisorSpec {
12820                restart_window: Some(restart_window),
12821                children: vec![child.clone()],
12822                ..SupervisorSpec::default()
12823            };
12824            assert!(
12825                s.validate().is_ok(),
12826                "validate must accept restart_window == Some({restart_window:?}) \
12827                 (an accept-set boundary of \
12828                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
12829            );
12830        }
12831    }
12832
12833    #[test]
12834    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
12835        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
12836        // `Option<Duration>` by copy — `Duration` is `Copy` (so
12837        // `Option<Duration>` is `Copy`) and the accessor must return by
12838        // value, not by reference. Peer of the sibling M2
12839        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
12840        // per-`:limits :wall-clock` axis and the sibling M3
12841        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
12842        // per-`:politicas :timeout` axis, extended onto the peer M2
12843        // supervisor-slot `Option<Duration>` copy-invariant shape — the
12844        // accessor's returned `Option<Duration>` must outlive `&self`
12845        // (multiple calls must return equal values from a dropped-`&self`
12846        // copy, since the returned Option carries no borrow), and calling
12847        // the accessor twice on the same SupervisorSpec must yield the
12848        // same `Option<Duration>` verbatim (idempotent, no side effects
12849        // on `&self`).
12850        //
12851        // Pins against a future silent detour that returned
12852        // `Option<&Duration>` (which would type-check but silently break
12853        // every downstream caller — the future wasm-operator's
12854        // per-supervisor restart-intensity counter consumes `Duration` by
12855        // value and `&Duration` would fold to a detached copy at the call
12856        // site), an accidental `Option::as_ref()` projection
12857        // (`self.restart_window.as_ref()` would also type-check but
12858        // return `Option<&Duration>`), or a one-arm-only accessor that
12859        // reads `Some(*w)` in the Some arm but reads a fresh
12860        // `Default::default()` (which would collapse to `Duration::ZERO`,
12861        // not `None`) in the None arm — a footgun the
12862        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
12863        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
12864        // requires `Period > 0` and `None` structurally expresses "never
12865        // reset" instead.
12866        for restart_window in [
12867            None,
12868            Some(Duration::from_millis(1)),
12869            Some(Duration::from_secs(60)),
12870            Some(SUPERVISOR_RESTART_WINDOW_MAX),
12871        ] {
12872            let s = SupervisorSpec {
12873                restart_window,
12874                ..SupervisorSpec::default()
12875            };
12876            let first = s.restart_window();
12877            let second = s.restart_window();
12878            assert_eq!(
12879                first, second,
12880                "SupervisorSpec::restart_window must be idempotent — two \
12881                 successive calls on the same &self must return the \
12882                 same Option<Duration>",
12883            );
12884            assert_eq!(
12885                first, restart_window,
12886                "SupervisorSpec::restart_window must return :supervisor \
12887                 :restart-window verbatim by copy — got {first:?}, \
12888                 expected {restart_window:?}",
12889            );
12890        }
12891    }
12892
12893    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
12894    //
12895    // The [`SupervisorSpec::children`] accessor lift is the seed of the
12896    // slice-return (`&[T]`) accessor discipline on the substrate — the four
12897    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
12898    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
12899    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
12900    // access at the time of this seed, and inherit this pin family's
12901    // discipline as future compounding runs migrate their consumers. The
12902    // three pins below cover (1) the accessor's byte-equal projection
12903    // against the raw field access across the empty / singleton / cohort
12904    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
12905    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
12906    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
12907    // consumer routing through the accessor on both arms, and (3) the
12908    // per-child validate loop's traversal reading the same slice-view the
12909    // accessor projects. Peer of the sibling M2
12910    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12911    // two-consumer coherence pin on the per-`:supervisor`
12912    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
12913    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
12914
12915    #[test]
12916    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
12917        // The canonical per-`:supervisor` static-child-list scalar-shape
12918        // pin: [`SupervisorSpec::children`] must return the `:supervisor
12919        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
12920        // slice-view over the same backing buffer the raw
12921        // `self.children.as_slice()` field access borrows from, byte-
12922        // equal across every representative fixture in the accept-set —
12923        // the empty slice (the `SimpleOneForOne`-arm sentinel),
12924        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
12925        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
12926        // with the peer three restart-policy variants in play).
12927        //
12928        // Pins against a future silent detour that returned
12929        // `&Vec<ChildSpec>` (which would type-check but leak the
12930        // storage-side `Vec`'s grow/push/reserve surface no consumer of
12931        // the typed view reaches for), a fresh-allocated
12932        // `Vec<ChildSpec>` copy (which would type-check via a coercion
12933        // but silently break every downstream caller that relied on the
12934        // slice sharing the backing buffer's identity), or an
12935        // out-of-order or length-drifted projection (which would silently
12936        // split the per-child validate loop's traversal input from the
12937        // paired partition-dispatch `.is_empty()` probe's input).
12938        //
12939        // Peer of the sibling
12940        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12941        // (eafb619) `Copy`-composite-enum byte-equal pin on the
12942        // per-`:supervisor` sibling-restart-strategy axis, extended onto
12943        // the per-`:supervisor` static-child-list `Vec`-carry axis.
12944        let fixtures: Vec<Vec<ChildSpec>> = vec![
12945            Vec::new(),
12946            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12947            vec![
12948                child("worker", "^0.1", RestartPolicy::Permanent),
12949                child("cache-server", "^0.1", RestartPolicy::Transient),
12950            ],
12951            vec![
12952                child("worker", "^0.1", RestartPolicy::Permanent),
12953                child("cache-server", "^0.1", RestartPolicy::Transient),
12954                child("scratch-job", "^0.1", RestartPolicy::Temporary),
12955            ],
12956        ];
12957        for children in fixtures {
12958            let s = SupervisorSpec {
12959                children: children.clone(),
12960                ..SupervisorSpec::default()
12961            };
12962            assert_eq!(
12963                s.children(),
12964                children.as_slice(),
12965                "SupervisorSpec::children must return :supervisor \
12966                 :children verbatim (got {:?}, expected {:?})",
12967                s.children(),
12968                children.as_slice(),
12969            );
12970            assert_eq!(
12971                s.children(),
12972                s.children.as_slice(),
12973                "SupervisorSpec::children accessor and \
12974                 .children.as_slice() field access must byte-equal — \
12975                 the accessor is the substrate-primitive typed \
12976                 dispatch every downstream static-child-list consumer \
12977                 must route through",
12978            );
12979            assert_eq!(
12980                s.children().len(),
12981                s.children.len(),
12982                "SupervisorSpec::children().len() must byte-equal \
12983                 self.children.len() — a length-drift would silently \
12984                 split the paired partition-dispatch `.is_empty()` \
12985                 probe input from the per-child validate loop's \
12986                 traversal input",
12987            );
12988        }
12989    }
12990
12991    #[test]
12992    fn validate_reads_through_lifted_children_accessor() {
12993        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
12994        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
12995        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
12996        // when the accessor projects a non-empty slice under a
12997        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
12998        // `self.children().is_empty()` refusal probe (which must trip
12999        // [`SupervisorError::NoChildren`] when the accessor projects the
13000        // empty slice under any peer estrategia), and the per-child
13001        // validate loop's `for child in self.children()` traversal
13002        // (which must reach every entry in the same order the accessor
13003        // projects) must all key off the lifted accessor, so any future
13004        // rebrand on the typed slot's reader shape lands at exactly one
13005        // place. Pins the three-site coherence by exercising each
13006        // production consumer end-to-end: (1) the
13007        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
13008        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
13009        // refusal under the empty slice + non-`SimpleOneForOne`
13010        // estrategia across every peer variant, and (3) the per-child
13011        // duplicate-detection surface fires on the second entry of a
13012        // two-child cohort that shares a `:caixa` name (which requires
13013        // the loop to reach both entries — a first-entry-only projection
13014        // would silently pass since the dedup HashSet has room for the
13015        // first insert).
13016        //
13017        // Peer of the sibling M2
13018        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13019        // two-consumer coherence pin on the per-`:supervisor`
13020        // sibling-restart-strategy axis, extended onto the
13021        // per-`:supervisor` static-child-list `Vec`-carry axis.
13022
13023        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
13024        // `SimpleOneForOne` estrategia must trip
13025        // `SimpleOneForOneWithStaticChildren`.
13026        let s = SupervisorSpec {
13027            estrategia: RestartStrategy::SimpleOneForOne,
13028            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13029            ..SupervisorSpec::default()
13030        };
13031        assert_eq!(
13032            s.validate().unwrap_err(),
13033            SupervisorError::SimpleOneForOneWithStaticChildren,
13034            "SimpleOneForOne + non-empty children must trip \
13035             SimpleOneForOneWithStaticChildren — the accessor projects \
13036             a non-empty slice, and the SimpleOneForOne-arm refusal \
13037             probe reads through the lifted accessor",
13038        );
13039        assert!(
13040            !s.children().is_empty(),
13041            "the SimpleOneForOne-arm refusal input must be a non-empty \
13042             slice per the accessor's projection",
13043        );
13044
13045        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
13046        // under any peer estrategia must trip `NoChildren`.
13047        for estrategia in [
13048            RestartStrategy::OneForOne,
13049            RestartStrategy::OneForAll,
13050            RestartStrategy::RestForOne,
13051        ] {
13052            let s = SupervisorSpec {
13053                estrategia,
13054                children: Vec::new(),
13055                ..SupervisorSpec::default()
13056            };
13057            match s.validate().unwrap_err() {
13058                SupervisorError::NoChildren { estrategia: e } => {
13059                    assert_eq!(
13060                        e, estrategia,
13061                        "NoChildren.estrategia must carry the author-\
13062                         declared :supervisor :estrategia variant \
13063                         verbatim (got {e:?}, expected {estrategia:?})",
13064                    );
13065                }
13066                other => panic!(
13067                    "expected NoChildren, got {other:?} for \
13068                     estrategia={estrategia:?}"
13069                ),
13070            }
13071            assert!(
13072                s.children().is_empty(),
13073                "the non-SimpleOneForOne-arm refusal input must be the \
13074                 empty slice per the accessor's projection",
13075            );
13076        }
13077
13078        // (3) Per-child validate loop: a two-child cohort that shares a
13079        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
13080        // reach both entries through the accessor.
13081        let s = SupervisorSpec {
13082            estrategia: RestartStrategy::OneForOne,
13083            children: vec![
13084                child("worker", "^0.1", RestartPolicy::Permanent),
13085                child("worker", "^0.2", RestartPolicy::Transient),
13086            ],
13087            ..SupervisorSpec::default()
13088        };
13089        match s.validate().unwrap_err() {
13090            SupervisorError::DuplicateChildCaixa { caixa } => {
13091                assert_eq!(
13092                    caixa, "worker",
13093                    "DuplicateChildCaixa.caixa must carry the shared \
13094                     child `:caixa` name verbatim",
13095                );
13096            }
13097            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
13098        }
13099        assert_eq!(
13100            s.children().len(),
13101            2,
13102            "the per-child validate loop's traversal input must be a \
13103             two-element slice per the accessor's projection",
13104        );
13105    }
13106
13107    // Shared helper for the M2 per-`:children` per-slot-gate ≡
13108    // `validate` equivalence pins: builds an `OneForOne`-estrategia
13109    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
13110    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
13111    // bracket all pass cleanly so the sole failing surface is the
13112    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
13113    // pins the two-altitude equivalence on the paired probe.
13114    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
13115        let s = SupervisorSpec {
13116            estrategia: RestartStrategy::OneForOne,
13117            children,
13118            ..SupervisorSpec::default()
13119        };
13120        let via_gate = s.validate_children().unwrap_err();
13121        let via_validate = s.validate().unwrap_err();
13122        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
13123        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
13124        assert_eq!(
13125            via_gate, via_validate,
13126            "per-slot gate ≡ validate() must discriminate the same \
13127             refusal shape",
13128        );
13129    }
13130
13131    #[test]
13132    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
13133        // Fail-before-pass-after equivalence pin on the M2
13134        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
13135        // convergence — sibling of the M3 mesh-slot
13136        // `validate_membros_*` / `validate_contratos_*` /
13137        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
13138        // peer per-entry axes. Sweeps four of the five refusal shapes
13139        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
13140        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
13141        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
13142        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
13143        // duplicate-`:caixa` fan-out. Companion pin
13144        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
13145        // covers `ChildVersaoInvalid` (whose parser-owned reason string
13146        // needs pattern-matching, not equality) and the clean-pass
13147        // canonical fixture; together the two pins guarantee the
13148        // per-slot gate and `validate` discriminate the same set on
13149        // every per-child-covered input.
13150        assert_validate_children_matches_gate(
13151            vec![child("", "^0.1", RestartPolicy::Permanent)],
13152            &SupervisorError::EmptyChildName,
13153        );
13154        assert_validate_children_matches_gate(
13155            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
13156            &SupervisorError::ChildCaixaInvalid {
13157                caixa: "Worker".into(),
13158                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
13159            },
13160        );
13161        assert_validate_children_matches_gate(
13162            vec![child("worker", "", RestartPolicy::Permanent)],
13163            &SupervisorError::EmptyChildVersion {
13164                caixa: "worker".into(),
13165            },
13166        );
13167        assert_validate_children_matches_gate(
13168            vec![
13169                child("worker", "^0.1", RestartPolicy::Permanent),
13170                child("worker", "^0.2", RestartPolicy::Transient),
13171            ],
13172            &SupervisorError::DuplicateChildCaixa {
13173                caixa: "worker".into(),
13174            },
13175        );
13176    }
13177
13178    #[test]
13179    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
13180        // Second half of the two-altitude equivalence pin — covers the
13181        // one refusal shape whose reason string is parser-owned
13182        // (`ChildVersaoInvalid`, whose reason comes from the shared
13183        // [`crate::version::parse_requirement`] impl and may drift) and
13184        // the clean-pass canonical fixture. Sibling pin
13185        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
13186        // covers the four equality-comparable refusal shapes.
13187        let s_bad_versao = SupervisorSpec {
13188            estrategia: RestartStrategy::OneForOne,
13189            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
13190            ..SupervisorSpec::default()
13191        };
13192        let via_gate = s_bad_versao.validate_children().unwrap_err();
13193        let via_validate = s_bad_versao.validate().unwrap_err();
13194        match (&via_gate, &via_validate) {
13195            (
13196                SupervisorError::ChildVersaoInvalid {
13197                    caixa: cg,
13198                    versao: vg,
13199                    ..
13200                },
13201                SupervisorError::ChildVersaoInvalid {
13202                    caixa: cv,
13203                    versao: vv,
13204                    ..
13205                },
13206            ) => {
13207                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
13208                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
13209                assert_eq!(cv, "worker", "validate() :caixa carrier");
13210                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
13211            }
13212            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
13213        }
13214        assert_eq!(
13215            via_gate, via_validate,
13216            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
13217        );
13218
13219        let s_ok = SupervisorSpec {
13220            estrategia: RestartStrategy::OneForOne,
13221            children: vec![
13222                child("worker-a", "^0.1", RestartPolicy::Permanent),
13223                child("worker-b", "~0.2.3", RestartPolicy::Transient),
13224                child("collector", "*", RestartPolicy::Temporary),
13225            ],
13226            ..SupervisorSpec::default()
13227        };
13228        s_ok.validate_children()
13229            .expect("per-slot gate must accept the clean-pass fixture");
13230        s_ok.validate()
13231            .expect("validate() must accept the clean-pass fixture");
13232    }
13233
13234    #[test]
13235    fn validate_children_is_self_contained_on_children_slot() {
13236        // Self-containment pin: [`SupervisorSpec::validate_children`]
13237        // resolves the per-child cascade against `&self` alone, without
13238        // depending on the peer `:estrategia`/`:max-restarts`/
13239        // `:restart-window` gates having run first — same posture the M3
13240        // peer per-slot gates carry (`validate_membros`,
13241        // `validate_contratos`, `validate_entrada`, `validate_placement`,
13242        // routing through their own oracles rather than borrowing state
13243        // threaded down from `validate`). A future consumer that reaches
13244        // the per-slot gate directly on a spec whose peer slots would
13245        // fail `validate` still surfaces the per-child refusal, not the
13246        // peer refusal.
13247        //
13248        // Construct a spec whose `:max-restarts` is `0` (which would
13249        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
13250        // the partition-dispatch) and whose `:children` carries a
13251        // `DuplicateChildCaixa` shape: the per-slot gate called directly
13252        // must surface `DuplicateChildCaixa`, proving it does not depend
13253        // on the peer `:max-restarts` gate running first.
13254        let s = SupervisorSpec {
13255            estrategia: RestartStrategy::OneForOne,
13256            max_restarts: 0,
13257            restart_window: Some(Duration::from_secs(60)),
13258            children: vec![
13259                child("worker", "^0.1", RestartPolicy::Permanent),
13260                child("worker", "^0.2", RestartPolicy::Transient),
13261            ],
13262        };
13263        assert_eq!(
13264            s.validate_children().unwrap_err(),
13265            SupervisorError::DuplicateChildCaixa {
13266                caixa: "worker".into(),
13267            },
13268            "per-slot gate must resolve per-child refusal directly against \
13269             `&self` — a dependency on the peer `:max-restarts` gate \
13270             running first would surface ZeroMaxRestarts here instead",
13271        );
13272        // The peer gate is still the surface `validate` reaches — pin
13273        // the ordering to establish that `validate_children` truly runs
13274        // last in `validate`'s dispatch, so a direct call bypasses the
13275        // peer gates on any spec whose per-child cascade would fail.
13276        assert_eq!(
13277            s.validate().unwrap_err(),
13278            SupervisorError::ZeroMaxRestarts,
13279            "validate() must surface the peer `:max-restarts` gate before \
13280             reaching the per-child cascade — this pins the dispatch \
13281             ordering the per-slot gate's self-containment complements",
13282        );
13283    }
13284
13285    #[test]
13286    fn child_spec_restart_accessor_is_const_fn() {
13287        // The [`ChildSpec::restart`] per-`:children` restart-decision-
13288        // policy `Copy`-return scalar accessor is declared
13289        // `#[must_use] pub const fn` — matching the sibling M2
13290        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
13291        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
13292        // both converted in this commit), the sibling M2
13293        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
13294        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
13295        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
13296        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
13297        // `Copy`-return `pub const fn` scalar accessors on the sibling
13298        // M3 surface. Pin the `const`-eval posture here so a future
13299        // accidental downgrade to non-`const` (an added runtime helper
13300        // reachable only from a non-`const` context, an
13301        // `Option<RestartPolicy>`-shape migration on the per-child
13302        // restart-decision axis once heterogeneous per-cluster
13303        // restart-policy overlays land that would silently drop the
13304        // `const` qualifier, a manual hand-rolled shadow) trips at
13305        // caixa-core build time rather than surfacing as a downstream
13306        // `const`-context regression far from the declaration.
13307        //
13308        // Same shape as the sibling M3
13309        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
13310        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
13311        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
13312        // accessor axis — the load-bearing witness lives in the
13313        // module-scope `const fn` wrapper `restart_via_const_fn` below:
13314        // a body that calls [`ChildSpec::restart`] under a `const fn`
13315        // signature is well-formed only when the callee is itself
13316        // `const fn`, so any future accidental downgrade of
13317        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
13318        // build time (const-eval E0015 `cannot call non-const method`),
13319        // strictly stronger than a runtime `assert!(CONST)` and
13320        // side-stepping the destructor-in-const restriction that
13321        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
13322        // items on `ChildSpec`'s `String` carriers.
13323        //
13324        // The runtime body sweeps every closed-set [`RestartPolicy`]
13325        // arm and asserts the wrapped and direct dispatches agree.
13326        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
13327            c.restart()
13328        }
13329        for restart in [
13330            RestartPolicy::Permanent,
13331            RestartPolicy::Transient,
13332            RestartPolicy::Temporary,
13333        ] {
13334            let c = ChildSpec {
13335                caixa: "worker".into(),
13336                versao: "^0.1".into(),
13337                restart,
13338            };
13339            assert_eq!(
13340                restart_via_const_fn(&c),
13341                c.restart(),
13342                "const-fn-wrapped and direct dispatch on \
13343                 ChildSpec::restart must agree for {restart:?}",
13344            );
13345            assert_eq!(
13346                c.restart(),
13347                restart,
13348                "ChildSpec::restart must return the storage-side \
13349                 RestartPolicy verbatim for {restart:?} (a violation \
13350                 means the accessor stopped being a raw field-return \
13351                 copy)",
13352            );
13353        }
13354    }
13355
13356    #[test]
13357    fn supervisor_spec_estrategia_accessor_is_const_fn() {
13358        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
13359        // sibling-restart-strategy `Copy`-return scalar accessor is
13360        // declared `#[must_use] pub const fn` — matching the sibling M2
13361        // per-`:children` [`ChildSpec::restart`] (pinned by
13362        // [`child_spec_restart_accessor_is_const_fn`] above, both
13363        // converted in this commit), the sibling M2 per-`:supervisor`
13364        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
13365        // accessor already `pub const fn`, and mirroring the peer M3
13366        // mesh-slot per-`:placement`
13367        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
13368        // `pub const fn` scalar accessor whose method-name discipline
13369        // the [`SupervisorSpec::estrategia`] method was authored to
13370        // match. Pin the `const`-eval posture here so a future
13371        // accidental downgrade to non-`const` (an added runtime helper
13372        // reachable only from a non-`const` context, an
13373        // `Option<RestartStrategy>`-shape migration once the substrate
13374        // grows per-cluster strategy overlays that would silently drop
13375        // the `const` qualifier, a manual hand-rolled shadow) trips at
13376        // caixa-core build time rather than surfacing as a downstream
13377        // `const`-context regression far from the declaration.
13378        //
13379        // Same shape as the sibling
13380        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
13381        // load-bearing witness lives in the module-scope `const fn`
13382        // wrapper `estrategia_via_const_fn` below: a body that calls
13383        // [`SupervisorSpec::estrategia`] under a `const fn` signature
13384        // is well-formed only when the callee is itself `const fn`,
13385        // side-stepping the destructor-in-const restriction that would
13386        // otherwise block a direct
13387        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
13388        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
13389        // carriers.
13390        //
13391        // The runtime body sweeps every closed-set [`RestartStrategy`]
13392        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
13393        // direct dispatches agree.
13394        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
13395            s.estrategia()
13396        }
13397        for &estrategia in RestartStrategy::ALL {
13398            let s = SupervisorSpec {
13399                estrategia,
13400                max_restarts: 5,
13401                restart_window: Some(Duration::from_secs(60)),
13402                children: Vec::new(),
13403            };
13404            assert_eq!(
13405                estrategia_via_const_fn(&s),
13406                s.estrategia(),
13407                "const-fn-wrapped and direct dispatch on \
13408                 SupervisorSpec::estrategia must agree for {estrategia:?}",
13409            );
13410            assert_eq!(
13411                s.estrategia(),
13412                estrategia,
13413                "SupervisorSpec::estrategia must return the storage-side \
13414                 RestartStrategy verbatim for {estrategia:?} (a violation \
13415                 means the accessor stopped being a raw field-return \
13416                 copy)",
13417            );
13418        }
13419    }
13420
13421    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
13422    // macro definition (see the paired doc-block above the macro
13423    // definition) — every generated `<ctor>(caixa: &str) -> Self`
13424    // constructor folds the uniform `Self::<Variant> { caixa:
13425    // caixa.to_string() }` one-field struct-literal onto one substrate
13426    // primitive. The three per-variant equivalence pins below
13427    // (fail-before-pass-after by construction — a byte-mismatched macro
13428    // arm would trip its equivalence pin first) lock each generated
13429    // constructor to its struct-literal peer under `PartialEq`, so
13430    // every wire-up in [`SupervisorSpec::validate_children`] and
13431    // [`validate_no_self_supervision`] on that variant produces a
13432    // byte-equal `SupervisorError` to the pre-lift open-coded
13433    // struct-literal. The cross-axis pin that follows (non-default
13434    // caixa name) routes the sole constructor input axis through
13435    // `.to_string()`, so the fold does not silently collapse onto a
13436    // fixed name.
13437    //
13438    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
13439    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
13440    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
13441    // `missing_entry_ctor_matches_struct_literal_wrap` /
13442    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
13443    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
13444    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
13445    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
13446    // on the six sibling ctor families the recent trajectory closed
13447    // on the peer `LayoutError` / `AplicacaoError` envelopes.
13448
13449    #[test]
13450    fn empty_child_version_ctor_matches_struct_literal_wrap() {
13451        assert_eq!(
13452            SupervisorError::empty_child_version("worker"),
13453            SupervisorError::EmptyChildVersion {
13454                caixa: "worker".to_string(),
13455            },
13456            "generated empty_child_version ctor must produce byte-equal \
13457             SupervisorError to the open-coded struct-literal wrap on the \
13458             same &str fixture",
13459        );
13460    }
13461
13462    #[test]
13463    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
13464        assert_eq!(
13465            SupervisorError::duplicate_child_caixa("worker"),
13466            SupervisorError::DuplicateChildCaixa {
13467                caixa: "worker".to_string(),
13468            },
13469            "generated duplicate_child_caixa ctor must produce byte-equal \
13470             SupervisorError to the open-coded struct-literal wrap on the \
13471             same &str fixture",
13472        );
13473    }
13474
13475    #[test]
13476    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
13477        assert_eq!(
13478            SupervisorError::child_supervises_self("orquestra"),
13479            SupervisorError::ChildSupervisesSelf {
13480                caixa: "orquestra".to_string(),
13481            },
13482            "generated child_supervises_self ctor must produce byte-equal \
13483             SupervisorError to the open-coded struct-literal wrap on the \
13484             same &str fixture",
13485        );
13486    }
13487
13488    // Per-variant equivalence pins for the two lifted
13489    // [`SupervisorError::child_caixa_invalid`] /
13490    // [`SupervisorError::child_versao_invalid`] inherent constructors
13491    // (fail-before-pass-after by construction — a byte-mismatched ctor body
13492    // would trip its equivalence pin first). Each pins the ctor output to
13493    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
13494    // in [`SupervisorSpec::validate_children`] on the two variants
13495    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
13496    // struct-literal on the same scalar fixtures. Peers of the sibling
13497    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
13498    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
13499    // the peer `AplicacaoError` envelope's
13500    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
13501
13502    #[test]
13503    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
13504        let caixa = "Worker";
13505        let reason = "sample reason text";
13506        assert_eq!(
13507            SupervisorError::child_caixa_invalid(caixa, reason),
13508            SupervisorError::ChildCaixaInvalid {
13509                caixa: caixa.to_string(),
13510                reason: reason.to_string(),
13511            },
13512            "lifted child_caixa_invalid ctor must produce byte-equal \
13513             SupervisorError to the open-coded struct-literal wrap on the \
13514             same (&str, reason) fixture",
13515        );
13516    }
13517
13518    #[test]
13519    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
13520        let caixa = "worker";
13521        let versao = "not-a-req";
13522        let reason = "sample reason text";
13523        assert_eq!(
13524            SupervisorError::child_versao_invalid(caixa, versao, reason),
13525            SupervisorError::ChildVersaoInvalid {
13526                caixa: caixa.to_string(),
13527                versao: versao.to_string(),
13528                reason: reason.to_string(),
13529            },
13530            "lifted child_versao_invalid ctor must produce byte-equal \
13531             SupervisorError to the open-coded struct-literal wrap on the \
13532             same (&str, &str, reason) fixture",
13533        );
13534    }
13535
13536    #[test]
13537    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
13538        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
13539        // against a `&str`-literal vs. `format!(…)` reason input to pin
13540        // both constructors accept the `impl Into<String>` bound
13541        // uniformly, so neither wire-up site drifts under a per-arm
13542        // wrapper transformation on the caller-side `reason` axis. Peer
13543        // of the sibling
13544        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
13545        // sweep on the peer `AplicacaoError` envelope.
13546        let via_literal = "literal reason text";
13547        let via_format = format!("{} reason text", "literal");
13548        assert_eq!(
13549            SupervisorError::child_caixa_invalid("Worker", via_literal),
13550            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
13551        );
13552        assert_eq!(
13553            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
13554            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
13555        );
13556    }
13557
13558    #[test]
13559    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
13560        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
13561        // &str`) through a non-default fixture name against every
13562        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
13563        // so any wrapper-side lowercase / trim / truncate / re-order on
13564        // the `caixa.to_string()` sole-field construction surfaces
13565        // here rather than at a downstream diagnostic-shape mismatch.
13566        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
13567        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
13568        // through_to_string` / `contrato_target_ctors_route_edge_
13569        // triple_through_verbatim` / `contrato_empty_pair_ctors_
13570        // route_edge_pair_through_verbatim` cross-axis routing pins on
13571        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
13572        // here onto the `SupervisorError` `{ caixa: String }` envelope
13573        // so every substrate-primitive ctor family in caixa-core
13574        // guarantees the sole-field construction routes the caller's
13575        // `&str` through `.to_string()` verbatim.
13576        let name = "cache-v2";
13577        assert_eq!(
13578            SupervisorError::empty_child_version(name),
13579            SupervisorError::EmptyChildVersion {
13580                caixa: name.to_string(),
13581            },
13582        );
13583        assert_eq!(
13584            SupervisorError::duplicate_child_caixa(name),
13585            SupervisorError::DuplicateChildCaixa {
13586                caixa: name.to_string(),
13587            },
13588        );
13589        assert_eq!(
13590            SupervisorError::child_supervises_self(name),
13591            SupervisorError::ChildSupervisesSelf {
13592                caixa: name.to_string(),
13593            },
13594        );
13595    }
13596
13597    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
13598    //
13599    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
13600    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
13601    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
13602    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
13603    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
13604    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
13605    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
13606    // / silent constant-substitution on any one variant surfaces here rather
13607    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
13608    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
13609    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
13610    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
13611    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
13612    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
13613    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
13614    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
13615    #[test]
13616    fn no_children_ctor_matches_struct_literal_wrap() {
13617        let estrategia = RestartStrategy::OneForAll;
13618        assert_eq!(
13619            SupervisorError::no_children(estrategia),
13620            SupervisorError::NoChildren { estrategia },
13621            "generated no_children ctor must produce byte-equal \
13622             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
13623             on the same `Copy`-`RestartStrategy` fixture",
13624        );
13625    }
13626
13627    #[test]
13628    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13629        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13630        assert_eq!(
13631            SupervisorError::max_restarts_exceeds_cap(max_restarts),
13632            SupervisorError::MaxRestartsExceedsCap { max_restarts },
13633            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13634             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13635             struct-literal wrap on the same `Copy`-`u32` fixture",
13636        );
13637    }
13638
13639    #[test]
13640    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13641        let window = Duration::from_micros(1_500);
13642        assert_eq!(
13643            SupervisorError::restart_window_not_canonical(window),
13644            SupervisorError::RestartWindowNotCanonical { window },
13645            "generated restart_window_not_canonical ctor must produce \
13646             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13647             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13648        );
13649    }
13650
13651    #[test]
13652    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13653        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13654        assert_eq!(
13655            SupervisorError::restart_window_exceeds_cap(window),
13656            SupervisorError::RestartWindowExceedsCap { window },
13657            "generated restart_window_exceeds_cap ctor must produce \
13658             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13659             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13660        );
13661    }
13662
13663    #[test]
13664    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13665        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13666        // constructor input axis through a non-default `Copy` fixture against
13667        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13668        // side silent `.into()` / silent constant-substitution / silent field
13669        // re-name away from the canonical `estrategia | max_restarts | window`
13670        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13671        // axis silently rerouted through some other `Copy` coercion, surfaces
13672        // here rather than at a downstream per-`:supervisor` diagnostic-shape
13673        // drift. Peer of the sibling
13674        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13675        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13676        // envelope's per-`:politicas` per-axis ctor family, extended here onto
13677        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13678        // variant family folded onto a substrate primitive.
13679        //
13680        // Fixtures picked out of each variant's accept-set boundary rather
13681        // than the default value so a silent constant-substitution to a per-
13682        // variant sentinel surfaces here on the structural-equality assertion.
13683        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13684        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13685        // isn't the `SimpleOneForOne` arm the sibling
13686        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13687        // `max_restarts` fixture picks an above-cap magnitude the cap arm
13688        // rejects; the two `Duration` fixtures pick the sub-millisecond and
13689        // above-cap ends of the `:restart-window` canonical-form + cap
13690        // bracket respectively.
13691        let estrategia = RestartStrategy::RestForOne;
13692        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13693        let sub_ms = Duration::from_micros(1_500);
13694        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13695        assert_eq!(
13696            SupervisorError::no_children(estrategia),
13697            SupervisorError::NoChildren { estrategia },
13698        );
13699        assert_eq!(
13700            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13701            SupervisorError::MaxRestartsExceedsCap {
13702                max_restarts: above_cap_restarts,
13703            },
13704        );
13705        assert_eq!(
13706            SupervisorError::restart_window_not_canonical(sub_ms),
13707            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13708        );
13709        assert_eq!(
13710            SupervisorError::restart_window_exceeds_cap(above_hour),
13711            SupervisorError::RestartWindowExceedsCap { window: above_hour },
13712        );
13713    }
13714
13715    #[test]
13716    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13717        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13718        // generated ctor `const fn` so a caller can pin a `SupervisorError`
13719        // at compile time — the same zero-runtime-work property the pre-lift
13720        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13721        // its `Copy`-pass-through construction path (no `.to_string()` /
13722        // `.into()` allocation, no branching). If any future edit silently
13723        // drops the `const` qualifier from the macro body the per-arm `const`
13724        // bindings below fail to compile, which surfaces the regression at
13725        // the substrate-primitive definition rather than at some downstream
13726        // consumer that had come to rely on the `const`-constructibility.
13727        // Peer of the sibling
13728        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13729        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13730        // per-`:politicas` per-axis ctor family.
13731        const NO_CHILDREN: SupervisorError =
13732            SupervisorError::no_children(RestartStrategy::OneForAll);
13733        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13734        const WINDOW_NC: SupervisorError =
13735            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13736        const WINDOW_CAP: SupervisorError =
13737            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13738        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13739        assert!(matches!(
13740            MAX_RESTARTS_CAP,
13741            SupervisorError::MaxRestartsExceedsCap { .. }
13742        ));
13743        assert!(matches!(
13744            WINDOW_NC,
13745            SupervisorError::RestartWindowNotCanonical { .. }
13746        ));
13747        assert!(matches!(
13748            WINDOW_CAP,
13749            SupervisorError::RestartWindowExceedsCap { .. }
13750        ));
13751    }
13752}