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    /// Substrate-canonical exhaustive accept-set on the
113    /// [`RestartStrategy`] `PascalCase` wire byte-string axis — the
114    /// closed four-arm roster of every byte-string [`Self::as_str`]
115    /// returns, routed byte-for-byte through the paired
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
118    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
119    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
120    /// lifted `pub const` roster the [`Self::as_str`] emitter (and the
121    /// [`std::fmt::Display`] / [`AsRef<str>`] /
122    /// `From<{Self,&Self}> for {&'static str, String, Cow<'static, str>,
123    /// Box<str>, Arc<str>}` trait triple + quintuple routed through it)
124    /// walks — and byte-for-byte the same four strings the un-`rename`d
125    /// `Serialize` derive emits under the paired
126    /// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] tag key on every
127    /// JSON / YAML CR round-trip.
128    ///
129    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
130    /// roster on the top-level typed-kind discriminator's `PascalCase`
131    /// wire byte-string axis, and of the sibling
132    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
133    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
134    /// rosters on the OTP-appup discriminator's two-axis roster split —
135    /// the same closed-set exhaustive-accept-set roster discipline
136    /// extended here onto the first M2 OTP-shape sibling-restart
137    /// closed-set typed enum. The sibling
138    /// [`crate::aplicacao::PlacementStrategy`] M3 mesh-shape distribution
139    /// strategy enum is the next natural peer on the same axis, still
140    /// carrying only [`crate::aplicacao::PlacementStrategy::ALL`].
141    ///
142    /// Downstream consumers of the closed accepted-wire-form set — a
143    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
144    /// rejection body enumerating the accepted JSON `:estrategia` values
145    /// verbatim (as distinct from the kebab-case dispatcher-catalog
146    /// enumeration [`Self::discriminant`] serves, whose per-arm form
147    /// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
148    /// `"simple-one-for-one"` structurally disagrees with the wire byte-
149    /// string these `PascalCase` entries carry), a future `feira
150    /// supervisor --estrategia …` CLI-side "did you mean" hint whose
151    /// candidate-list must byte-match the wire form the operator's
152    /// per-strategy dispatch keys off (rather than the kebab
153    /// dispatcher-catalog identity), a future `feira app graph`
154    /// per-supervisor `:estrategia`-histogram column that renders
155    /// zero-count arms, a future wasm-operator per-reconcile-step
156    /// diagnostic log line enumerating accepted wire forms on an
157    /// unknown-strategy rejection, a future
158    /// `tracing::field::valuable::Value::List` structured-log accepted-
159    /// wire-form emit — now reach for one lifted substrate-primitive
160    /// roster rather than open-coding a four-string array-literal
161    /// (`["OneForOne", "OneForAll", "RestForOne", "SimpleOneForOne"]`)
162    /// whose arm-set has no compile-time link back to the typed
163    /// [`RestartStrategy`] enum. A future arm addition (an OTP-`rest_for_all`
164    /// arm the theory
165    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
166    /// might reach for once the four canonical OTP strategies stop
167    /// covering the substrate's discovered load-shape) extends this
168    /// roster as a single edit — paired with the [`Self::as_str`]
169    /// match's compiler-checked exhaustiveness on the new arm — and
170    /// every consumer picks up the new wire form by construction rather
171    /// than a coordinated array-literal rewrite across every downstream
172    /// site.
173    ///
174    /// Length is pinned load-bearing at `RestartStrategy::ALL.len()`
175    /// (four) by
176    /// [`tests::restart_strategy_wire_names_covers_every_arm`], every
177    /// variant's [`Self::as_str`] projection is pinned to a member of
178    /// the roster so a silent skew between the emitter's arm-set and
179    /// this const's arm-set trips at caixa-core test time rather than
180    /// at a downstream consumer's accepted-set enumeration miss, and
181    /// every entry is further pinned to open with an ASCII uppercase
182    /// byte so a silent collapse of the wire-form axis with the peer
183    /// kebab-case dispatcher-catalog axis (an entry byte-identical to a
184    /// sibling [`Self::discriminant`] kebab byte-string that would let
185    /// a wire-axis consumer accept the dispatcher-catalog vocabulary)
186    /// trips here rather than at a downstream K8s-CR round-trip miss.
187    pub const WIRE_NAMES: &'static [&'static str] = &[
188        crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
189        crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
190        crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
191        crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
192    ];
193
194    /// Canonical PascalCase discriminator scalar this variant serializes
195    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
196    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
197    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
198    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
199    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
200    /// constants so every substrate consumer that dispatches on the
201    /// per-supervisor sibling-restart strategy (the future
202    /// wasm-operator's per-supervisor sibling-restart branch, the future
203    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
204    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
205    /// reconciliation scheduler's per-strategy fan-out) reads the same
206    /// byte-string the `Serialize` derive emits — the pin test in
207    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
208    /// asserts the two paths agree, peer of the M3
209    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
210    /// distribution-strategy axis.
211    #[must_use]
212    pub const fn as_str(self) -> &'static str {
213        match self {
214            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
215            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
216            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
217            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
218        }
219    }
220
221    /// Substrate-canonical reverse projection on the `:supervisor
222    /// :estrategia` closed-set axis — parses the `PascalCase`
223    /// discriminator scalar back to the typed variant, or `None` when
224    /// `s` is outside
225    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
226    /// on the same lifted
227    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
228    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
229    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
230    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
231    /// constants the [`Self::as_str`] emitter walks, so the parse and
232    /// emit halves of the round-trip migrate through one caixa-core
233    /// edit on any future arm addition.
234    ///
235    /// Prior to this lift the substrate carried only the forward
236    /// `Self → &str` projection on the OTP sibling-restart axis (the
237    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
238    /// through it, the `Serialize` derive that emits the same
239    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
240    /// plus the kebab-case dispatcher-catalog identity via
241    /// [`Self::discriminant`] — every non-serde consumer that wanted to
242    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
243    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
244    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
245    /// that expressed no compile-time link back to the typed variant's
246    /// canonical lifted constant. A future variant rename or per-arm
247    /// serde-attribute drift would silently split the wire byte-string
248    /// one non-serde consumer parsed from the one the emitter wrote,
249    /// with the failure surfacing at parse time far from the rebrand
250    /// commit.
251    ///
252    /// Distinct axis from the [`std::str::FromStr`] impl the
253    /// [`gen_platform::FromStrKind`] derive already installs on this
254    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
255    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
256    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
257    /// [`Self::discriminant`]), while this method inverts the
258    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
259    /// two-axis split lets the dispatcher-catalog identity live in
260    /// kebab-case
261    /// (where every peer catalog identifier already lives) without
262    /// forcing a wire-format rename on the tatara-lisp author surface
263    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
264    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
265    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
266    /// carry on their peer closed-set typed-enum wire round-trips.
267    ///
268    /// Same closed-set-reverse-projection discipline the sibling
269    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
270    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
271    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
272    /// carry on the peer wire-side `str → Self` axes — extended onto
273    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
274    /// fifth substrate-side closed-set typed enum to converge on the
275    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
276    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
277    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
278    /// derive already installs on the sibling kebab-case axis. Returns
279    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
280    /// shapes: the caller picks the diagnostic form appropriate for
281    /// its use site.
282    #[must_use]
283    pub fn from_wire(s: &str) -> Option<Self> {
284        match s {
285            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
286            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
287            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
288            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
289            _ => None,
290        }
291    }
292}
293
294/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
295/// pretty-printed byte-string every consumer that formats the strategy as
296/// user-facing text lands on (the future wasm-operator's per-supervisor
297/// sibling-restart-strategy diagnostic line, the future `feira app graph`
298/// per-supervisor strategy line, the future M4
299/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
300/// rejection body) reaches for the same lifted
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
303/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
304/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
305/// wire-format `Serialize` derive already emits under
306/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
307/// [`RestartStrategy::as_str`] helper already returns.
308///
309/// Pre-convergence the two paths structurally disagreed — the
310/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
311/// route (now retired here) sent [`std::fmt::Display`] through the
312/// gen-platform discriminant catalog string, which arrives kebab-case as
313/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
314/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
315/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
316/// through the un-`rename`d serde derive. Every consumer that formatted
317/// the strategy for a diagnostic line, a graph, or a rejection body under
318/// `format!("{v}")` therefore landed under a different byte-string than
319/// the wire format the operator's per-strategy dispatch keyed off — a
320/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
321/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
322/// probed was `"OneForOne"`) surfaced as a confused correlate at
323/// operator-log time far from the two-declaration site.
324///
325/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
326/// path: every `format!("{v}")` call reaches the same lifted
327/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
328/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
329/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
330/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
331/// byte-string per variant. A future variant rename or
332/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
333/// exactly one place, structurally.
334///
335/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
336/// (from `#[derive(gen_platform::Discriminant)]`) still returns
337/// `"one-for-one"` / etc., and the fleet-wide
338/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
339/// registration keys the catalog off the same kebab identity. The two
340/// naming worlds now live on separate typed methods (`Display` /
341/// `as_str` for the wire byte-string, `discriminant` for the catalog
342/// identity) rather than sharing one `Display` route that structurally
343/// disagrees with the wire format.
344///
345/// Pin tests
346/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
347/// and
348/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
349/// assert the three paths agree byte-for-byte on every variant, so a
350/// future variant rename or per-arm serde attribute drift is a build
351/// error visible at caixa-core test time, not a silent per-consumer
352/// dispatch miss at apply / reconcile time.
353///
354/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
355/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
356/// axis — same three-path-convergence discipline, extended to close the
357/// second of three OTP-shaped closed-enum discriminator axes on the
358/// caixa typed surface.
359impl std::fmt::Display for RestartStrategy {
360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        f.write_str(self.as_str())
362    }
363}
364
365/// Substrate-canonical [`AsRef<str>`] projection on the M2
366/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
367/// enum — routes through the same [`RestartStrategy::as_str`]
368/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
369/// impl and the un-`rename`d [`serde::Serialize`] derive already key
370/// off, so any future consumer that binds a [`RestartStrategy`]
371/// through the standard-library `impl AsRef<str>` bound (a future
372/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
373/// composes the emitted `PascalCase` wire scalar into a
374/// [`std::process::Command::arg`] shell-out of the future
375/// wasm-operator's admission gate, a per-supervisor structured-log
376/// recorder on the future `caixa-operator`'s hierarchical
377/// reconciliation surface that accepts `impl AsRef<str>` at the
378/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
379/// lookup keyed on the estrategia wire byte through
380/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
381/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
382/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
383/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
384/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
385/// lifted-const through one substrate-primitive dispatch rather
386/// than an open-coded `.as_str()` projection at every wire-up.
387///
388/// Peer of the sibling [`std::fmt::Display`] impl on the same
389/// primitive — both delegate to the shared
390/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
391/// [`format!("{s}")`], `s.as_str()`, and
392/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
393/// byte-string per instance by construction. A future variant rename
394/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
395/// enum reaches every one of the three paths (plus the wire-format
396/// `Serialize` derive that already routes through the same lifted
397/// const) through exactly one caixa-core edit.
398///
399/// Same "route the trait impl through the substrate-primitive
400/// accessor" discipline the sibling [`crate::CaixaVersion`]
401/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
402/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
403/// axis on the caixa typed surface (the first M2 OTP-shape
404/// closed-set typed enum to converge onto the standard-library
405/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
406/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
407/// primitive so a caller who has one has both; before this lift,
408/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
409/// [`AsRef<str>`] impl the convention names.
410///
411/// Pinned load-bearing by
412/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
413/// (byte-parity pin against [`RestartStrategy::as_str`] across the
414/// four-arm closed set) — any future silent detour that routes the
415/// impl through a divergent projection (a per-arm inline
416/// `match self { … }` re-inlining that opens a compile-time link to
417/// the un-lifted arm-literal, a swap onto the kebab-case
418/// [`gen_platform::Discriminant`] catalog identity that would collide
419/// the wire axis with the dispatcher-catalog axis) trips at
420/// caixa-core test time under `assert_eq!` rather than at a
421/// downstream `impl AsRef<str>`-bound consumer's silent split.
422impl AsRef<str> for RestartStrategy {
423    fn as_ref(&self) -> &str {
424        self.as_str()
425    }
426}
427
428/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
429/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
430/// the paired substrate-primitive [`RestartStrategy::from_wire`]
431/// `Option<Self>` accessor so every future consumer that binds a
432/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
433/// standard-library `.try_into()` / [`TryFrom`] axis (a future
434/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
435/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
436/// `let estrategia: RestartStrategy = s.try_into()?`, a future
437/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
438/// `spec.estrategia: String` field through
439/// `RestartStrategy::try_from(&s)?`, a generic
440/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
441/// set typed enums) reaches the same four-arm accept-set the sibling
442/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
443/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
444/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
445/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
446/// compile-time link back to the substrate primitive.
447///
448/// Complements the pre-existing forward-projection triple
449/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
450/// with the paired trait-idiomatic reverse-projection axis: Rust-side
451/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
452/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
453/// caller who can project *out to* a `&str` can also project *in from*
454/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
455/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
456/// lint the sibling method-named [`RestartStrategy::from_wire`] would
457/// trigger under a `FromStr` impl and to avoid colliding with the
458/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
459/// already installs on the paired *kebab-case dispatcher-catalog* axis
460/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
461/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
462/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
463/// half without disturbing either the method-named `from_wire` shape every
464/// sibling closed-set typed enum on the substrate already carries or the
465/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
466/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
467///
468/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
469/// `Option<Self>` return-shape's deliberate deferral of error typing: the
470/// caller picks the diagnostic form appropriate for its use site (a future
471/// `feira supervisor --estrategia` arg-parse composes its own per-verb
472/// "unknown strategy: <arg> — accepted: {…}" message enumerating
473/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
474/// wraps the `Err(())` outcome with the accepted-set enumeration for
475/// operator diagnostics, a `Result::map_err` at the call site lifts the
476/// unit-error to a per-verb error type). Same shape the peer
477/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
478/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
479/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
480/// on their peer closed-set typed enums' reverse projections.
481///
482/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
483/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
484/// future 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 axis
488/// by construction — one caixa-core edit on
489/// [`RestartStrategy::from_wire`] extends both the method-named reverse
490/// projection every existing consumer keys off and the trait-idiomatic
491/// reverse projection this impl exposes, without a coordinated rewrite
492/// across every future `TryFrom<&str>`-bound consumer's arm-set.
493///
494/// Extends the substrate-wide closed-set-enum reverse-projection family
495/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
496/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
497/// M2-OTP-shape closed-set typed enum on the caixa surface — the
498/// `:supervisor :estrategia` closed set the future wasm-operator's
499/// hierarchical reconciliation scheduler keys off end-to-end.
500///
501/// Pinned load-bearing by
502/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
503/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
504/// four-arm accept-set) and
505/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
506/// (rejection witness against silent accept-set widening).
507impl TryFrom<&str> for RestartStrategy {
508    type Error = ();
509
510    fn try_from(s: &str) -> Result<Self, Self::Error> {
511        Self::from_wire(s).ok_or(())
512    }
513}
514
515/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
516/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
517/// routes byte-for-byte through the paired substrate-primitive
518/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
519/// consumer that binds a [`RestartStrategy`] through the standard-library
520/// `.into()` / [`From<Self> for &'static str`] (equivalently
521/// [`Into<&'static str>`]) axis (a future
522/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
523/// recorder where the `Str` arm typing demands `&'static str` and the
524/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
525/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
526/// composer on the future M4 admission-webhook rejection body where the
527/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
528/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
529/// per-strategy diagnostic column) reaches the same lifted
530/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
531/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
532/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
533/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
534/// paired [`std::fmt::Display`], [`AsRef<str>`], and
535/// [`RestartStrategy::as_str`] surfaces already return, rather than an
536/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
537/// whose arm-set has no compile-time link back to the substrate primitive.
538///
539/// Complements the pre-existing quadruple
540/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
541/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
542/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
543/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
544/// &'static str`] (trait-idiomatic forward) on the same primitive so a
545/// caller who can project *in from* a `&str` via the trait axis can also
546/// project *out to* one — mirroring the `strum::IntoStaticStr` /
547/// `serde::Serialize`-shape idiom where both projection halves share one
548/// trait-driven vocabulary. Before this lift the substrate carried a
549/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
550/// returning [`From<Self> for &'static str`] axis every downstream
551/// generic that specifically needs `'static` byte-string bytes reaches for.
552///
553/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
554/// construction (each `match` arm resolves to a
555/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
556/// lifetime), so the trait's return-type promise is upheld structurally.
557/// Any future silent detour that routes the impl through a non-static
558/// projection (a per-arm inline `String::from("OneForOne")`-shaped
559/// re-inlining that would `.leak()`-cast for the `'static` bound, a
560/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
561/// const to a non-`const &str`) is a caixa-core-build-time failure through
562/// the `pub const fn as_str` signature the trait routes through.
563///
564/// The paired impl reaches the same four-arm emit-set the
565/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
566/// arm addition (an OTP-`rest_for_all` fifth arm the theory
567/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
568/// might reach for once the four canonical OTP strategies stop covering
569/// the substrate's discovered load-shape) grows the trait-idiomatic
570/// forward axis by construction — one caixa-core edit on
571/// [`RestartStrategy::as_str`] extends every one of the five sibling
572/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
573/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
574/// and the un-`rename`d [`serde::Serialize`] derive that also emits
575/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
576/// future `Into<&'static str>`-bound consumer's arm-set.
577///
578/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
579/// closed-set fieldless typed enums — the mirror of the recently-closed
580/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
581/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
582/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
583/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
584/// [`crate::aplicacao::WitShape`] via 5472902,
585/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
586/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
587/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
588/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
589/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
590/// [`caixa_theme::Semantic`] via bd7da69, and
591/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
592/// picks [`RestartStrategy`] as the first-mover on the forward-projection
593/// family because its wire byte-string (`PascalCase`) and diagnostic
594/// byte-string ([`as_str`] return) coincide by construction — the sibling
595/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
596/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
597/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
598///
599/// Pinned load-bearing by
600/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
601/// (byte-parity pin against [`RestartStrategy::as_str`] across the
602/// four-arm emit-set, plus a `const`-context materialization witness for
603/// the `&'static str` lifetime promise) and
604/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
605/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
606/// and [`RestartStrategy::as_str`] agree on every arm, so no future
607/// silent bifurcation of the two forward-projection paths can land
608/// silently).
609impl From<RestartStrategy> for &'static str {
610    fn from(strategy: RestartStrategy) -> &'static str {
611        strategy.as_str()
612    }
613}
614
615/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
616/// *borrowed* input onto the `&'static str` axis — the borrowed-input
617/// companion to the paired owned-input [`From<RestartStrategy> for
618/// &'static str`] impl immediately above. Routes byte-for-byte through
619/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
620/// fn` accessor so every consumer that binds a `&RestartStrategy`
621/// through the standard-library `.into()` / [`From<&Self> for &'static
622/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
623/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
624/// whose iterator over `&'static [RestartStrategy]` yields
625/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
626/// [`From<RestartStrategy>`] axis alone forces every call site through
627/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
628/// rather than the direct trait-idiomatic projection; a future generic
629/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
630/// that walks the `iter().map(Into::into)` shape verbatim across every
631/// substrate-wide closed-set typed enum; the future wasm-operator's
632/// per-supervisor sibling-restart-strategy diagnostic line that
633/// composes the accepted-set enumeration from an iterated
634/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
635/// per-arm `match s { … }` cascade; a future
636/// `HashMap::<&'static str, RestartStrategy>::from_iter(
637///     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
638/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
639/// impl cannot compose without this borrowed-input axis in place)
640/// reaches the same four-arm lifted
641/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
645/// the paired owned-input [`From<RestartStrategy> for &'static str`],
646/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
647/// [`RestartStrategy::as_str`] surfaces already return.
648///
649/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
650/// forward-projection family opened on [`crate::dep::DepList`]
651/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
652/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
653/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
654/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
655/// not exist in `core`), so every closed-set typed enum that carries
656/// the owned-input axis but not the borrowed-input axis forces every
657/// borrowed-input call site through a `.copied()` /
658/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
659/// type bounds have no compile-time link to the substrate primitive.
660/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
661/// this campaign (mirroring the first-mover role it played on the
662/// owned-input axis in 523157d); the remaining eleven substrate-wide
663/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
664/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
665/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
666/// `FerriteRuntime`) are the future targets of this campaign.
667///
668/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
669/// [`From<Self> for &'static str`] emits the lowercase Portuguese
670/// [`Self::as_str`] diagnostic vocabulary while the reverse
671/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
672/// author-surface vocabulary, forcing the round-trip through an
673/// intermediate wire-vocab hop), [`RestartStrategy`]'s
674/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
675/// `PascalCase` vocabulary by construction, so the borrowed-input
676/// forward axis and the reverse axis compose directly — the round-trip
677/// witness pin below locks this direct composition without the
678/// intermediate hop the peer axis requires.
679///
680/// Pinned load-bearing by
681/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
682/// (byte-parity pin against [`RestartStrategy::as_str`] across the
683/// four-arm emit-set via a borrowed input, plus a `const`-context
684/// materialization witness for the `&'static str` lifetime promise,
685/// plus a blanket `.into()` shape) and
686/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
687/// (cross-axis partition pin against the paired owned-input
688/// [`From<RestartStrategy> for &'static str`] impl, plus a
689/// `.iter().map(Into::into)` pipe witness over
690/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
691/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
692/// Self` round-trip without the wire-vocab intermediate the peer
693/// [`crate::CaixaKind`] axis pair requires).
694impl From<&RestartStrategy> for &'static str {
695    fn from(strategy: &RestartStrategy) -> &'static str {
696        strategy.as_str()
697    }
698}
699
700/// Trait-idiomatic *owned-`String`* forward projection on the M2
701/// OTP-shape sibling-restart-strategy closed-set typed enum — the
702/// owned-heap-string companion to the paired `&'static str`-returning
703/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
704/// for &'static str`] impls immediately above. Routes byte-for-byte
705/// through the substrate-primitive [`RestartStrategy::as_str`]
706/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
707/// that binds a [`RestartStrategy`] through the standard-library
708/// `.into()` / [`From<Self> for String`] (equivalently
709/// [`Into<String>`]) axis — a future
710/// `serde_json::Value::String(strategy.into())` structured-payload
711/// composer where the `Value::String` arm typing demands an owned
712/// [`String`] and the sibling [`&'static str`]-returning axis forces an
713/// explicit `.to_owned()` / `String::from` restatement at every call
714/// site, a future
715/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
716/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
717/// map's key type is owned [`String`] rather than [`&'static str`], a
718/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
719/// the future M4 admission-webhook rejection body's owned-arm, the
720/// future wasm-operator's per-supervisor `serde_json::json!({
721/// "estrategia": strategy })` diagnostic emit where the JSON
722/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
723/// the same four-arm lifted
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
726/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
727/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
728/// paired [`std::fmt::Display`], [`AsRef<str>`],
729/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
730/// forward-projection impls already return.
731///
732/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
733/// on the closed-set fieldless typed enum surface — first-mover on the
734/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
735/// [`crate::supervisor::RestartStrategy`] first-mover position that
736/// opened the paired owned-`&'static str` axis (523157d) and the
737/// borrowed-input `&'static str` axis on
738/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
739/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
740/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
741/// typed enum that carries the paired `AsRef<str>` / `Display` /
742/// `From<Self> for &'static str` triple but not the owned-[`String`]
743/// axis forces every owned-string call site through a `.to_string()` /
744/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
745/// whose type bounds have no compile-time link to the substrate
746/// primitive.
747///
748/// Deliberately routes through the human-readable
749/// [`RestartStrategy::as_str`] axis — for this enum the wire format
750/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
751/// and the diagnostic byte-string share the same vocabulary by
752/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
753/// axes diverge), so the owned-[`String`] projection lands
754/// byte-identically on both the wire vocabulary the paired
755/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
756/// [`RestartStrategy::as_str`] helper returns.
757///
758/// The remaining fourteen closed-set typed enums on the caixa
759/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
760/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
761/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
762/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
763/// this campaign — each carries the same paired `AsRef<str>` /
764/// `Display` / `From<Self> for &'static str` / `From<&Self> for
765/// &'static str` quadruple that this owned-[`String`] axis extends onto.
766///
767/// Pinned load-bearing by
768/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
769/// (byte-parity pin against [`RestartStrategy::as_str`] across the
770/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
771/// and
772/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
773/// (cross-axis partition pin against the paired owned-input
774/// [`From<RestartStrategy> for &'static str`] impl and the sibling
775/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
776/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
777/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
778/// `Self → String → Self` round-trip on the trait-idiomatic
779/// owned-[`String`] forward + reverse axis pair).
780impl From<RestartStrategy> for String {
781    fn from(strategy: RestartStrategy) -> String {
782        strategy.as_str().to_owned()
783    }
784}
785
786/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
787/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
788/// typed enum — the fourth (and closing) corner of the
789/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
790/// projection family. Routes byte-for-byte through the
791/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
792/// accessor (via [`str::to_owned`]) so every consumer that holds a
793/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
794/// future `serde_json::Value::String(String::from(&strategy))`
795/// structured-payload composer over a borrowed field, a future
796/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
797/// keys through `.iter().map(String::from)`, a future
798/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
799/// borrowed-iteration axis where dereferencing the strategy would force
800/// an unnecessary `Copy` at every step, the future wasm-operator's
801/// per-supervisor `strategies.iter().map(String::from).collect()`
802/// diagnostic emit whose iteration axis is borrowed by construction —
803/// reaches the same four-arm lifted
804/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
805/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
806/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
807/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
808/// paired [`std::fmt::Display`], [`AsRef<str>`],
809/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
810/// forward-projection impls
811/// ([`From<RestartStrategy> for &'static str`],
812/// [`From<&RestartStrategy> for &'static str`],
813/// [`From<RestartStrategy> for String`]) already return.
814///
815/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
816/// forward-projection axis on closed-set fieldless typed enums —
817/// first-mover on the 2×2 completion corner, mirror of the
818/// [`crate::supervisor::RestartStrategy`] first-mover position that
819/// opened the paired owned-input owned-`String` axis (7baa18a), the
820/// owned-input owned-`&'static str` axis (523157d), and the paired
821/// [`crate::dep::DepList`] first-mover position that opened the
822/// borrowed-input `&'static str` axis (64aa742). Rust's standard
823/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
824/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
825/// every closed-set typed enum that carries the paired `AsRef<str>` /
826/// `Display` / `From<Self> for &'static str` / `From<&Self> for
827/// &'static str` / `From<Self> for String` quintuple but not the
828/// borrowed-input owned-[`String`] axis forces every borrowed-input
829/// owned-string call site through a `strategy.as_str().to_owned()` /
830/// `String::from(*strategy)` (with a spurious `Copy`) /
831/// `strategy.to_string()` (through `Display`) detour whose type bounds
832/// have no compile-time link to the substrate primitive.
833///
834/// Deliberately routes through the human-readable
835/// [`RestartStrategy::as_str`] axis — for this enum the wire format
836/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
837/// and the diagnostic byte-string share the same vocabulary by
838/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
839/// axes diverge), so the borrowed-input owned-[`String`] projection
840/// lands byte-identically on both the wire vocabulary the paired
841/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
842/// [`RestartStrategy::as_str`] helper returns.
843///
844/// The remaining fourteen closed-set typed enums on the caixa
845/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
846/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
847/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
848/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
849/// this 2×2-completion campaign — each carries the same paired
850/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
851///
852/// Pinned load-bearing by
853/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
854/// (byte-parity pin against [`RestartStrategy::as_str`] across the
855/// four-arm emit-set through the borrowed-input surface) and
856/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
857/// (cross-axis partition pin against the paired owned-input owned-
858/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
859/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
860/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
861/// routed through [`std::fmt::Display`], plus a direct round-trip
862/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
863/// [`String::as_str`] borrow that closes the two-way
864/// `&Self → String → Self` round-trip on the trait-idiomatic
865/// borrowed-input owned-[`String`] forward + reverse axis pair).
866impl From<&RestartStrategy> for String {
867    fn from(strategy: &RestartStrategy) -> String {
868        strategy.as_str().to_owned()
869    }
870}
871
872/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
873/// output* forward projection on the M2 OTP-shape sibling-restart
874/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
875/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
876/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
877/// shape closed-set fieldless typed enum peer on the caixa surface
878/// (`:supervisor :estrategia`). Routes byte-for-byte through the
879/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
880/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
881/// that binds a [`RestartStrategy`] through the trait-idiomatic
882/// [`std::borrow::Cow<'static, str>`] axis — a future
883/// `axum::response::IntoResponse` composer whose per-strategy
884/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
885/// borrowed return, a future M4 admission-webhook rejection body
886/// that composes the accepted-strategy enumeration through the same
887/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
888/// already routes through, a generic `<T: for<'a>
889/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
890/// emitter on a per-supervisor diagnostic column — reaches the same
891/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
892/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
895/// the paired [`std::fmt::Display`], [`AsRef<str>`],
896/// [`RestartStrategy::as_str`], and the four
897/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
898/// forward-projection corners already return.
899///
900/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
901/// [`std::borrow::Cow::Owned`] — the substrate-primitive
902/// [`RestartStrategy::as_str`] accessor's return carries the
903/// `&'static str` lifetime by construction (each `match` arm resolves
904/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
905/// with static lifetime), so the zero-alloc borrowed arm is the
906/// type-correct projection with no runtime allocation.
907///
908/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
909/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
910/// From<T> for Cow<'static, str>`), so the paired sibling
911/// [`From<RestartStrategy> for &'static str`],
912/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
913/// [`std::fmt::Display`] surfaces do not implicitly extend to a
914/// [`Cow<'static, str>`]-bound call site — every such site is forced
915/// through a `Cow::Borrowed(strategy.as_str())` /
916/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
917/// have no compile-time link back to the substrate primitive until
918/// this lift.
919///
920/// First peer to extend the substrate-wide trait-idiomatic
921/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
922/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
923/// d45c409 borrowed-input) onto the wider substrate — the remaining
924/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
925/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
926/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
927/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
928/// future targets of this campaign.
929///
930/// Pinned load-bearing by
931/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
932/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
933/// against [`RestartStrategy::as_str`] across the four-arm
934/// [`RestartStrategy::ALL`]) and
935/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
936/// (cross-axis partition pin against the paired [`From<RestartStrategy>
937/// for &'static str`], [`From<RestartStrategy> for String`], and
938/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
939/// `.iter().copied().map(Cow::from)` pipe witness over
940/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
941/// through the [`Cow<'static, str>`] axis alone and pins the
942/// zero-alloc discipline on every element).
943impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
944    fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
945        std::borrow::Cow::Borrowed(strategy.as_str())
946    }
947}
948
949/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
950/// output* forward projection on the M2 OTP-shape sibling-restart
951/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
952/// companion to the paired owned-input
953/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
954/// immediately above (7dd28b3). Routes byte-for-byte through the same
955/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
956/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
957/// that holds a `&RestartStrategy` and needs a
958/// [`std::borrow::Cow<'static, str>`] — a
959/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
960/// per-arm accept-set materializer (whose iterator over
961/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
962/// `RestartStrategy`, so the paired owned-input
963/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
964/// alone forces every call site through an explicit `.copied()` /
965/// dereference / [`Copy`]-bound restatement rather than the direct
966/// trait-idiomatic projection), a future generic
967/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
968/// on a per-strategy diagnostic column that walks the
969/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
970/// webhook rejection body that composes the accepted-strategy
971/// enumeration from an iterated
972/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
973/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
974/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
978/// the paired [`std::fmt::Display`], [`AsRef<str>`],
979/// [`RestartStrategy::as_str`], the four
980/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
981/// forward-projection corners, and the paired owned-input
982/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
983/// already return.
984///
985/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
986/// [`std::borrow::Cow::Owned`] — the substrate-primitive
987/// [`RestartStrategy::as_str`] accessor's return carries the
988/// `&'static str` lifetime by construction (each `match` arm resolves
989/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
990/// with static lifetime), so the zero-alloc borrowed arm is the
991/// type-correct projection with no runtime allocation.
992///
993/// Second peer on the substrate-wide trait-idiomatic
994/// [`std::borrow::Cow<'static, str>`] forward-projection family
995/// opened one commit prior (7dd28b3) on the paired owned-input
996/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
997/// — closes the `{Self, &Self}` input-shape corner of the
998/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
999/// fieldless typed enum peer on the caixa surface, exactly as
1000/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
1001/// after the owning half (99c1735) landed. Rust's standard library
1002/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
1003/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
1004/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
1005/// on the substrate that carries the paired owned-input
1006/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
1007/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
1008/// through a spurious [`Copy`] deref
1009/// (`std::borrow::Cow::from(*strategy)`) or a
1010/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
1011/// type bounds have no compile-time link to the substrate primitive.
1012///
1013/// Pinned load-bearing by
1014/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1015/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1016/// against [`RestartStrategy::as_str`] across the four-arm
1017/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
1018/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1019/// (cross-axis partition pin against the paired owned-input
1020/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
1021/// paired borrowed-input owned-`&'static str`
1022/// [`From<&RestartStrategy> for &'static str`], and the paired
1023/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
1024/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1025/// over [`RestartStrategy::ALL`] — whose iterator yields
1026/// `&RestartStrategy` by construction, so the borrowed-input
1027/// [`Cow<'static, str>`] axis is what routes the pipe through the
1028/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
1029/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
1030/// spurious [`Copy`] deref).
1031impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
1032    fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
1033        std::borrow::Cow::Borrowed(strategy.as_str())
1034    }
1035}
1036
1037/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
1038/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1039/// closed-set fieldless typed enum — opens a fresh
1040/// substrate-wide `Box<str>` forward-projection campaign tier on the
1041/// first M2 OTP-shape closed-set fieldless typed enum peer on the
1042/// caixa surface, immediately after the paired `Cow<'static, str>`
1043/// axis (7dd28b3 / ee577fd) closed the
1044/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
1045/// corner on this enum. Routes byte-for-byte through the
1046/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1047/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
1048/// so every consumer that binds a
1049/// `let key: Box<str> = strategy.into();`-shaped call site — a
1050/// per-supervisor metric-key materializer that stashes the strategy
1051/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
1052/// clone (a shared-nothing per-strategy accept-set the
1053/// `caixa-operator` reconciliation scheduler carries), a future
1054/// admission-webhook rejection body whose per-arm `Box<str>` field
1055/// composes from an owned `RestartStrategy` handle — reaches the
1056/// same four-arm lifted
1057/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1058/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1059/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1060/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1061/// the sibling
1062/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1063/// forward-projection corner already returns. Rust's standard
1064/// library carries `impl From<&str> for Box<str>` and
1065/// `impl From<String> for Box<str>` but no blanket
1066/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
1067/// distinct trait-idiomatic surface that a downstream
1068/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
1069/// and no other — without a
1070/// `Box::from(strategy.as_str())` open-code whose type bounds have
1071/// no compile-time link back to the substrate primitive.
1072///
1073/// Pinned load-bearing by
1074/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
1075/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1076/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1077/// surface, plus a blanket-derived [`Into`] shape witness).
1078impl From<RestartStrategy> for Box<str> {
1079    fn from(strategy: RestartStrategy) -> Box<str> {
1080        Box::<str>::from(strategy.as_str())
1081    }
1082}
1083
1084/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1085/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1086/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1087/// input-shape corner of the substrate-wide `Box<str>`
1088/// forward-projection axis opened one commit prior (69ef45c) on the
1089/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1090/// Routes byte-for-byte through the same substrate-primitive
1091/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1092/// [`Box::<str>::from`] on the returned `&'static str`, so every
1093/// consumer that holds a `&RestartStrategy` and needs a
1094/// [`Box<str>`] — a
1095/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1096/// per-arm accept-set materializer (whose iterator over
1097/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1098/// `RestartStrategy`, so the paired owned-input
1099/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1100/// call site through an explicit `.copied()` / dereference /
1101/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1102/// projection), a per-supervisor metric-key materializer holding
1103/// `&RestartStrategy` through a `caixa-operator` reconciliation
1104/// scheduler's borrow lifetime, a future admission-webhook rejection
1105/// body whose per-arm `Box<str>` field composes from a borrowed
1106/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1107/// reaches the same four-arm lifted
1108/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1109/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1110/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1111/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1112/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1113/// the sibling
1114/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1115/// forward-projection corner already return.
1116///
1117/// Second peer on the substrate-wide trait-idiomatic
1118/// [`Box<str>`] forward-projection family opened one commit prior
1119/// (69ef45c) on the paired owned-input
1120/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1121/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1122/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1123/// the caixa surface (`:supervisor :estrategia`), exactly as
1124/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1125/// after its owning half (7dd28b3) landed. Rust's standard library
1126/// carries `impl From<&str> for Box<str>` and
1127/// `impl From<String> for Box<str>` but no blanket
1128/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1129/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1130/// every closed-set fieldless typed enum peer on the substrate that
1131/// carries the paired owned-input `Box<str>` axis but not the
1132/// borrowed-input axis forces every borrowed-input
1133/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1134/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1135/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1136/// have no compile-time link back to the substrate primitive.
1137///
1138/// Pinned load-bearing by
1139/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1140/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1141/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1142/// surface, plus a blanket-derived [`Into`] shape witness and a
1143/// cross-axis pin against the paired owned-input
1144/// [`From<RestartStrategy> for Box<str>`] and the sibling
1145/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1146/// return-shape axes).
1147impl From<&RestartStrategy> for Box<str> {
1148    fn from(strategy: &RestartStrategy) -> Box<str> {
1149        Box::<str>::from(strategy.as_str())
1150    }
1151}
1152
1153/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1154/// forward projection on the M2 OTP-shape sibling-restart
1155/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1156/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1157/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1158/// on the caixa surface (`:supervisor :estrategia`), immediately after
1159/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1160/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1161/// 2×4 corner on this enum. Routes byte-for-byte through the
1162/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1163/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1164/// `&'static str`), so every consumer that binds a
1165/// [`RestartStrategy`] through the standard-library `.into()` /
1166/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1167/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1168/// running under `axum` + `tokio` whose per-arm structured-log field
1169/// crosses an `.await` boundary and demands the [`Sync`] +
1170/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1171/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1172/// forces every downstream `.clone()` through a heap allocation, while
1173/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1174/// resolves the same `.clone()` through a refcount bump), a future
1175/// wasm-operator's per-supervisor reconciliation scheduler that
1176/// dispatches the same per-strategy diagnostic key onto multiple
1177/// concurrent reconcile-loop tasks holding shared-ownership through
1178/// [`std::sync::Arc<str>`], a future
1179/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1180/// log recorder whose typing folds a shared-ownership envelope onto
1181/// the span-context axis, a generic
1182/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1183/// shared-ownership per-strategy cache — reaches the same four-arm
1184/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1185/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1186/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1187/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1188/// the sibling
1189/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1190/// forward-projection corner already returns.
1191///
1192/// First-mover on the substrate-wide trait-idiomatic
1193/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1194/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1195/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1196/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1197/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1198/// closed-set fieldless typed enum on the substrate that carries the
1199/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1200/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1201/// [`From<Self> for String`] / [`From<&Self> for String`] /
1202/// [`From<Self> for Cow<'static, str>`] /
1203/// [`From<&Self> for Cow<'static, str>`] /
1204/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1205/// but not the [`std::sync::Arc<str>`] axis forces every
1206/// `std::sync::Arc<str>`-parameterized call site through a
1207/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1208/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1209/// composition through the owned-`String` axis that allocates
1210/// twice — once into the intermediate `String`, once into the
1211/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1212/// have no compile-time link back to the substrate primitive. Opening
1213/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1214/// peer on the caixa substrate surface establishes the "route through
1215/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1216/// `&'static str`" discipline; every future closed-set fieldless
1217/// typed enum peer on the substrate ([`RestartPolicy`],
1218/// [`crate::aplicacao::PlacementStrategy`],
1219/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1220/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1221/// [`crate::kind::CaixaKind`],
1222/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1223/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1224/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1225/// tracking the same 14-peer emit-set every prior projection tier
1226/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1227/// converged onto.
1228///
1229/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1230/// (69ef45c) — same "opens a new substrate-wide projection tier"
1231/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1232/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1233/// value the [`Box<str>`] axis's owned-move return-shape cannot
1234/// provide.
1235///
1236/// Pinned load-bearing by
1237/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1238/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1239/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1240/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1241/// axis byte-parity pins against the sibling owned-input
1242/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1243/// axes).
1244impl From<RestartStrategy> for std::sync::Arc<str> {
1245    fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1246        std::sync::Arc::<str>::from(strategy.as_str())
1247    }
1248}
1249
1250/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1251/// forward projection on the M2 OTP-shape sibling-restart
1252/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1253/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1254/// forward-projection axis on the first M2 OTP-shape closed-set
1255/// fieldless typed enum peer on the caixa surface
1256/// (`:supervisor :estrategia`), companion to the paired owned-input
1257/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1258/// prior (bca2ec8). Routes byte-for-byte through the
1259/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1260/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1261/// `&'static str`), so every consumer that binds a
1262/// [`&RestartStrategy`] through the standard-library `.into()` /
1263/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1264/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1265/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1266/// `Sync` + `Send`-safe structured-log field across an `.await`
1267/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1268/// diagnostic-column dispatch, a future wasm-operator's per-
1269/// supervisor reconciliation pipeline whose
1270/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1271/// the shared-ownership per-strategy key without a spurious [`Copy`]
1272/// deref (which would only be reachable through the owned-input
1273/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1274/// calling `.copied()` on the iterator), a future
1275/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1276/// collector recording a borrowed-`&RestartStrategy` per-arm field
1277/// onto the parent span's shared-ownership context — reaches the
1278/// same four-arm lifted
1279/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1280/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1281/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1282/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1283/// the paired owned-input
1284/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1285/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1286/// forward-projection corner already return.
1287///
1288/// Second peer on the substrate-wide trait-idiomatic
1289/// [`std::sync::Arc<str>`] forward-projection family opened one
1290/// commit prior (bca2ec8) on the paired owned-input
1291/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1292/// the `{Self, &Self}` input-shape corner of the
1293/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1294/// fieldless typed enum peer on the caixa surface, exactly as
1295/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1296/// owning half (69ef45c) landed. Rust's standard library carries
1297/// `impl From<&str> for std::sync::Arc<str>` and
1298/// `impl From<String> for std::sync::Arc<str>` but no blanket
1299/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1300/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1301/// every closed-set fieldless typed enum peer on the substrate that
1302/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1303/// not the borrowed-input axis forces every borrowed-input
1304/// [`std::sync::Arc<str>`]-parameterized call site through a
1305/// spurious [`Copy`] deref
1306/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1307/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1308/// type bounds have no compile-time link back to the substrate
1309/// primitive.
1310///
1311/// Pinned load-bearing by
1312/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1313/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1314/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1315/// surface, plus a blanket-derived [`Into`] shape witness and a
1316/// cross-axis pin against the paired owned-input
1317/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1318/// borrowed-input `{&'static str, String, Cow<'static, str>,
1319/// Box<str>}` return-shape axes).
1320impl From<&RestartStrategy> for std::sync::Arc<str> {
1321    fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1322        std::sync::Arc::<str>::from(strategy.as_str())
1323    }
1324}
1325
1326/// Substrate-canonical [`AsRef<[u8]>`] byte-view projection on the M2
1327/// OTP-shape sibling-restart [`RestartStrategy`] closed-set fieldless
1328/// typed enum — routes byte-for-byte through the substrate-primitive
1329/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1330/// [`str::as_bytes`] on the returned `&'static str`, so any future
1331/// consumer that binds a [`RestartStrategy`] through a standard-library
1332/// `<T: AsRef<[u8]>>` trait bound reaches the same four-arm lifted
1333/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1334/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1335/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1336/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
1337/// `PascalCase` wire byte-string emit-set the paired sibling
1338/// [`AsRef<str>`] (5b828ed) / [`std::fmt::Display`] /
1339/// [`RestartStrategy::as_str`] str-view surfaces and every
1340/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>,
1341/// std::sync::Arc<str>}` reverse-projection corner already return —
1342/// through the byte-view axis, which the str-view axes cannot express.
1343///
1344/// Rust's standard library carries `impl AsRef<[u8]> for str` and
1345/// `impl AsRef<[u8]> for String`, so the two-hop composition
1346/// `strategy.as_str().as_bytes()` (or, equivalently,
1347/// `AsRef::<str>::as_ref(&strategy).as_bytes()`) is reachable through
1348/// the pre-existing str-view axis alone. But that two-hop shape has no
1349/// compile-time link back to the byte-projection axis, forces every
1350/// downstream `<T: AsRef<[u8]>>`-bound consumer to open-code the
1351/// two-hop composition at every call site, and admits a silent split
1352/// whenever a future call site takes a sibling reverse-projection axis
1353/// whose `.as_bytes()` byte-tail carries no compile-time byte-view
1354/// surface (`Display` returns a formatter, `String` / `Box<str>` /
1355/// `Arc<str>` allocate). The lifted single-hop impl closes the
1356/// byte-view axis so every future `<T: AsRef<[u8]>>`-bound consumer
1357/// reaches the substrate primitive through one trait dispatch, and
1358/// every future arm addition (an OTP-`rest_for_all` fifth arm the
1359/// theory
1360/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1361/// might reach for once the four canonical OTP strategies stop covering
1362/// the substrate's discovered load-shape) grows the byte-view axis
1363/// through one edit on the substrate-primitive `as_str` accessor, not a
1364/// coordinated rewrite across every future `<T: AsRef<[u8]>>`-bound
1365/// consumer's arm-set.
1366///
1367/// The primary compounding target is the same `caixa-lacre` BLAKE3
1368/// content-address closure the peer [`crate::CaixaKind`] (69d8d86),
1369/// [`crate::dialeto::CaixaDialeto`] (8151347),
1370/// [`crate::dep::DepList`] (05ffaca),
1371/// [`crate::aplicacao::PlacementStrategy`] (daa8705), and
1372/// [`crate::aplicacao::RateLimitUnit`] (4867e0f) `AsRef<[u8]>` impls
1373/// open onto: [`blake3::hash`] and [`blake3::Hasher::update`] both bind
1374/// their input through `impl AsRef<[u8]>`, so any future per-supervisor
1375/// content-address tag that folds an `:estrategia` discriminator
1376/// byte-tag into the [`crate::Lacre`] closure (a hypothetical
1377/// `hasher.update(estrategia);`-shape composition partitioning the
1378/// four OTP restart-topology closures at content-address time so
1379/// downstream `Lacre` consumers key per-strategy reconciliation caches
1380/// off the typed discriminator rather than the sibling `&'static str`
1381/// wire scalar) reaches the substrate-primitive `as_str` accessor
1382/// through this impl and no other.
1383///
1384/// Opens the trait-idiomatic byte-view axis on the first M2 OTP-shape
1385/// closed-set fieldless typed enum peer on the caixa surface
1386/// (`:supervisor :estrategia`), extending the substrate-wide byte-view
1387/// campaign the sibling [`crate::CaixaKind`] first-mover (69d8d86)
1388/// opened onto the fifth in-caixa-core enum peer. The remaining
1389/// in-caixa-core closed-set fieldless typed-enum peers
1390/// ([`RestartPolicy`], [`crate::aplicacao::WitShape`],
1391/// [`crate::upgrade::UpgradeInstruction`],
1392/// [`crate::render::PathShapeViolation`]) each carry the same
1393/// [`AsRef<str>`] + `pub const fn as_str` substrate-primitive accessor
1394/// discipline, so a future extension of the byte-view axis onto each
1395/// peer reaches through one impl per enum keyed to that peer's
1396/// substrate-primitive accessor.
1397///
1398/// Pinned load-bearing by
1399/// [`tests::restart_strategy_as_ref_bytes_routes_through_as_str_accessor`]
1400/// (fail-before-pass-after byte-parity pin against
1401/// [`RestartStrategy::as_str`] `.as_bytes()` across the four-arm
1402/// [`RestartStrategy::ALL`] emit-set, cross-axis witness against the
1403/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
1404/// [`RestartStrategy::as_str`] axes' `.as_bytes()` byte-tails,
1405/// cross-axis witness against the paired reverse-projection
1406/// `{&'static str, String, Cow<'static, str>, Box<str>,
1407/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
1408/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
1409/// byte-input function accepts a [`RestartStrategy`] directly through
1410/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
1411/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
1412/// consumer axis to reach the caixa-lacre compounding target). Any
1413/// future silent detour that routes the byte-view impl off the
1414/// substrate-primitive [`RestartStrategy::as_str`] accessor (a per-arm
1415/// inline `b"OneForOne".as_slice()`-shaped re-inlining that opens a
1416/// compile-time link to the un-lifted arm-literal, a swap onto the
1417/// kebab-case [`gen_platform::Discriminant`] catalog identity that
1418/// would collide the wire axis with the dispatcher-catalog axis) trips
1419/// at caixa-core test time rather than at a downstream byte-consumer's
1420/// silent split.
1421impl AsRef<[u8]> for RestartStrategy {
1422    fn as_ref(&self) -> &[u8] {
1423        self.as_str().as_bytes()
1424    }
1425}
1426
1427/// Per-child restart policy.
1428///
1429/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1430#[derive(
1431    Serialize,
1432    Deserialize,
1433    Debug,
1434    Clone,
1435    Copy,
1436    PartialEq,
1437    Eq,
1438    Hash,
1439    gen_platform::TypedDispatcher,
1440    gen_platform::Discriminant,
1441    gen_platform::IsVariant,
1442    gen_platform::FromStrKind,
1443)]
1444pub enum RestartPolicy {
1445    /// Always restart the child, regardless of how it died. Used for
1446    /// long-running services that must always be up.
1447    Permanent,
1448    /// Never restart. Used for one-shot work whose completion is
1449    /// itself the success signal (`oneShot` triggers map here).
1450    Temporary,
1451    /// Restart only when the child died *abnormally* (non-zero exit
1452    /// or unhandled exception). A clean exit completes the child.
1453    Transient,
1454}
1455
1456impl Default for RestartPolicy {
1457    fn default() -> Self {
1458        // Route the [`Default for RestartPolicy`] impl's return arm through
1459        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1460        // `pub const` rather than a raw `Self::Permanent` arm — one source
1461        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1462        // default across the two production consumers that currently
1463        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1464        // and the serde-side `#[serde(default)]` on
1465        // [`ChildSpec::restart`] that resolves an author-omitted
1466        // `:children :restart` slot through `RestartPolicy::default()`).
1467        // Peer of the sibling per-`:supervisor` axis
1468        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1469        // route (95ffacc) — the two impls now share one substrate-primitive
1470        // lift discipline, so any future coherent rebrand of the OTP-shape
1471        // supervisor+child default set migrates through typed constants in
1472        // lockstep instead of splitting a lifted supervisor half against
1473        // an open-coded child half. Pinned by
1474        // `restart_policy_default_routes_through_lifted_default` +
1475        // `child_spec_serde_default_restart_routes_through_lifted_default`
1476        // in the tests module.
1477        SUPERVISOR_CHILD_RESTART_DEFAULT
1478    }
1479}
1480
1481impl RestartPolicy {
1482    /// Exhaustive iteration surface for every consumer that walks the
1483    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1484    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1485    /// per-child admission-webhook rejection body naming the accepted-
1486    /// `:restart` list, a future `feira supervisor --restart …` CLI
1487    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1488    /// over the slice, the future `feira app graph` per-child restart
1489    /// column, any future round-trip fuzz harness that sweeps every
1490    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1491    /// theory
1492    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1493    /// might reach for once the three canonical OTP restart policies
1494    /// stop covering the substrate's discovered load-shape) extends
1495    /// this slice as one edit and every consumer picks up the new entry
1496    /// by construction; the compiler-checked exhaustiveness on the
1497    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1498    /// is the build-time guarantee that no arm forgets to grow.
1499    ///
1500    /// Peer of the sibling closed-set typed enums'
1501    /// [`RestartStrategy::ALL`] (4eec29c) /
1502    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1503    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1504    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1505    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1506    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1507    /// closed-set typed enum on the caixa surface to converge onto the
1508    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1509    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1510    /// sibling-restart-strategy axis; this closes the per-child
1511    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1512    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1513
1514    /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1515    /// `PascalCase` wire byte-string axis — the closed three-arm roster
1516    /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1517    /// through the paired
1518    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1519    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1520    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1521    /// `pub const` roster the [`Self::as_str`] emitter (and the
1522    /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1523    /// walks — and byte-for-byte the same three strings the un-`rename`d
1524    /// `Serialize` derive emits under the paired
1525    /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1526    /// JSON / YAML CR round-trip.
1527    ///
1528    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1529    /// roster on the top-level typed-kind discriminator's `PascalCase`
1530    /// wire byte-string axis, the sibling
1531    /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1532    /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1533    /// closed-set typed enum to converge onto the paired-roster
1534    /// discipline), the sibling
1535    /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1536    /// roster on the first M3 mesh-shape distribution-strategy closed-
1537    /// set typed enum, and the sibling
1538    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1539    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1540    /// rosters on the OTP-appup discriminator's two-axis roster split —
1541    /// the same closed-set exhaustive-accept-set roster discipline
1542    /// extended here onto the second and final M2 OTP-shape sibling-
1543    /// enum on the caixa surface, closing the per-child restart-decision-
1544    /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1545    /// per-supervisor sibling-restart-strategy axis on the same M2
1546    /// `:supervisor` slot.
1547    ///
1548    /// Downstream consumers of the closed accepted-wire-form set — a
1549    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1550    /// webhook rejection body enumerating the accepted JSON `:restart`
1551    /// values verbatim (as distinct from the kebab-case dispatcher-
1552    /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1553    /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1554    /// disagrees with the wire byte-string these `PascalCase` entries
1555    /// carry — the split the sibling
1556    /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1557    /// pin already makes load-bearing), a future `feira supervisor
1558    /// --restart …` CLI-side "did you mean" hint whose candidate-list
1559    /// must byte-match the wire form the operator's per-child dispatch
1560    /// keys off, a future `feira app graph` per-child `:restart`-
1561    /// histogram column that renders zero-count arms, a future
1562    /// `caixa-operator` per-reconcile-step diagnostic log line
1563    /// enumerating accepted wire forms on an unknown-policy rejection,
1564    /// a future
1565    /// `tracing::field::valuable::Value::List` structured-log accepted-
1566    /// wire-form emit — now reach for one lifted substrate-primitive
1567    /// roster rather than open-coding a three-string array-literal
1568    /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1569    /// compile-time link back to the typed [`RestartPolicy`] enum. A
1570    /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1571    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1572    /// might reach for once the three canonical OTP restart policies
1573    /// stop covering the substrate's discovered load-shape) extends
1574    /// this roster as a single edit — paired with the [`Self::as_str`]
1575    /// match's compiler-checked exhaustiveness on the new arm — and
1576    /// every consumer picks up the new wire form by construction rather
1577    /// than a coordinated array-literal rewrite across every downstream
1578    /// site.
1579    ///
1580    /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1581    /// (three) by
1582    /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1583    /// variant's [`Self::as_str`] projection is pinned to a member of
1584    /// the roster so a silent skew between the emitter's arm-set and
1585    /// this const's arm-set trips at caixa-core test time rather than at
1586    /// a downstream consumer's accepted-set enumeration miss, and every
1587    /// entry is further pinned to open with an ASCII uppercase byte so
1588    /// a silent collapse of the `PascalCase` wire-form axis with the
1589    /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1590    /// to a sibling [`Self::discriminant`] kebab byte-string that would
1591    /// let a wire-axis consumer accept the dispatcher-catalog
1592    /// vocabulary) trips here rather than at a downstream K8s-CR round-
1593    /// trip miss.
1594    pub const WIRE_NAMES: &'static [&'static str] = &[
1595        crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1596        crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1597        crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1598    ];
1599
1600    /// Canonical PascalCase discriminator scalar this variant serializes
1601    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1602    /// arms return the paired
1603    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1604    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1605    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1606    /// constants so every substrate consumer that dispatches on the
1607    /// per-child restart-decision policy (the future wasm-operator's
1608    /// per-child post-exit restart-decision branch, the future M4
1609    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1610    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1611    /// reconciliation scheduler's per-child-policy fan-out) reads the
1612    /// same byte-string the `Serialize` derive emits — the pin test in
1613    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1614    /// asserts the two paths agree, peer of the M2
1615    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1616    /// sibling-restart-strategy axis and the M3
1617    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1618    /// per-Aplicacao distribution-strategy axis — the third of three
1619    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1620    /// surface to converge onto the same three-path-convergence
1621    /// (`Serialize` derive → `as_str` helper → lifted constant)
1622    /// drift-detection posture.
1623    #[must_use]
1624    pub const fn as_str(self) -> &'static str {
1625        match self {
1626            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1627            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1628            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1629        }
1630    }
1631
1632    /// Substrate-canonical reverse projection on the `:children :restart`
1633    /// closed-set axis — parses the `PascalCase` discriminator scalar
1634    /// back to the typed variant, or `None` when `s` is outside the
1635    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1636    /// the same lifted
1637    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1638    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1639    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1640    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1641    /// of the round-trip migrate through one caixa-core edit on any
1642    /// future arm addition.
1643    ///
1644    /// Prior to this lift the substrate carried only the forward
1645    /// `Self → &str` projection on the OTP per-child restart-policy
1646    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1647    /// impl routed through it, the `Serialize` derive that emits the
1648    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1649    /// plus the kebab-case dispatcher-catalog identity via
1650    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1651    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1652    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1653    /// "Transient" => …, _ => … }` cascade that expressed no
1654    /// compile-time link back to the typed variant's canonical lifted
1655    /// constant. A future variant rename or per-arm serde-attribute
1656    /// drift would silently split the wire byte-string one non-serde
1657    /// consumer parsed from the one the emitter wrote, with the failure
1658    /// surfacing at the operator's reconcile posture (a `:temporary`
1659    /// `oneShot` child being restarted on clean exit, treating the
1660    /// successful-completion signal as failure and re-running the
1661    /// completion-terminal one-shot indefinitely; a `:transient` child
1662    /// that clean-exited being restarted, masking the clean-completion
1663    /// contract) far from the rebrand commit and with no field naming
1664    /// the drift.
1665    ///
1666    /// Distinct axis from the [`std::str::FromStr`] impl the
1667    /// [`gen_platform::FromStrKind`] derive already installs on this
1668    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1669    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1670    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1671    /// this method inverts the `PascalCase` wire byte-string
1672    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1673    /// catalog identity live in kebab-case (where every peer catalog
1674    /// identifier already lives) without forcing a wire-format rename
1675    /// on the tatara-lisp author surface (`:restart Permanent`,
1676    /// `PascalCase`) — the same two-axis distinction the sibling
1677    /// [`RestartStrategy::from_wire`] (4eec29c) /
1678    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1679    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1680    /// carry on their peer closed-set typed-enum wire round-trips.
1681    ///
1682    /// Same closed-set-reverse-projection discipline the sibling
1683    /// [`RestartStrategy::from_wire`] (4eec29c) /
1684    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1685    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1686    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1687    /// carry on the peer wire-side `str → Self` axes — extended onto
1688    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1689    /// sixth substrate-side closed-set typed enum (and the third and
1690    /// final OTP-shape closed-enum discriminator axis) to converge on
1691    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1692    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1693    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1694    /// derive already installs on the sibling kebab-case axis. Returns
1695    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1696    /// shapes: the caller picks the diagnostic form appropriate for
1697    /// its use site.
1698    #[must_use]
1699    pub fn from_wire(s: &str) -> Option<Self> {
1700        match s {
1701            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1702            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1703            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1704            _ => None,
1705        }
1706    }
1707}
1708
1709/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1710/// pretty-printed byte-string every consumer that formats the policy as
1711/// user-facing text lands on (the future wasm-operator's per-child
1712/// post-exit restart-decision diagnostic line, the future `feira app
1713/// graph` per-child restart column, the future M4
1714/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1715/// admission-webhook rejection body) reaches for the same lifted
1716/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1717/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1718/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1719/// wire-format `Serialize` derive already emits under
1720/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1721/// [`RestartPolicy::as_str`] helper already returns.
1722///
1723/// Pre-convergence the two paths structurally disagreed — the
1724/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1725/// route (now retired here) sent [`std::fmt::Display`] through the
1726/// gen-platform discriminant catalog string, which arrives kebab-case as
1727/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1728/// (whose variant names each collapse to their own lowercase form under
1729/// the kebab-case transform), while the wire format ran as `PascalCase`
1730/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1731/// serde derive. Every consumer that formatted the policy for a
1732/// diagnostic line, a graph column, or a rejection body under
1733/// `format!("{v}")` therefore landed under a different byte-string than
1734/// the wire format the operator's per-child-policy dispatch keyed off —
1735/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1736/// diagnostic quoting `"permanent"` while the wire scalar the operator
1737/// probed was `"Permanent"`) surfaced as a confused correlate at
1738/// operator-log time far from the two-declaration site.
1739///
1740/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1741/// path: every `format!("{v}")` call reaches the same lifted
1742/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1743/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1744/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1745/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1746/// byte-string per variant. A future variant rename or
1747/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1748/// exactly one place, structurally.
1749///
1750/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1751/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1752/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1753/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1754/// registration keys the catalog off the same kebab identity. The two
1755/// naming worlds now live on separate typed methods (`Display` /
1756/// `as_str` for the wire byte-string, `discriminant` for the catalog
1757/// identity) rather than sharing one `Display` route that structurally
1758/// disagrees with the wire format.
1759///
1760/// Pin tests
1761/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1762/// and
1763/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1764/// assert the three paths agree byte-for-byte on every variant, so a
1765/// future variant rename or per-arm serde attribute drift is a build
1766/// error visible at caixa-core test time, not a silent per-consumer
1767/// dispatch miss at apply / reconcile time.
1768///
1769/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1770/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1771/// and the sibling [`RestartStrategy`] `Display` impl on the
1772/// per-supervisor sibling-restart-strategy axis — same three-path-
1773/// convergence discipline, extended to close the third and final of
1774/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1775/// surface.
1776impl std::fmt::Display for RestartPolicy {
1777    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1778        f.write_str(self.as_str())
1779    }
1780}
1781
1782/// Substrate-canonical [`AsRef<str>`] projection on the M2
1783/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1784/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1785/// scalar accessor the paired [`std::fmt::Display`] impl and the
1786/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1787/// future consumer that binds a [`RestartPolicy`] through the
1788/// standard-library `impl AsRef<str>` bound (a future
1789/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1790/// composes the emitted `PascalCase` wire scalar into a
1791/// [`std::process::Command::arg`] shell-out of the future
1792/// wasm-operator's per-child admission gate, a per-child structured-
1793/// log recorder on the future `caixa-operator`'s hierarchical
1794/// reconciliation surface that accepts `impl AsRef<str>` at the
1795/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1796/// lookup keyed on the restart-policy wire byte through
1797/// `map.get::<str>(policy.as_ref())` on a future per-policy
1798/// dispatch table) reaches the paired
1799/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1800/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1801/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1802/// lifted-const through one substrate-primitive dispatch rather
1803/// than an open-coded `.as_str()` projection at every wire-up.
1804///
1805/// Peer of the sibling [`std::fmt::Display`] impl on the same
1806/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1807/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1808/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1809/// byte-string per instance by construction. A future variant rename
1810/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1811/// enum reaches every one of the three paths (plus the wire-format
1812/// `Serialize` derive that already routes through the same lifted
1813/// const) through exactly one caixa-core edit.
1814///
1815/// Same "route the trait impl through the substrate-primitive
1816/// accessor" discipline the sibling [`crate::CaixaVersion`]
1817/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1818/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1819/// the axis onto the paired per-child-restart-decision-policy
1820/// sibling on the same M2 `:supervisor` slot (the second M2
1821/// OTP-shape closed-set typed enum to converge onto the standard-
1822/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1823/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1824/// primitive so a caller who has one has both; before this lift,
1825/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1826/// [`AsRef<str>`] impl the convention names.
1827///
1828/// Pinned load-bearing by
1829/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1830/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1831/// three-arm closed set) and
1832/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1833/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1834/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1835/// arm) — any future silent detour that routes the impl through a
1836/// divergent projection (a per-arm inline `match self { … }`
1837/// re-inlining that opens a compile-time link to the un-lifted
1838/// arm-literal, a swap onto the kebab-case
1839/// [`gen_platform::Discriminant`] catalog identity that would
1840/// collide the wire axis with the dispatcher-catalog axis) trips at
1841/// caixa-core test time under `assert_eq!` rather than at a
1842/// downstream `impl AsRef<str>`-bound consumer's silent split.
1843impl AsRef<str> for RestartPolicy {
1844    fn as_ref(&self) -> &str {
1845        self.as_str()
1846    }
1847}
1848
1849/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1850/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1851/// byte-for-byte through the paired substrate-primitive
1852/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1853/// consumer that binds a `PascalCase` `:children :restart` wire
1854/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1855/// axis (a future [`caixa-feira`] `feira supervisor --restart
1856/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1857/// `let restart: RestartPolicy = s.try_into()?`, a future
1858/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1859/// `spec.children[*].restart: String` field through
1860/// `RestartPolicy::try_from(&s)?`, a generic
1861/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1862/// set typed enums) reaches the same three-arm accept-set the sibling
1863/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1864/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1865/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1866/// … }` cascade whose arm-set has no compile-time link back to the
1867/// substrate primitive.
1868///
1869/// Complements the pre-existing forward-projection triple
1870/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1871/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1872/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1873/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1874/// caller who can project *out to* a `&str` can also project *in from*
1875/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1876/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1877/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1878/// trigger under a `FromStr` impl and to avoid colliding with the
1879/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1880/// already installs on the paired *kebab-case dispatcher-catalog* axis
1881/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1882/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1883/// idiomatic reverse axis on the *`PascalCase` wire* half without
1884/// disturbing either the method-named `from_wire` shape every sibling
1885/// closed-set typed enum on the substrate already carries or the
1886/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1887/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1888///
1889/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1890/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1891/// caller picks the diagnostic form appropriate for its use site (a
1892/// future `feira supervisor --restart` arg-parse composes its own
1893/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1894/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1895/// wraps the `Err(())` outcome with the accepted-set enumeration for
1896/// operator diagnostics, a `Result::map_err` at the call site lifts the
1897/// unit-error to a per-verb error type). Same shape the peer
1898/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1899/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1900/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1901/// their peer closed-set typed enums' reverse projections.
1902///
1903/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1904/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1905/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1906/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1907/// might reach for once the three canonical OTP restart policies stop
1908/// covering the substrate's discovered load-shape) grows the trait-
1909/// idiomatic axis by construction — one caixa-core edit on
1910/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1911/// projection every existing consumer keys off and the trait-idiomatic
1912/// reverse projection this impl exposes, without a coordinated rewrite
1913/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1914///
1915/// Extends the substrate-wide closed-set-enum reverse-projection family
1916/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1917/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1918/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1919/// closed-enum discriminator axis on the caixa surface — the paired
1920/// per-child `:children :restart` closed set the future wasm-operator's
1921/// hierarchical reconciliation scheduler's per-child post-exit
1922/// restart-decision branch keys off end-to-end.
1923///
1924/// Pinned load-bearing by
1925/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1926/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1927/// three-arm accept-set),
1928/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1929/// (rejection witness against silent accept-set widening), and
1930/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1931/// (cross-axis partition pin locking the trait and method-named
1932/// projections onto one accept-set).
1933impl TryFrom<&str> for RestartPolicy {
1934    type Error = ();
1935
1936    fn try_from(s: &str) -> Result<Self, Self::Error> {
1937        Self::from_wire(s).ok_or(())
1938    }
1939}
1940
1941/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1942/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1943/// byte-for-byte through the paired substrate-primitive
1944/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1945/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1946/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1947/// &str` with `'static` lifetime, so the trait's return-type promise is
1948/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1949/// literal.
1950///
1951/// Every future consumer that specifically needs `&'static str` lifetime
1952/// bytes on the per-child restart-decision axis (a
1953/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1954/// arm's typing demands `&'static str`, a
1955/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1956/// on the future M4 admission-webhook rejection body where the
1957/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1958/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1959/// or error formatter that requires the `'static` bound) reaches the same
1960/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1961/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1962/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1963/// primitive dispatch rather than an open-coded per-arm literal cascade
1964/// whose arm-set has no compile-time link back to the substrate primitive.
1965///
1966/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1967/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1968/// the second (and second-of-two-in-M2) closed-set typed enum on the
1969/// caixa surface to converge onto the paired trait-idiomatic forward-
1970/// projection axis. With this lift the paired per-child
1971/// `:children :restart` closed-set typed enum carries the full sibling
1972/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1973/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1974/// lift) plus the round-trip witness through both the trait-idiomatic
1975/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1976/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1977/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1978/// (an OTP-`intrinsic` fourth arm the theory
1979/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1980/// might reach for once the three canonical OTP restart policies stop
1981/// covering the substrate's discovered load-shape) grows the trait-
1982/// idiomatic forward axis by construction: one caixa-core edit on
1983/// [`RestartPolicy::as_str`] extends every one of the five sibling
1984/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1985/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1986/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1987/// bytes) without a coordinated rewrite across every future
1988/// `Into<&'static str>`-bound consumer's arm-set.
1989///
1990/// Pinned load-bearing by
1991/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1992/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1993/// three-arm emit-set, plus a `const`-context materialization witness for
1994/// the `&'static str` lifetime promise) and
1995/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1996/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1997/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1998/// round-trip witness through the paired trait-idiomatic reverse-
1999/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2000/// `policy.into::<&'static str>()` output re-parses back through
2001/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2002/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2003impl From<RestartPolicy> for &'static str {
2004    fn from(policy: RestartPolicy) -> &'static str {
2005        policy.as_str()
2006    }
2007}
2008
2009/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2010/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2011/// companion to the paired owned-input [`From<RestartPolicy> for
2012/// &'static str`] impl immediately above. Routes byte-for-byte through
2013/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2014/// fn` accessor so every consumer that binds a `&RestartPolicy`
2015/// through the standard-library `.into()` / [`From<&Self> for &'static
2016/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2017/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2018/// whose iterator over `&'static [RestartPolicy]` yields
2019/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2020/// [`From<RestartPolicy>`] axis alone forces every call site through
2021/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2022/// rather than the direct trait-idiomatic projection; a future generic
2023/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2024/// that walks the `iter().map(Into::into)` shape verbatim across every
2025/// substrate-wide closed-set typed enum; the future wasm-operator's
2026/// per-child post-exit restart-decision diagnostic line that composes
2027/// the accepted-set enumeration from an iterated
2028/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2029/// per-arm `match p { … }` cascade; a future
2030/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2031///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2032/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2033/// cannot compose without this borrowed-input axis in place) reaches
2034/// the same three-arm lifted
2035/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2036/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2037/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2038/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2039/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2040/// [`RestartPolicy::as_str`] surfaces already return.
2041///
2042/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2043/// forward-projection family opened on [`crate::dep::DepList`]
2044/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2045/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2046/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2047/// (e941836). Rust's `From` trait does not auto-derive the
2048/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2049/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2050/// exist in `core`), so every closed-set typed enum that carries the
2051/// owned-input axis but not the borrowed-input axis forces every
2052/// borrowed-input call site through a `.copied()` /
2053/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2054/// type bounds have no compile-time link to the substrate primitive.
2055/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2056/// OTP-shape peer to converge onto this campaign — sibling of the
2057/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2058/// with this lift both closed-set typed enums on the M2 `:supervisor`
2059/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2060/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2061/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2062/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2063/// forward-projection axis on the M2 OTP-shape slot as a unit.
2064///
2065/// Same three-path convergence discipline as the paired owned-input
2066/// impl (this borrowed-input axis, the paired owned-input
2067/// [`From<RestartPolicy> for &'static str`], and
2068/// [`RestartPolicy::as_str`] all route through the same lifted
2069/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2070/// variant rename or per-arm serde-attribute drift reaches every one
2071/// of the six sibling forward-projection paths
2072/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2073/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2074/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2075/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2076/// edit.
2077///
2078/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2079/// parse share the same `PascalCase` vocabulary by construction, so
2080/// the borrowed-input forward axis and the reverse axis compose
2081/// directly — the round-trip witness pin below locks this direct
2082/// composition without the intermediate wire-vocab hop the peer
2083/// [`crate::CaixaKind`] axis pair requires.
2084///
2085/// Pinned load-bearing by
2086/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2087/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2088/// three-arm emit-set via a borrowed input, plus a `const`-context
2089/// materialization witness for the `&'static str` lifetime promise,
2090/// plus a blanket `.into()` shape) and
2091/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2092/// (cross-axis partition pin against the paired owned-input
2093/// [`From<RestartPolicy> for &'static str`] impl, plus a
2094/// `.iter().map(Into::into)` pipe witness over
2095/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2096/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2097/// Self` round-trip without the wire-vocab intermediate the peer
2098/// [`crate::CaixaKind`] axis pair requires).
2099impl From<&RestartPolicy> for &'static str {
2100    fn from(policy: &RestartPolicy) -> &'static str {
2101        policy.as_str()
2102    }
2103}
2104
2105/// Trait-idiomatic *owned-`String`* forward projection on the second
2106/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2107/// owned-heap-string companion to the paired `&'static str`-returning
2108/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2109/// for &'static str`] impls immediately above. Routes byte-for-byte
2110/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2111/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2112/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2113/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2114/// future `serde_json::Value::String(policy.into())` structured-payload
2115/// composer where the `Value::String` arm typing demands an owned
2116/// [`String`] and the sibling [`&'static str`]-returning axis forces
2117/// an explicit `.to_owned()` / `String::from` restatement at every
2118/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2119/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2120/// lookup where the map's key type is owned [`String`] rather than
2121/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2122/// composer on the future M4 admission-webhook rejection body's
2123/// owned-arm, the future wasm-operator's per-child post-exit
2124/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2125/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2126/// — reaches the same three-arm lifted
2127/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2128/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2129/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2130/// paired [`std::fmt::Display`], [`AsRef<str>`],
2131/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2132/// forward-projection impls already return.
2133///
2134/// Extends the trait-idiomatic *owned-`String`* forward-projection
2135/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2136/// the caixa surface — mirror of the first-mover
2137/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2138/// axis on the sibling supervisor-level strategy enum. Rust's standard
2139/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2140/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2141/// every closed-set typed enum that carries the paired `AsRef<str>` /
2142/// `Display` / `From<Self> for &'static str` triple but not the
2143/// owned-[`String`] axis forces every owned-string call site through a
2144/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2145/// detour whose type bounds have no compile-time link to the
2146/// substrate primitive.
2147///
2148/// Deliberately routes through the human-readable
2149/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2150/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2151/// the diagnostic byte-string share the same vocabulary by
2152/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2153/// two axes diverge), so the owned-[`String`] projection lands
2154/// byte-identically on both the wire vocabulary the paired
2155/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2156/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2157/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2158/// axis parses the same `PascalCase` vocabulary — the direct two-way
2159/// `Self → String → Self` round-trip composes without the wire-vocab
2160/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2161/// axis pair requires.
2162///
2163/// Pinned load-bearing by
2164/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2165/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2166/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2167/// witness) and
2168/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2169/// (cross-axis partition pin against the paired owned-input
2170/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2171/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2172/// plus a `.iter().copied().map(String::from)` pipe witness over
2173/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2174/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2175/// borrow that closes the two-way `Self → String → Self` round-trip
2176/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2177/// pair).
2178impl From<RestartPolicy> for String {
2179    fn from(policy: RestartPolicy) -> String {
2180        policy.as_str().to_owned()
2181    }
2182}
2183
2184/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2185/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2186/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2187/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2188/// projection family on this enum, mirror of the first-mover
2189/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2190/// 2×2-completion corner on the sibling supervisor-level strategy
2191/// enum. Routes byte-for-byte through the substrate-primitive
2192/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2193/// [`str::to_owned`]) so every consumer that holds a borrowed
2194/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2195/// `serde_json::Value::String(String::from(&policy))` structured-payload
2196/// composer over a borrowed field, a future `Iterator::map` over
2197/// `&[RestartPolicy]` that projects to owned keys through
2198/// `.iter().map(String::from)`, a future `HashMap::<String,
2199/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2200/// where dereferencing the policy would force an unnecessary `Copy` at
2201/// every step, the future wasm-operator's per-supervisor
2202/// `child_policies.iter().map(String::from).collect()` per-child post-
2203/// exit restart-decision diagnostic emit whose iteration axis is
2204/// borrowed by construction — reaches the same three-arm lifted
2205/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2206/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2207/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2208/// paired [`std::fmt::Display`], [`AsRef<str>`],
2209/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2210/// forward-projection impls
2211/// ([`From<RestartPolicy> for &'static str`],
2212/// [`From<&RestartPolicy> for &'static str`],
2213/// [`From<RestartPolicy> for String`]) already return.
2214///
2215/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2216/// owned-`String` output* forward-projection family opened on
2217/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2218/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2219/// both M2 OTP-shape sibling peers (the paired supervisor-level
2220/// sibling-restart-strategy axis and the per-child restart-decision-
2221/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2222/// full four-corner family by construction. Rust's standard library
2223/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2224/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2225/// closed-set typed enum that carries the paired `AsRef<str>` /
2226/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2227/// &'static str` / `From<Self> for String` quintuple but not the
2228/// borrowed-input owned-[`String`] axis forces every borrowed-input
2229/// owned-string call site through a `policy.as_str().to_owned()` /
2230/// `String::from(*policy)` (with a spurious `Copy`) /
2231/// `policy.to_string()` (through `Display`) detour whose type bounds
2232/// have no compile-time link to the substrate primitive.
2233///
2234/// Deliberately routes through the human-readable
2235/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2236/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2237/// the diagnostic byte-string share the same vocabulary by
2238/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2239/// two axes diverge), so the borrowed-input owned-[`String`]
2240/// projection lands byte-identically on both the wire vocabulary the
2241/// paired [`serde::Serialize`] derive emits and the diagnostic
2242/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2243/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2244/// reverse-projection axis parses the same `PascalCase` vocabulary —
2245/// the direct two-way `&Self → String → Self` round-trip composes
2246/// without the wire-vocab intermediate hop the peer
2247/// [`crate::CaixaKind`] axis pair requires.
2248///
2249/// The remaining thirteen closed-set typed enums on the caixa
2250/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2251/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2252/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2253/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2254/// of this 2×2-completion campaign — each carries the same paired
2255/// quintuple that this borrowed-input owned-[`String`] axis extends
2256/// onto.
2257///
2258/// Pinned load-bearing by
2259/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2260/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2261/// three-arm emit-set through the borrowed-input surface) and
2262/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2263/// (cross-axis partition pin against the paired owned-input owned-
2264/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2265/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2266/// &'static str`] impl, and the sibling [`ToString::to_string`]
2267/// surface routed through [`std::fmt::Display`], plus a direct round-
2268/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2269/// [`String::as_str`] borrow that closes the two-way
2270/// `&Self → String → Self` round-trip on the trait-idiomatic
2271/// borrowed-input owned-[`String`] forward + reverse axis pair).
2272impl From<&RestartPolicy> for String {
2273    fn from(policy: &RestartPolicy) -> String {
2274        policy.as_str().to_owned()
2275    }
2276}
2277
2278/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2279/// output* forward projection on the M2 OTP-shape per-child-restart
2280/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2281/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2282/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2283/// borrowed-input) and first extended off it onto the sibling M2
2284/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2285/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2286/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2287/// surface (`:children :restart`). Routes byte-for-byte through the
2288/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2289/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2290/// that binds a [`RestartPolicy`] through the trait-idiomatic
2291/// [`std::borrow::Cow<'static, str>`] axis — a future
2292/// `axum::response::IntoResponse` composer whose per-policy
2293/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2294/// borrowed return, a future M4 admission-webhook rejection body
2295/// that composes the accepted-policy enumeration through the same
2296/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2297/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2298/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2299/// emitter on a per-child-policy diagnostic column — reaches the same
2300/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2301/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2302/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2303/// paired [`std::fmt::Display`], [`AsRef<str>`],
2304/// [`RestartPolicy::as_str`], and the four
2305/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2306/// forward-projection corners already return.
2307///
2308/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2309/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2310/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2311/// str` lifetime by construction (each `match` arm resolves to a
2312/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2313/// with static lifetime), so the zero-alloc borrowed arm is the
2314/// type-correct projection with no runtime allocation.
2315///
2316/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2317/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2318/// From<T> for Cow<'static, str>`), so the paired sibling
2319/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2320/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2321/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2322/// [`Cow<'static, str>`]-bound call site — every such site is forced
2323/// through a `Cow::Borrowed(policy.as_str())` /
2324/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2325/// no compile-time link back to the substrate primitive until this
2326/// lift.
2327///
2328/// Second peer to extend the substrate-wide trait-idiomatic
2329/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2330/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2331/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2332/// tier of the campaign (both sibling peers, `RestartStrategy` and
2333/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2334/// forward projection) so the remaining eleven peers
2335/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2336/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2337/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2338/// `FerriteRuntime`) are the future targets. Every future arm addition
2339/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2340/// might reach for once the three canonical OTP restart policies stop
2341/// covering the substrate's discovered load-shape) grows the
2342/// Cow<'static, str> axis by construction through one caixa-core edit
2343/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2344/// across every future Cow<'static, str>-bound consumer site.
2345///
2346/// Pinned load-bearing by
2347/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2348/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2349/// against [`RestartPolicy::as_str`] across the three-arm
2350/// [`RestartPolicy::ALL`]) and
2351/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2352/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2353/// for &'static str`], [`From<RestartPolicy> for String`], and
2354/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2355/// `.iter().copied().map(Cow::from)` pipe witness over
2356/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2357/// through the [`Cow<'static, str>`] axis alone and pins the
2358/// zero-alloc discipline on every element).
2359impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2360    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2361        std::borrow::Cow::Borrowed(policy.as_str())
2362    }
2363}
2364
2365/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2366/// output* forward projection on the M2 OTP-shape per-child-restart
2367/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2368/// companion to the paired owned-input
2369/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2370/// immediately above (0612398). Routes byte-for-byte through the same
2371/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2372/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2373/// that holds a `&RestartPolicy` and needs a
2374/// [`std::borrow::Cow<'static, str>`] — a
2375/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2376/// per-arm accept-set materializer (whose iterator over
2377/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2378/// `RestartPolicy`, so the paired owned-input
2379/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2380/// alone forces every call site through an explicit `.copied()` /
2381/// dereference / [`Copy`]-bound restatement rather than the direct
2382/// trait-idiomatic projection), a future generic
2383/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2384/// on a per-child-policy diagnostic column that walks the
2385/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2386/// webhook rejection body that composes the accepted-policy
2387/// enumeration from an iterated
2388/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2389/// per-arm `match p { … }` cascade — reaches the same three-arm
2390/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2391/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2392/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2393/// paired [`std::fmt::Display`], [`AsRef<str>`],
2394/// [`RestartPolicy::as_str`], the four
2395/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2396/// forward-projection corners, and the paired owned-input
2397/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2398/// already return.
2399///
2400/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2401/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2402/// [`RestartPolicy::as_str`] accessor's return carries the
2403/// `&'static str` lifetime by construction (each `match` arm resolves
2404/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2405/// with static lifetime), so the zero-alloc borrowed arm is the
2406/// type-correct projection with no runtime allocation.
2407///
2408/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2409/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2410/// one commit prior (0612398) on the paired owned-input
2411/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2412/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2413/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2414/// which carries both {Self, &Self} × Cow<'static, str> corners since
2415/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2416/// closed it on the top-level [`crate::CaixaKind`] one commit after
2417/// the owning half (99c1735) landed. This lift closes the whole M2
2418/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2419/// forward-projection campaign on both input-shape corners
2420/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2421/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2422/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2423/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2424/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2425/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2426/// standard library does not carry a blanket
2427/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2428/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2429/// closed-set fieldless typed enum peer on the substrate that carries
2430/// the paired owned-input [`Cow<'static, str>`] axis but not the
2431/// borrowed-input axis forces every borrowed-input
2432/// [`Cow<'static, str>`]-parameterized call site through a spurious
2433/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2434/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2435/// bounds have no compile-time link to the substrate primitive.
2436///
2437/// Pinned load-bearing by
2438/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2439/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2440/// against [`RestartPolicy::as_str`] across the three-arm
2441/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2442/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2443/// (cross-axis partition pin against the paired owned-input
2444/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2445/// paired borrowed-input owned-`&'static str`
2446/// [`From<&RestartPolicy> for &'static str`], and the paired
2447/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2448/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2449/// over [`RestartPolicy::ALL`] — whose iterator yields
2450/// `&RestartPolicy` by construction, so the borrowed-input
2451/// [`Cow<'static, str>`] axis is what routes the pipe through the
2452/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2453/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2454/// spurious [`Copy`] deref).
2455impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2456    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2457        std::borrow::Cow::Borrowed(policy.as_str())
2458    }
2459}
2460
2461/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2462/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2463/// closed-set fieldless typed enum — extends the substrate-wide
2464/// `Box<str>` forward-projection campaign tier opened one commit prior
2465/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2466/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2467/// typed enum peer on the caixa surface (`:children :restart`),
2468/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2469/// b4dc55c) closed the
2470/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2471/// corner on this enum. Routes byte-for-byte through the
2472/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2473/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2474/// so every consumer that binds a
2475/// `let key: Box<str> = policy.into();`-shaped call site — a
2476/// per-child metric-key materializer that stashes the policy
2477/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2478/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2479/// hierarchical reconciliation scheduler's per-child restart-decision
2480/// fan-out carries), a future admission-webhook rejection body whose
2481/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2482/// handle — reaches the same three-arm lifted
2483/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2484/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2485/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2486/// sibling
2487/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2488/// forward-projection corner already returns. Rust's standard library
2489/// carries `impl From<&str> for Box<str>` and
2490/// `impl From<String> for Box<str>` but no blanket
2491/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2492/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2493/// this axis is a distinct trait-idiomatic surface that a downstream
2494/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2495/// no other — without a `Box::from(policy.as_str())` open-code whose
2496/// type bounds have no compile-time link back to the substrate
2497/// primitive.
2498///
2499/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2500/// forward-projection family opened on the sibling-restart
2501/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2502/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2503/// projection campaign's owned-input corner on both M2 OTP-shape
2504/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2505/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2506/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2507/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2508/// are the future targets of the campaign.
2509///
2510/// Pinned load-bearing by
2511/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2512/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2513/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2514/// surface, plus a blanket-derived [`Into`] shape witness).
2515impl From<RestartPolicy> for Box<str> {
2516    fn from(policy: RestartPolicy) -> Box<str> {
2517        Box::<str>::from(policy.as_str())
2518    }
2519}
2520
2521/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2522/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2523/// closed-set fieldless typed enum — the borrowed-input companion to
2524/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2525/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2526/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2527/// projection axis on the second (and third-and-final) M2 OTP-shape
2528/// closed-set fieldless typed enum peer on the caixa surface
2529/// (`:children :restart`), routing byte-for-byte through the
2530/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2531/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2532/// Every consumer that holds a `&RestartPolicy` and needs a
2533/// [`Box<str>`] — a
2534/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2535/// per-arm accept-set materializer (whose iterator over
2536/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2537/// `RestartPolicy`, so the paired owned-input
2538/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2539/// call site through an explicit [`Copy`] deref or a
2540/// `.copied()` restatement rather than the direct trait-idiomatic
2541/// projection), a per-child metric-key materializer holding
2542/// `&RestartPolicy` through a `caixa-operator` hierarchical
2543/// reconciliation scheduler's borrow lifetime, a future admission-
2544/// webhook rejection body whose per-arm `Box<str>` field composes
2545/// from a borrowed `&RestartPolicy` handle — reaches the
2546/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2547/// this impl and no other, without a
2548/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2549/// have no compile-time link back to the substrate primitive.
2550///
2551/// Rust's standard library carries `impl From<&str> for Box<str>`
2552/// and `impl From<String> for Box<str>` but no blanket
2553/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2554/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2555/// set fieldless typed enum peer on the substrate that carries the
2556/// paired owned-input `Box<str>` axis but not the borrowed-input
2557/// axis forces every borrowed-input `Box<str>`-parameterized call
2558/// site through a spurious [`Copy`] deref
2559/// (`Box::<str>::from((*policy).as_str())`) or a
2560/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2561/// have no compile-time link back to the substrate primitive.
2562///
2563/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2564/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2565/// — closes the whole `{Self, &Self}` input-shape corner of the
2566/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2567/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2568/// closed the paired [`Cow<'static, str>`] axis one commit after
2569/// its owning half (0612398) landed on this enum. The remaining
2570/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2571/// core / render-side / outside-caixa-core tiers are the future
2572/// targets of the [`Box<str>`] campaign.
2573///
2574/// Pinned load-bearing by
2575/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2576/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2577/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2578/// surface, plus a blanket-derived [`Into`] shape witness, a
2579/// cross-axis partition pin against the paired owned-input
2580/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2581/// input `{&'static str, String, Cow<'static, str>}` return-shape
2582/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2583/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2584/// by construction, so the borrowed-input [`Box<str>`] axis is
2585/// what routes the pipe through the substrate-primitive
2586/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2587/// deref).
2588impl From<&RestartPolicy> for Box<str> {
2589    fn from(policy: &RestartPolicy) -> Box<str> {
2590        Box::<str>::from(policy.as_str())
2591    }
2592}
2593
2594/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2595/// forward projection on the M2 OTP-shape per-child-restart
2596/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2597/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2598/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2599/// returned `&'static str`, so every consumer that binds a
2600/// [`RestartPolicy`] through the standard-library `.into()` /
2601/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2602/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2603/// per-request `Sync` + `Send`-safe structured-log field composed
2604/// across an `.await` boundary through a
2605/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2606/// a future wasm-operator's per-child post-exit restart-decision
2607/// pipeline holding a shared-ownership per-arm cache key, a
2608/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2609/// collector recording a per-child-policy field onto the parent
2610/// span's shared-ownership context — reaches the same three-arm
2611/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2612/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2613/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2614/// sibling
2615/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2616/// forward-projection corner already returns.
2617///
2618/// Second peer on the substrate-wide trait-idiomatic
2619/// [`std::sync::Arc<str>`] forward-projection family opened one
2620/// projection tier prior (bca2ec8) on the paired sibling-restart
2621/// [`RestartStrategy`] owned-input first-mover — extends the tier
2622/// onto the second (and third-and-final) M2 OTP-shape closed-set
2623/// fieldless typed enum peer on the caixa surface
2624/// (`:children :restart`), immediately after the paired [`Box<str>`]
2625/// axis (0a1b313 / cb1d068) closed the whole
2626/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2627/// 2×4 corner on this enum. Rust's standard library carries
2628/// `impl From<&str> for std::sync::Arc<str>` and
2629/// `impl From<String> for std::sync::Arc<str>` but no blanket
2630/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2631/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2632/// axis is a distinct trait-idiomatic surface that a
2633/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2634/// reaches through this impl and no other — a paired
2635/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2636/// compile-time link back to the substrate primitive, and a two-step
2637/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2638/// through the owned-`String` axis allocates twice (once into the
2639/// intermediate `String`, once into the [`Arc<str>`] on the
2640/// `From<String>` conversion) where the single-step trait impl
2641/// allocates once.
2642///
2643/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2644/// same "extends the substrate-wide projection tier onto the next
2645/// M2 OTP-shape peer" discipline, extended onto the
2646/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2647/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2648/// owned-move return-shape cannot provide.
2649///
2650/// Pinned load-bearing by
2651/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2652/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2653/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2654/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2655/// axis byte-parity pins against the sibling owned-input
2656/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2657/// axes).
2658impl From<RestartPolicy> for std::sync::Arc<str> {
2659    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2660        std::sync::Arc::<str>::from(policy.as_str())
2661    }
2662}
2663
2664/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2665/// forward projection on the M2 OTP-shape per-child-restart
2666/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2667/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2668/// forward-projection axis on the second (and third-and-final) M2
2669/// OTP-shape closed-set fieldless typed enum peer on the caixa
2670/// surface (`:children :restart`), companion to the paired
2671/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2672/// one commit prior (b05724e). Routes byte-for-byte through the
2673/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2674/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2675/// `&'static str`), so every consumer that binds a
2676/// [`&RestartPolicy`] through the standard-library `.into()` /
2677/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2678/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2679/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2680/// `Sync` + `Send`-safe structured-log field across an `.await`
2681/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2682/// diagnostic-column dispatch, a future wasm-operator's per-child
2683/// post-exit restart-decision pipeline whose
2684/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2685/// into the shared-ownership per-arm key without a spurious [`Copy`]
2686/// deref (which would only be reachable through the owned-input
2687/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2688/// calling `.copied()` on the iterator), a future
2689/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2690/// collector recording a borrowed-`&RestartPolicy` per-arm field
2691/// onto the parent span's shared-ownership context — reaches the
2692/// same three-arm lifted
2693/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2694/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2695/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2696/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2697/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2698/// Box<str>}` forward-projection corner already return.
2699///
2700/// Closes the substrate-wide trait-idiomatic
2701/// [`std::sync::Arc<str>`] forward-projection family opened one
2702/// commit prior (b05724e) on the paired owned-input
2703/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2704/// the `{Self, &Self}` input-shape corner of the
2705/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2706/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2707/// surface, exactly as b3e72d7 closed the paired
2708/// [`std::sync::Arc<str>`] corner on the sibling-restart
2709/// [`RestartStrategy`] first-mover one commit after its owning half
2710/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2711/// corner on this enum one commit after its owning half (0a1b313)
2712/// landed. Rust's standard library carries `impl From<&str> for
2713/// std::sync::Arc<str>` and `impl From<String> for
2714/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2715/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2716/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2717/// enum peer on the substrate that carries the paired owned-input
2718/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2719/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2720/// call site through a spurious [`Copy`] deref
2721/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2722/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2723/// type bounds have no compile-time link back to the substrate
2724/// primitive.
2725///
2726/// Pinned load-bearing by
2727/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2728/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2729/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2730/// surface, plus a blanket-derived [`Into`] shape witness, a
2731/// cross-axis pin against the paired owned-input
2732/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2733/// borrowed-input `{&'static str, String, Cow<'static, str>,
2734/// Box<str>}` return-shape axes, and a
2735/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2736/// [`RestartPolicy::ALL`]).
2737impl From<&RestartPolicy> for std::sync::Arc<str> {
2738    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2739        std::sync::Arc::<str>::from(policy.as_str())
2740    }
2741}
2742
2743// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2744// supervisor surface — two more typed shadows over Erlang/OTP
2745// primitives the substrate now mechanically tracks (see
2746// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2747// theory/TYPED-ABSORPTION.md for the absorption arc).
2748gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2749gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2750
2751/// One child entry in the supervisor's `:children` list.
2752///
2753/// Every child references another caixa by `:caixa <nome>` + version
2754/// constraint. The supervisor materializes one ComputeUnit per entry.
2755#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2756#[serde(rename_all = "camelCase")]
2757pub struct ChildSpec {
2758    /// The child caixa's `:nome`. Must resolve via the same dependency
2759    /// resolution path as `:deps` (caixa-resolver).
2760    pub caixa: String,
2761
2762    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2763    /// [`crate::dep::Dep::versao`].
2764    pub versao: String,
2765
2766    /// Restart policy — an author-omitted slot degrades onto the
2767    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2768    /// (`permanent`, the Erlang/OTP worker-child default) through the
2769    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2770    /// to.
2771    #[serde(default)]
2772    pub restart: RestartPolicy,
2773}
2774
2775impl ChildSpec {
2776    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2777    /// accessor every consumer that reads the OTP-shape supervised
2778    /// child's identity keys off — returns the author-declared
2779    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2780    /// from the typed slot's own [`String`] storage.
2781    ///
2782    /// The `:children :caixa` slot carries the DNS-1123 label — the
2783    /// child caixa's `:nome` — that every emitted cluster artifact
2784    /// derives its `metadata.name` from verbatim: the rendered
2785    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2786    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2787    /// identity, and the per-child K8s Service `metadata.name` the
2788    /// future wasm-operator (M3) provisions for inter-child supervision-
2789    /// tree wiring. Every downstream consumer that fans on the child's
2790    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2791    /// per-child DNS-1123 gate at
2792    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2793    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2794    /// [`validate_no_self_supervision`] cross-slot equality check
2795    /// against the parent's `:nome`, every `SupervisorError` variant
2796    /// carrying the offending child caixa verbatim for `feira lint`
2797    /// rendering, the future wasm-operator's hierarchical reconciliation
2798    /// scheduler's per-child ComputeUnit-name projection, the future M4
2799    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2800    /// admission webhook).
2801    ///
2802    /// Prior to this lift the `.caixa` byte-string was accessed inline
2803    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2804    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2805    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2806    /// carriers' `child.caixa.clone()`, the dedup key's
2807    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2808    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2809    /// field-accesses that expressed no compile-time link back to the
2810    /// typed slot. A future extension of the `:children :caixa` axis to
2811    /// a richer author surface (a per-cluster alias table the operator
2812    /// pins through a future `:placement`-scoped slot on the supervisor
2813    /// tree, a namespace-qualified rewrite the M4 CR materializer
2814    /// applies per-CR, a per-child overlay from the future `:children
2815    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2816    /// acknowledges) would have had to be threaded through every
2817    /// open-coded copy in lockstep or one consumer would silently
2818    /// disagree with the peers on which caixa a given child resolves to
2819    /// — a child-set lookup that treated the name as `"cart-worker"`
2820    /// while the peer duplicate-detector treated it as
2821    /// `"tenant-a/cart-worker"` would silently split the
2822    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2823    /// self-supervision detector's parent-equality check, a two-consumer
2824    /// split at the validator far from the source `caixa.lisp` with no
2825    /// field naming the identity-drift root cause. Lifting the resolution
2826    /// rule to a typed method on the substrate primitive means every
2827    /// downstream consumer of the Supervisor's per-`:children` identity
2828    /// surface reaches for exactly one typed dispatch — the resolver's
2829    /// accept-set migrates as a unit on any future axis addition.
2830    ///
2831    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2832    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2833    /// mesh-slot surface — same "one typed dispatch on the substrate
2834    /// primitive, thin projections at each consumer" discipline extended
2835    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2836    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2837    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2838    /// accessor discipline for the shared substrate concept "another
2839    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2840    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2841    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2842    /// slot family's typed-accessor discipline now spans both the
2843    /// upgrade axis (`:upgrade-from`) and the supervision axis
2844    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2845    /// shape. Named `nome()` to match the tatara-lisp author-surface
2846    /// term the field's docstring already reaches for ("The child
2847    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2848    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2849    /// discipline the substrate already carries — the accessor's name
2850    /// maps directly onto the canonical caixa-identity vocabulary rather
2851    /// than shadowing the field's storage-side `caixa` label.
2852    #[must_use]
2853    pub const fn nome(&self) -> &str {
2854        self.caixa.as_str()
2855    }
2856
2857    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2858    /// requirement scalar accessor every consumer that reads the OTP-shape
2859    /// supervised child's version pin keys off — returns the author-declared
2860    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2861    /// the typed slot's own [`String`] storage.
2862    ///
2863    /// The `:children :versao` slot carries the Cargo-shaped semver
2864    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2865    /// which release of the supervised child caixa the OTP-shape supervisor
2866    /// tree materializes against — the same requirement grammar the peer
2867    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2868    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2869    /// and the shared [`crate::version::parse_requirement`] parser. Every
2870    /// downstream consumer that fans on the child's version pin keys off
2871    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2872    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2873    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2874    /// for `feira lint` rendering, every future per-cluster version-lock
2875    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2876    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2877    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2878    /// per-child version resolver, the future wasm-operator's per-child
2879    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2880    ///
2881    /// Prior to this lift the `.versao` byte-string was accessed inline at
2882    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2883    /// [`SupervisorSpec::validate`] requirement-gate call
2884    /// `require_valid_versao_requirement(&child.versao, …)` and the
2885    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2886    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2887    /// expressed no compile-time link back to the typed slot. A future
2888    /// extension of the `:children :versao` axis to a richer author surface
2889    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2890    /// flow, a lacre-projected concrete-version rewrite the operator
2891    /// materializes at CR-admission time, a future `:children :versao-lock`
2892    /// per-cluster override slot the wasm-operator's hierarchical
2893    /// reconciliation scheduler authors per-CR) would have had to be
2894    /// threaded through both open-coded copies in lockstep or one consumer
2895    /// would silently disagree with the peer on which release constraint a
2896    /// given child resolves to — the requirement-gate call reading
2897    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2898    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2899    /// the actual gate rejection input, a two-consumer split at the
2900    /// validator far from the source `caixa.lisp` with no field naming the
2901    /// version-pin drift root cause. Lifting the resolution rule to a typed
2902    /// method on the substrate primitive means every downstream
2903    /// requirement-facing consumer of the Supervisor's per-`:children`
2904    /// version-pin surface reaches for exactly one typed dispatch — the
2905    /// resolver's accept-set migrates as a unit on any future axis addition.
2906    ///
2907    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2908    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2909    /// surface — same "one typed dispatch on the substrate primitive, thin
2910    /// projections at each consumer" discipline extended onto the M2
2911    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2912    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2913    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2914    /// one accessor discipline for the shared substrate concept "another
2915    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2916    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2917    /// `:nome` scalar accessor — the pair
2918    /// `(nome(), versao_requirement())` jointly projects the
2919    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2920    /// that fans on per-child identity + version pin keys off, closing the
2921    /// last unlifted per-`:children` `String`-carry axis so every downstream
2922    /// per-`:children` reader now routes through a typed dispatch on the
2923    /// substrate primitive. Named `versao_requirement()` rather than
2924    /// `versao()` because the field's storage-side `.versao` label is
2925    /// already the author-surface term (`:versao`); the accessor's name
2926    /// carries the semantic role — the semver *requirement* string the
2927    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2928    /// so a raw field access and a typed dispatch read differently at every
2929    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2930    /// naming discipline verbatim.
2931    #[must_use]
2932    pub const fn versao_requirement(&self) -> &str {
2933        self.versao.as_str()
2934    }
2935
2936    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2937    /// per-child post-exit restart-decision policy scalar accessor every
2938    /// consumer that dispatches on the supervised child's post-exit
2939    /// reconcile posture keys off — returns the author-declared
2940    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2941    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2942    /// storage.
2943    ///
2944    /// The `:children :restart` slot carries the closed-set OTP-shaped
2945    /// per-child restart-decision policy discriminator
2946    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2947    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2948    /// on abnormal exit, the OTP `transient` clean-completion-aware
2949    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2950    /// `temporary` one-shot default) that every downstream consumer of
2951    /// the Supervisor's per-child post-exit reconcile branch keys off.
2952    /// Every future downstream consumer that fans on the per-child
2953    /// restart-decision keys off this scalar (the future `feira app
2954    /// graph` per-child restart column, the future wasm-operator's
2955    /// per-child post-exit restart-decision branch, the future M4
2956    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2957    /// admission webhook, the `caixa-operator`'s hierarchical
2958    /// reconciliation scheduler's per-child post-exit reconcile branch,
2959    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2960    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2961    /// pin threads through).
2962    ///
2963    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2964    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2965    /// scalar accessor and the M3 mesh-slot
2966    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2967    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2968    /// — same "one typed dispatch on the substrate primitive,
2969    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2970    /// the downstream renderer's per-arm fan-out" discipline extended
2971    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2972    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2973    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2974    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2975    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2976    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2977    /// on the sibling `String`-carry axes. The triple
2978    /// `(nome(), versao_requirement(), restart())` jointly projects the
2979    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2980    /// tree consumer that fans on per-child identity + version pin +
2981    /// restart-decision keys off, closing the last unlifted per-`:children`
2982    /// axis so every downstream per-`:children` reader now routes through
2983    /// a typed dispatch on the substrate primitive. Named `restart()` to
2984    /// match the storage field's name and the author-surface
2985    /// `:children :restart` slot term verbatim; the accessor's identity
2986    /// name maps onto the canonical OTP-shape per-child restart-decision-
2987    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2988    /// carries.
2989    ///
2990    /// Declared `pub const fn` to close the last non-`const`
2991    /// `Copy`-return raw-field-getter posture on the M2
2992    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2993    /// of the sibling M2 per-`:supervisor`
2994    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2995    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2996    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2997    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2998    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2999    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
3000    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
3001    /// downstream substrate-side `const`-context consumer of the
3002    /// per-`:children` restart-decision-policy scalar (a future
3003    /// module-scope `const _:() = assert!(matches!(child.restart(),
3004    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
3005    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3006    /// admission-webhook `const fn` per-child restart-decision floor
3007    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
3008    /// composer over the substrate primitive that fans on the per-child
3009    /// restart-decision policy at compile time) now reaches through the
3010    /// same typed dispatch on the substrate primitive at const-eval
3011    /// time as at runtime. A future non-`Copy`-return promotion of the
3012    /// scalar (an `Option<RestartPolicy>`-shape migration on the
3013    /// per-child restart-decision axis once heterogeneous per-cluster
3014    /// restart-policy overlays land, a per-tenant restart-policy-alias
3015    /// table the M4 CR materializer resolves per-CR) that would drop
3016    /// the `const` qualifier fails the fail-before-pass-after pin
3017    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
3018    /// build time rather than surfacing as a downstream consumer
3019    /// regression.
3020    #[must_use]
3021    pub const fn restart(&self) -> RestartPolicy {
3022        self.restart
3023    }
3024}
3025
3026/// Supervisor-typed slots that live alongside the standard Caixa
3027/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
3028/// the manifest stays a single typed form; this struct exists for
3029/// validation + conversion.
3030#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3031#[serde(rename_all = "camelCase")]
3032pub struct SupervisorSpec {
3033    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
3034    #[serde(default)]
3035    pub estrategia: RestartStrategy,
3036
3037    /// Max restarts within [`Self::restart_window`] before the
3038    /// supervisor itself terminates (and its parent supervisor decides
3039    /// what to do). Default 5.
3040    #[serde(default = "default_max_restarts")]
3041    pub max_restarts: u32,
3042
3043    /// Sliding window for `max_restarts`. Authored as a duration
3044    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
3045    /// is rejected by [`Self::validate`] — Erlang/OTP's
3046    /// `MaxIntensity / Period` invariant requires a positive window
3047    /// (a zero-period supervisor either trips on the first failure or
3048    /// never trips, depending on operator interpretation, neither of
3049    /// which is the author's intent). Omit the slot to express "no
3050    /// reset"; carry a positive duration to express the sliding window.
3051    #[serde(
3052        default,
3053        skip_serializing_if = "Option::is_none",
3054        with = "duration_codec"
3055    )]
3056    pub restart_window: Option<Duration>,
3057
3058    /// Static children. Empty for `SimpleOneForOne` (children added
3059    /// dynamically); required for the other three strategies.
3060    #[serde(default)]
3061    pub children: Vec<ChildSpec>,
3062}
3063
3064const fn default_max_restarts() -> u32 {
3065    // Route the private serde-`#[serde(default = "…")]` helper through
3066    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
3067    // `pub const` rather than the raw `5` literal — one source of truth
3068    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3069    // default across the two production consumers that currently
3070    // dispatch on it (this helper via `#[serde(default = "…")]` on
3071    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
3072    // impl at line 962). Pinned by
3073    // `default_max_restarts_helper_routes_through_lifted_default` +
3074    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
3075    // in the tests module; peer of the sibling caixa-core
3076    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
3077    // that now routes its author-omitted `:max-restarts` arm through
3078    // the same lifted constant.
3079    SUPERVISOR_MAX_RESTARTS_DEFAULT
3080}
3081
3082/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
3083/// count default for the `:supervisor :max-restarts` axis — the
3084/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
3085/// Erlang's worker-supervisor default, extracted as a typed `pub const`
3086/// so every substrate-side consumer that resolves "what
3087/// [`SupervisorSpec::max_restarts`] value does an author-omitted
3088/// `:max-restarts` slot degrade onto?" reaches for exactly one
3089/// substrate-primitive `u32`.
3090///
3091/// The `:max-restarts` default axis has two production consumers on the
3092/// substrate side today (both prior to this lift folded onto raw `5`
3093/// literals with no compile-time link back to a shared truth): the
3094/// serde-`#[serde(default = "default_max_restarts")]` helper on
3095/// [`SupervisorSpec::max_restarts`] that every author-omitted
3096/// `:supervisor :max-restarts` slot lands in past the derive-macro's
3097/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
3098/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
3099/// the composed [`SupervisorSpec`] altitude reaches through
3100/// (`feira app graph`, the future wasm-operator's per-supervisor
3101/// restart-intensity counter, the future M4
3102/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3103/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3104/// A pair of open-coded `5`s across two files that expressed no
3105/// compile-time link back to the shared OTP-canonical default — a
3106/// future rebrand of the default (a tightening to Elixir's
3107/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3108/// the operator pins through a future
3109/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3110/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3111/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3112/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3113/// per-child-cohort roadmap lands) would have had to be threaded
3114/// through both open-coded copies in lockstep or the wire-format
3115/// author-omitted arm and the view-construction author-omitted arm
3116/// would silently disagree on which restart-budget an omitted
3117/// `:max-restarts` resolves to (an author writing `:supervisor
3118/// (:max-restarts ())` would round-trip through serde with the new
3119/// default while `supervisor_view` silently continued to compose the
3120/// stale `5`, or vice versa), a two-consumer split at the composition
3121/// boundary far from the source `caixa.lisp` with no field naming the
3122/// default-drift root cause. Lifting the resolution rule to a typed
3123/// `pub const` on the substrate primitive means every downstream
3124/// consumer of the per-Supervisor default-restart-budget-count surface
3125/// reaches for exactly one substrate-primitive `u32` — the resolver's
3126/// accepted value migrates as a unit on any future axis change.
3127///
3128/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3129/// worker-supervisor default (the closest canonical OTP-shape
3130/// production reference the substrate carries, matching the sibling
3131/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3132/// this constant with on the paired sliding-window axis). Two orders of
3133/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3134/// (the upper bracket on the same axis, sibling of this lower default;
3135/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3136/// axis and now share one accessor discipline on the substrate) and
3137/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3138/// restart floor — the "one restart, then escalate" default is
3139/// deliberately loose enough to absorb a short burst of transient
3140/// child failures without escalating past the supervisor's parent
3141/// while remaining tight enough to trip the `MaxIntensity / Period`
3142/// ratio's escalation on a genuinely-stuck child within the sibling
3143/// `60s` sliding window.
3144///
3145/// Lifted as a typed `pub const` so the bound has exactly one source
3146/// of truth — the serde-side wire-format author-omitted arm at
3147/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3148/// struct-literal default field, and the caixa-core
3149/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3150/// arm all read from one place. Same shape every other typed default
3151/// in this crate carries (the sibling
3152/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3153/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3154/// sibling `:restart-window` axis, and the peer
3155/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3156/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3157/// axes).
3158pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3159
3160/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3161/// validated [`SupervisorSpec::max_restarts`] past
3162/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3163///
3164/// The typed field is `u32` (the zero-floor arm
3165/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3166/// so a programmatic struct literal
3167/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3168/// author-surface form (`:max-restarts 4294967295` or any
3169/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3170/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3171/// runtime substrate consuming the value (Erlang/OTP's
3172/// `MaxIntensity / Period` ratio, the future wasm-operator's
3173/// per-supervisor restart-intensity counter, the M4
3174/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3175/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3176/// escalation threshold is structurally so high that no realistic
3177/// restarts-per-`:restart-window` traffic shape can reach it, the
3178/// supervisor never escalates to its parent, and a bad child can loop
3179/// inside the window indefinitely with the parent supervisor structurally
3180/// never receiving the "this subtree has exceeded its restart budget"
3181/// signal the typed slot is meant to express — the canonical
3182/// "supervisor intensity declared, no escalation" footgun, exactly the
3183/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3184/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3185/// "trip the next-higher protection layer after N events in a rolling
3186/// window" counters with identical degenerate-at-the-high-end shape).
3187///
3188/// The `1000` ceiling matches the sibling
3189/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3190/// peer — same "events-per-window trip threshold" semantics, same `u32`
3191/// type, same no-op-at-the-high-end failure mode) so the M4
3192/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3193/// and the future wasm-operator's per-supervisor restart-intensity
3194/// counter reach for either field knowing the value is in `1..=1000`
3195/// without re-validating at the reconciler layer. The cap sits two
3196/// orders of magnitude above every documented Erlang/OTP production
3197/// playbook recommendation (Learn You Some Erlang's
3198/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3199/// `max_restarts: 3` default, OTP's `supervisor` callback module
3200/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3201/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3202/// default) and below the clearly-pathological "effectively no
3203/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3204/// author can plausibly want at hyperscale (a long-running supervisor
3205/// over a very-flaky pool tolerating thousands of transient restarts
3206/// before escalating), but a hard wall above which the typed policy is
3207/// structurally a no-op carried verbatim on every emitted child-restart
3208/// reconciliation contract.
3209///
3210/// Lifted as a typed `pub const` so the bound has exactly one source of
3211/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3212/// materializer's admission webhook and the wasm-operator-side
3213/// per-supervisor restart-intensity reconciler read from one place. Same
3214/// shape every other typed upper bound in this crate carries
3215/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3216/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3217/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3218/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3219/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3220/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3221pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3222
3223/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3224/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3225/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3226/// (inclusive on both ends, integer-millisecond magnitudes by the
3227/// canonical-form gate immediately preceding).
3228///
3229/// The typed field is `Option<Duration>` (the zero-floor arm
3230/// [`SupervisorError::RestartWindowZero`] already rejects
3231/// `Some(Duration::ZERO)`, and the canonical-form arm
3232/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3233/// sub-millisecond residue), so a programmatic struct literal
3234/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3235/// .. }` — 24h) and the equivalent author-surface form
3236/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3237/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3238/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3239/// A `:restart-window` value far above the documented Erlang/OTP
3240/// `MaxIntensity / Period` production-playbook band (Learn You Some
3241/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3242/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3243/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3244/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3245/// degenerates the supervisor's restart-intensity counter into a
3246/// lifetime counter: the rolling failure-counting window is structurally
3247/// so long that transient restarts are never forgotten, so the
3248/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3249/// supervisor when the child has exceeded its restart budget *within
3250/// the recent window*" to "trip the parent when the child has exceeded
3251/// its restart budget *over its lifetime*" — every transient restart
3252/// counts against the budget forever, the supervisor's reset semantic
3253/// never reaches the child, and the typed `:restart-window` slot
3254/// becomes a no-op rolling window carried on every emitted hierarchical
3255/// reconciliation contract. The canonical
3256/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3257/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3258/// `:politicas :circuit-breaker :window` axis with identical shape (both
3259/// are "rolling failure-counting window with a per-`Period` reset" Duration
3260/// axes whose lifetime-counter degenerate at the high end is the same
3261/// "the reset semantic never fires" CSE invariant violation).
3262///
3263/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3264/// the shared duration codec emits (`"<n>h"` for any integer-hour
3265/// magnitude) — every value in the canonical authoring form's
3266/// `<integer><unit>` grammar at or below this cap renders to a clean
3267/// canonical string — and matches the three sibling typed-`Duration`
3268/// caps already lifted to this surface
3269/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3270/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3271/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3272/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3273/// per-supervisor `:supervisor :restart-window` — now share a single
3274/// uniform top edge at the codec's largest emitted unit so the next
3275/// typed-slot wiring (the future wasm-operator's per-supervisor
3276/// `MaxIntensity / Period` reconciler, the M4
3277/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3278/// webhook, the `caixa-operator`'s hierarchical reconciliation
3279/// scheduler) reaches for any of the four knowing the value is in
3280/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3281/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3282/// Riak Core / RabbitMQ production-playbook recommendation band
3283/// (`5s..=300s`) and below the clearly-pathological "rolling window
3284/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3285/// a value the author can plausibly want for a very-low-traffic
3286/// long-tail failure-restart window over a hyperscale-flaky child pool,
3287/// but a hard wall above which the rolling-window contract is
3288/// structurally a lifetime-counter contract.
3289///
3290/// Lifted as a typed `pub const` so the bound has exactly one source
3291/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3292/// materializer's admission webhook, the wasm-operator-side
3293/// per-supervisor `MaxIntensity / Period` reconciler, and the
3294/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3295/// from one place. Same shape every other typed upper bound in this
3296/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3297/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3298/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3299/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3300/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3301/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3302/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3303/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3304/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3305pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3306
3307/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3308/// default for the `:supervisor :restart-window` axis — the canonical
3309/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3310/// worker-supervisor default, extracted as a typed `pub const` so every
3311/// substrate-side consumer that resolves "what
3312/// [`SupervisorSpec::restart_window`] value does an author-omitted
3313/// `:restart-window` slot degrade onto?" reaches for exactly one
3314/// substrate-primitive [`Duration`].
3315///
3316/// The `:restart-window` default axis has one production consumer on the
3317/// substrate side today: the [`Default for SupervisorSpec`] impl's
3318/// struct-literal `restart_window` field, which prior to this lift folded
3319/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3320/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3321/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3322/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3323/// *not* fall back to this default on the sibling `:restart-window` axis
3324/// — an author-omitted `:supervisor :restart-window` composes to
3325/// `restart_window: None` (the shared codec's soft-swallow shape),
3326/// keeping author-declared intent ("no reset — never escalate on rolling
3327/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3328/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3329/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3330/// default was split across two files with no compile-time link between
3331/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3332/// `MaxIntensity` half at the substrate primitive while the `Period`
3333/// half rode as an open-coded literal at the composition site, so a
3334/// future coherent rebrand of the paired canonical (a tightening to
3335/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3336/// per-cluster overlay the operator pins through a future
3337/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3338/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3339/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3340/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3341/// roadmap lands) would have had to migrate the `MaxIntensity` half
3342/// through the lifted constant and the `Period` half through a raw
3343/// literal in lockstep or the two halves of the same OTP-canonical
3344/// default would silently drift out of pairing. Lifting the resolution
3345/// rule to a typed `pub const` on the substrate primitive means the
3346/// paired OTP-canonical default migrates as one unit on any future
3347/// axis change.
3348///
3349/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3350/// worker-supervisor default (the closest canonical OTP-shape
3351/// production reference the substrate carries, matching the paired
3352/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3353/// constant is the `Period` denominator of on the same
3354/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3355/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3356/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3357/// this lower default; both are typed [`Duration`] const bounds on the
3358/// `:supervisor :restart-window` axis and now share one accessor
3359/// discipline on the substrate) and above the OTP-`supervisor`
3360/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3361/// rolling window" default is deliberately loose enough to absorb a
3362/// short burst of transient child failures without escalating past the
3363/// supervisor's parent while remaining tight enough for the paired
3364/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3365/// stuck child within a human-scale observation window.
3366///
3367/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3368/// exactly one source of truth on each half — the sibling
3369/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3370/// `Period` `60s` half now share the same substrate-primitive lift
3371/// discipline. Same shape every other typed default in this crate
3372/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3373/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3374/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3375/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3376/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3377/// caixa-flux / caixa-helm rendering axes).
3378pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3379
3380/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3381/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3382/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3383/// worker-supervisor default, extracted as a typed `pub const` so every
3384/// substrate-side consumer that resolves "what
3385/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3386/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3387/// primitive [`RestartStrategy`].
3388///
3389/// The `:estrategia` default axis has three production consumers on the
3390/// substrate side today: the [`Default for RestartStrategy`] impl's
3391/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3392/// `estrategia` field, and the
3393/// [`crate::manifest::Caixa::supervisor_view`] fold's
3394/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3395/// collapse arm — three entry points onto the same OTP-canonical
3396/// `one_for_one` value that prior to this lift folded onto a raw
3397/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3398/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3399/// with no compile-time link back to the paired
3400/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3401/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3402/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3403/// triple was split across three altitudes with no compile-time link
3404/// between the halves: the `MaxIntensity` half rode through the lifted
3405/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3406/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3407/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3408/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3409/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3410/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3411/// intensity/period; an OTP `rest_for_one` widening once the substrate
3412/// discovers startup-order-coupled child cohorts as the more common
3413/// worker-supervisor default; a per-cluster overlay the operator pins
3414/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3415/// §III.2 supervision-canary roadmap acknowledges) would have had to
3416/// migrate the `MaxIntensity` + `Period` halves through the lifted
3417/// constants and the `one_for_one` half through an open-coded arm in
3418/// lockstep or the three halves of the same OTP-canonical default would
3419/// silently drift out of pairing. Lifting the resolution rule to a typed
3420/// `pub const` on the substrate primitive means the paired OTP-canonical
3421/// worker-supervisor default migrates as one unit on any future axis
3422/// change.
3423///
3424/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3425/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3426/// closest canonical OTP-shape production reference the substrate
3427/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3428/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3429/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3430/// failed child, leaving siblings untouched — is the default for tree-of-
3431/// independent-workers use cases the substrate's [`RestartStrategy`]
3432/// discriminator's own docstring already carries as the default arm; it
3433/// composes with the `{5, 60}` restart-intensity ratio to name the same
3434/// substrate-canonical "canonical worker-supervisor" shape the paired
3435/// halves close on their respective axes.
3436///
3437/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3438/// exactly one source of truth on each of its three halves — the sibling
3439/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3440/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3441/// this `one_for_one` strategy half now share the same substrate-
3442/// primitive lift discipline. Same shape every other typed default in
3443/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3444/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3445/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3446/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3447/// upper caps on the paired sibling axes, and the peer
3448/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3449/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3450pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3451
3452/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3453/// default for the `:children :restart` axis — the OTP `permanent`
3454/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3455/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3456/// `pub const` so every substrate-side consumer that resolves "what
3457/// [`ChildSpec::restart`] variant does an author-omitted `:children
3458/// :restart` slot degrade onto?" reaches for exactly one substrate-
3459/// primitive [`RestartPolicy`].
3460///
3461/// Completes the OTP-shape supervisor-tree default set at the substrate
3462/// primitive. The per-`:supervisor` axis already carries all three of its
3463/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3464/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3465/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3466/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3467/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3468/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3469/// the M2 `:supervisor` slot family. The split mattered because the two
3470/// axes resolve *together* on every author-omitted supervisor: a
3471/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3472/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3473/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3474/// `permanent` through an open-coded enum arm, so a future coherent
3475/// rebrand of the OTP-shape default set (an Elixir-shaped
3476/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3477/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3478/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3479/// once the substrate discovers clean-completion-aware children as the
3480/// more common child shape) would have had to migrate three halves
3481/// through typed constants and the fourth through a raw enum arm in
3482/// lockstep or the supervisor-level and child-level defaults would
3483/// silently drift apart.
3484///
3485/// The `:children :restart` default axis has two production consumers on
3486/// the substrate side today: the [`Default for RestartPolicy`] impl's
3487/// return arm, and the serde-side `#[serde(default)]` on
3488/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3489/// :restart` slot through that same impl. Both now key off this one
3490/// substrate primitive, so the future wasm-operator's per-child post-exit
3491/// restart-decision branch, the future M4
3492/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3493/// admission webhook, and the `caixa-operator`'s hierarchical
3494/// reconciliation scheduler's per-child fan-out all reach for one typed
3495/// identifier when they resolve an omitted per-child restart posture.
3496///
3497/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3498/// worker-child restart type — always restart the child regardless of how
3499/// it died, the canonical posture for long-running services that must
3500/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3501/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3502/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3503/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3504/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3505/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3506/// one-shot / clean-completion-aware postures an author declares
3507/// explicitly, never a posture an omitted slot should silently assume.
3508pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3509
3510/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3511/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3512/// `pub const fn` constructor rather than a struct-literal cascade over
3513/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3514/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3515/// lifted consts — one source of truth for the Erlang/OTP-canonical
3516/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3517/// paths every downstream consumer already reaches through (the
3518/// hand-authored-until-now [`Default::default`] the
3519/// `..SupervisorSpec::default()` struct-update-syntax on every
3520/// one-axis-under-test fixture in this crate's test module rests on,
3521/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3522/// every `const`-context consumer reaches through).
3523///
3524/// Extends the [`Default`]-through-const-ctor fold discipline the
3525/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3526/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3527/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3528/// and [`crate::BehaviorSpec`]
3529/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3530/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3531/// typed-slot spec family — extended here onto the M2 supervisor-slot
3532/// [`SupervisorSpec`] whose canonical baseline is not "everything
3533/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3534/// supervisor triple. The `empty()` peer's naming did not fit
3535/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3536/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3537/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3538/// the sibling `Option`-only slots fold to), so this peer is named
3539/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3540/// existing per-arm pin tests
3541/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3542/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3543/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3544/// already reach for. Pinned load-bearing by
3545/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3546/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3547/// [`PartialEq`], sharpening the sibling
3548/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3549/// pins from a per-field lift into a whole-struct one-source-of-truth
3550/// pin — the derived-until-now [`Default::default`] and the
3551/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3552/// construction, not by coincidence).
3553impl Default for SupervisorSpec {
3554    #[inline]
3555    fn default() -> Self {
3556        Self::otp_canonical()
3557    }
3558}
3559
3560impl SupervisorSpec {
3561    /// `const`-context peer of the [`Default for SupervisorSpec`]
3562    /// impl (which routes through this constructor) — returns the
3563    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3564    /// baseline this crate reaches for in every fixture-builder
3565    /// `..SupervisorSpec::default()` struct-update expression and
3566    /// every downstream `SupervisorSpec::default()` seed.
3567    ///
3568    /// Each field routes through the same substrate-canonical
3569    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3570    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3571    /// per-arm pin tests
3572    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3573    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3574    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3575    /// already assert, so a future coherent rebrand of the OTP-canonical
3576    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3577    /// cluster overlay via a future `:restart-window-overrides` slot, a
3578    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3579    /// absorption roadmap acknowledges) migrates through three typed
3580    /// constants in lockstep, and the paired [`Default`] impl inherits
3581    /// every future extension by construction.
3582    ///
3583    /// `pub const fn` rather than the derived-style `Default::default`
3584    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3585    /// [`Default::default`] is not `const` on stable Rust, and
3586    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3587    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3588    /// discipline lets `const`-context callers construct the OTP-
3589    /// canonical baseline at compile time without runtime dispatch on
3590    /// the derived [`Default::default`], the same posture the sibling
3591    /// [`crate::LimitsSpec::empty`] (9739971) /
3592    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3593    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3594    /// spec `pub const fn` constructors carry on the sibling
3595    /// "everything `None`" baseline axis.
3596    ///
3597    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3598    /// of the derived-style [`Default`]" family — sibling of the
3599    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3600    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3601    /// baseline" trio, extended here onto the M2 supervisor-slot
3602    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3603    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3604    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3605    /// than `empty()` to name the actual invariant the return value
3606    /// pins — the same phrasing already used in the per-arm pin tests
3607    /// on this file. Pinned load-bearing by
3608    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3609    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3610    #[must_use]
3611    pub const fn otp_canonical() -> Self {
3612        Self {
3613            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3614            max_restarts: default_max_restarts(),
3615            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3616            children: Vec::new(),
3617        }
3618    }
3619
3620    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3621    /// sibling-restart-strategy scalar accessor every consumer that
3622    /// dispatches on the supervisor's per-sibling restart-decision shape
3623    /// keys off — returns the author-declared `:supervisor :estrategia`
3624    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3625    /// the typed slot's own [`RestartStrategy`] storage.
3626    ///
3627    /// The `:supervisor :estrategia` slot carries the closed-set
3628    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3629    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3630    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3631    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3632    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3633    /// every child started after it, the Erlang/OTP `rest_for_one`
3634    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3635    /// dynamic children of the same shape, the Erlang/OTP
3636    /// `simple_one_for_one` per-session default) that every downstream
3637    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3638    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3639    /// paired coherently with the sibling `:children` axis
3640    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3641    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3642    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3643    /// downstream consumer that reads the strategy keys off this scalar
3644    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3645    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3646    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3647    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3648    /// strategy print line, the future wasm-operator's per-supervisor
3649    /// sibling-restart-strategy branch, the future M4
3650    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3651    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3652    /// reconciliation scheduler's per-strategy fan-out).
3653    ///
3654    /// Prior to this lift the `.estrategia` field was accessed inline at
3655    /// two production sites in `caixa-core/src/supervisor.rs` — the
3656    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3657    /// `match self.estrategia { … }` partition dispatch, and the
3658    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3659    /// carrier at `estrategia: self.estrategia` — two open-coded
3660    /// field-accesses that expressed no compile-time link back to the
3661    /// typed slot. A future extension of the `:supervisor :estrategia`
3662    /// axis to a richer author surface (a per-cluster strategy override
3663    /// the operator pins through a future `:supervisor :estrategia-overrides`
3664    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3665    /// acknowledges, a per-tenant strategy-alias table the M4 CR
3666    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3667    /// derivation the future adaptive-supervision engine computes from
3668    /// child-failure-history topology, a per-child-cohort strategy split
3669    /// the future `RestForCohort` extension acknowledged by the
3670    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3671    /// would have had to be threaded through every open-coded copy in
3672    /// lockstep — one consumer reading the raw variant while a peer read
3673    /// the operator-resolved variant would silently split the
3674    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3675    /// the actual partition-dispatch input the empty-children refusal
3676    /// arm reached under, a two-consumer split at the validator far from
3677    /// the source `caixa.lisp` with no field naming the strategy-drift
3678    /// root cause. Lifting the resolution rule to a typed method on the
3679    /// substrate primitive means every downstream consumer of the
3680    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3681    /// reaches for exactly one typed dispatch — the resolver's accept-set
3682    /// migrates as a unit on any future axis addition.
3683    ///
3684    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3685    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3686    /// per-`:placement` distribution-strategy axis — same "one typed
3687    /// dispatch on the substrate primitive, thin projections at each
3688    /// consumer" discipline extended onto the M2 supervisor-slot
3689    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3690    /// scalar axis. The two typed axes (`Placement::estrategia` on the
3691    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3692    /// Supervisor side) now share one accessor discipline for the shared
3693    /// substrate concept "a `Copy`-projected closed-set enum-arm
3694    /// discriminator that partitions the downstream renderer's per-arm
3695    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3696    /// `SupervisorSpec` type — companion to the sibling per-`:children`
3697    /// [`crate::ChildSpec::nome`] (57c61d0) /
3698    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3699    /// scalar accessors on the sibling per-`:children` `String`-carry
3700    /// axes. Named `estrategia()` to match the storage field's name and
3701    /// the peer [`crate::Placement::estrategia`] method-name discipline
3702    /// verbatim; the accessor's identity name maps onto the canonical
3703    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3704    /// docstring already carries.
3705    ///
3706    /// Declared `pub const fn` to close the M2 supervisor-slot
3707    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3708    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3709    /// (converted in this commit) `Copy`-composite-enum accessor, peer
3710    /// of the sibling M2 per-`:supervisor`
3711    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3712    /// already lifted, and mirror of the peer M3 mesh-slot
3713    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3714    /// `Copy`-return `pub const fn` scalar accessor whose method-name
3715    /// discipline this accessor was authored to match. Every downstream
3716    /// substrate-side `const`-context consumer of the per-`:supervisor`
3717    /// sibling-restart-strategy scalar (a future module-scope `const
3718    /// _:() = assert!(matches!(sup.estrategia(),
3719    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3720    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3721    /// admission-webhook `const fn` per-supervisor strategy-arm floor
3722    /// over a typed [`SupervisorSpec`], any future `const fn`
3723    /// supervisor-tree composer over the substrate primitive that fans
3724    /// on the sibling-restart-strategy at compile time) now reaches
3725    /// through the same typed dispatch on the substrate primitive at
3726    /// const-eval time as at runtime. A future non-`Copy`-return
3727    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3728    /// migration once the substrate grows per-cluster strategy overlays
3729    /// the [`SupervisorSpec`] docstring already anticipates, a
3730    /// per-tenant strategy-alias table the M4 CR materializer resolves
3731    /// per-CR) that would drop the `const` qualifier fails the
3732    /// fail-before-pass-after pin
3733    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3734    /// caixa-core build time rather than surfacing as a downstream
3735    /// consumer regression.
3736    #[must_use]
3737    pub const fn estrategia(&self) -> RestartStrategy {
3738        self.estrategia
3739    }
3740
3741    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3742    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3743    /// reads the supervisor's per-`:restart-window` restart-budget count
3744    /// keys off — returns the author-declared `:supervisor :max-restarts`
3745    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3746    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3747    /// borrow of `&self` past the call). Non-optional (the `u32` field
3748    /// carries the restart-budget count as a required axis with a
3749    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3750    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3751    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3752    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3753    ///
3754    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3755    /// `MaxIntensity` restart-budget count that pairs with the sibling
3756    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3757    /// restart-intensity ratio the supervisor trips its own escalation on
3758    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3759    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3760    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3761    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3762    /// upper-cap bracket at
3763    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3764    /// wasm-operator's per-supervisor restart-intensity counter's
3765    /// budget-vs-count comparator, the future M4
3766    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3767    /// webhook, the `caixa-operator`'s hierarchical reconciliation
3768    /// scheduler's per-supervisor escalation-decision branch, every
3769    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3770    /// offending count verbatim for `feira lint` rendering).
3771    ///
3772    /// Prior to this lift the `.max_restarts` field was accessed inline at
3773    /// one production site in `caixa-core/src/supervisor.rs` — the
3774    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3775    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3776    /// that expressed no compile-time link back to the typed slot. A
3777    /// future extension of the `:max-restarts` axis to a richer author
3778    /// surface (a per-cluster restart-budget override the operator pins
3779    /// through a future `:supervisor :max-restarts-overrides` slot the
3780    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3781    /// a per-tenant restart-budget-alias table the M4 CR materializer
3782    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3783    /// the future adaptive-supervision engine computes from child-failure-
3784    /// history topology, a promotion of the plain `u32` count to a richer
3785    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3786    /// budget-partition slot comes into scope) would have had to be
3787    /// threaded through every open-coded copy in lockstep or the validate
3788    /// gate and the future M4 emit path would silently disagree on which
3789    /// restart-budget count a given supervisor resolves to — an author's
3790    /// `:max-restarts 5` would satisfy validate while the emit path
3791    /// silently read a drifted other value (a `:max-restarts 10000`
3792    /// no-op supervisor at the emit boundary would carry the author's
3793    /// declared `5` verbatim in `feira lint` output while the future
3794    /// wasm-operator's restart-intensity counter operated under the
3795    /// drifted count), a two-consumer split at the validator far from the
3796    /// source `caixa.lisp` with no field naming the restart-budget-drift
3797    /// root cause. Lifting the resolution rule to a typed method on the
3798    /// substrate primitive means every downstream consumer of the
3799    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3800    /// for exactly one typed dispatch — the resolver's accept-set migrates
3801    /// as a unit on any future axis addition.
3802    ///
3803    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3804    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3805    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3806    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3807    /// the substrate primitive, thin projections at each consumer"
3808    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3809    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3810    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3811    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3812    /// one accessor discipline for the shared substrate concept "a
3813    /// `Copy`-projected required `u32` count that trips the next-higher
3814    /// protection layer after N events in a rolling window" — both are
3815    /// counters with identical degenerate-at-the-high-end shape and share
3816    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3817    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3818    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3819    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3820    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3821    /// the storage field's name verbatim and the peer
3822    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3823    /// accessor's identity maps onto the canonical OTP-shape supervision
3824    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3825    /// already carries.
3826    #[must_use]
3827    pub const fn max_restarts(&self) -> u32 {
3828        self.max_restarts
3829    }
3830
3831    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3832    /// `Period` sliding-window scalar accessor every consumer of the
3833    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3834    /// keys off — returns the author-declared `:supervisor :restart-window`
3835    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3836    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3837    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3838    /// value; no borrow of `&self` past the call). `None` when the slot is
3839    /// absent (the canonical "never reset — every restart across the
3840    /// supervisor's lifetime counts against the sibling `:max-restarts`
3841    /// budget" sentinel the field's own docstring names and the peer
3842    /// `validate_accepts_none_restart_window` pin locks in on the
3843    /// [`SupervisorSpec::validate`] entry-side).
3844    ///
3845    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3846    /// `Period` sliding-observation-interval that pairs with the sibling
3847    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3848    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3849    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3850    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3851    /// default). The typed slot's `Option<Duration>` accept-set —
3852    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3853    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3854    /// `Period > 0`; a zero period either trips on the first failure or
3855    /// never trips depending on operator interpretation, neither of which
3856    /// is the author's intent — omit the slot to express "no reset";
3857    /// carry a positive duration to express the sliding window),
3858    /// integer-millisecond canonical form enforced through
3859    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3860    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3861    /// future wasm-operator's per-supervisor restart-intensity counter
3862    /// quantizes at milliseconds), upper-bounded by
3863    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3864    /// supervisor rolling window any operationally-reachable supervisor
3865    /// can honor without spanning multiple scheduler epochs the
3866    /// hierarchical-reconciliation scheduler treats as independent) —
3867    /// maps onto the future wasm-operator (M3) per-supervisor
3868    /// restart-intensity counter's rolling-observation-interval, the
3869    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3870    /// per-`spec.restartWindow` admission webhook, and the sibling
3871    /// `duration_codec`-serialized wire scalar every downstream consumer
3872    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3873    /// keys off.
3874    ///
3875    /// Prior to this lift the `.restart_window` field was accessed inline
3876    /// at one production site in `caixa-core/src/supervisor.rs` — the
3877    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3878    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3879    /// open-coded field-access that expressed no compile-time link back to
3880    /// the typed slot. A future extension of the `:restart-window` axis to
3881    /// a richer author surface (a per-cluster restart-window override the
3882    /// operator pins through a future `:supervisor :restart-window-overrides`
3883    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3884    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3885    /// materializer resolves per-CR, a per-supervisor dynamic
3886    /// restart-window derivation the future adaptive-supervision engine
3887    /// computes from child-failure-history topology, a promotion of the
3888    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3889    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3890    /// partition slot comes into scope) would have had to be threaded
3891    /// through every open-coded copy in lockstep or the validate gate and
3892    /// the future M4 emit path would silently disagree on which
3893    /// restart-window a given supervisor resolves to — an author's
3894    /// `:restart-window "60s"` would satisfy validate while the emit path
3895    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3896    /// authored slot at the emit boundary would carry the author's
3897    /// declared window verbatim in `feira lint` output while the future
3898    /// wasm-operator's restart-intensity counter operated under a
3899    /// drifted window, or vice versa: an author's `:restart-window ()`
3900    /// would carry the "never reset" sentinel through validate while the
3901    /// emit path silently substituted a default sliding window), a
3902    /// two-consumer split at the validator far from the source
3903    /// `caixa.lisp` with no field naming the restart-window-drift root
3904    /// cause. Lifting the resolution rule to a typed method on the
3905    /// substrate primitive means every downstream consumer of the
3906    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3907    /// surface reaches for exactly one typed dispatch — the resolver's
3908    /// accept-set migrates as a unit on any future axis addition.
3909    ///
3910    /// Third `Copy`-return accessor on the M2 supervisor-slot
3911    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3912    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3913    /// payload rather than a `Copy`-scalar, and the per-`:children`
3914    /// [`crate::ChildSpec::nome`] (57c61d0) /
3915    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3916    /// scalar accessors already close the per-element `String`-carry
3917    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3918    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3919    /// per-outermost-call wall-clock-deadline axis and the peer M3
3920    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3921    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3922    /// three share the shared substrate concept "a `Copy`-projected
3923    /// optional `Duration` that carries a positive integer-millisecond
3924    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3925    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3926    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3927    /// bracket-helper the three axes each route through. Named
3928    /// `restart_window()` to match the storage field's name verbatim and
3929    /// the peer [`crate::LimitsSpec::wall_clock`] /
3930    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3931    /// accessor's identity maps onto the canonical OTP-shape supervision
3932    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3933    /// already carries.
3934    #[must_use]
3935    pub const fn restart_window(&self) -> Option<Duration> {
3936        self.restart_window
3937    }
3938
3939    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3940    /// static-child-list slice accessor every consumer that walks the
3941    /// supervisor's declared child set keys off — returns the author-
3942    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3943    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3944    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3945    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3946    /// through). Non-optional: an empty slice is the load-bearing
3947    /// "author declared `:children ()`" sentinel every consumer of the
3948    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3949    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3950    /// three strategies require a non-empty slice — the paired
3951    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3952    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3953    /// partition on both arms).
3954    ///
3955    /// The `:supervisor :children` slot carries the OTP-shaped static
3956    /// child list the supervisor materializes one ComputeUnit per
3957    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3958    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3959    /// through the tatara-lisp `:children` author surface onto a typed
3960    /// `Vec<ChildSpec>` whose per-element `(nome(),
3961    /// versao_requirement(), restart)` triple the per-child
3962    /// [`SupervisorSpec::validate`] loop already gates through the
3963    /// lifted [`ChildSpec::nome`] (57c61d0) /
3964    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3965    /// Every downstream consumer that fans on the static child list
3966    /// keys off this slice (the [`SupervisorSpec::validate`]
3967    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3968    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3969    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3970    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3971    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3972    /// materialization loop, the future M4
3973    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3974    /// admission-webhook fan-out, the future `feira app graph`
3975    /// per-supervisor tree-print traversal).
3976    ///
3977    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3978    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3979    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3980    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3981    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3982    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3983    /// validate loop's `for child in &self.children` traversal head —
3984    /// three open-coded field-accesses that expressed no compile-time
3985    /// link back to the typed slot. A future extension of the
3986    /// `:supervisor :children` axis to a richer author surface (a
3987    /// per-cluster child-set overlay the operator pins through a future
3988    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3989    /// supervision-canary roadmap acknowledges, a per-tenant
3990    /// child-set-alias table the M4 CR materializer resolves per-CR,
3991    /// a per-supervisor dynamic-child derivation the future adaptive-
3992    /// supervision engine computes from child-failure-history topology,
3993    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3994    /// `{static, dynamic}` partition once Erlang/OTP's
3995    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3996    /// would have had to be threaded through all three open-coded copies
3997    /// in lockstep or one consumer would silently disagree with the
3998    /// peers on which child-set a given supervisor resolves to — the
3999    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
4000    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
4001    /// would silently split the partition-dispatch's two-arm coherence
4002    /// (a supervisor that satisfies neither arm's precondition, or that
4003    /// satisfies both, at the cost of the paired
4004    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
4005    /// silently drifting from the per-child validate loop's actual
4006    /// traversal input), a three-consumer split at the validator far
4007    /// from the source `caixa.lisp` with no field naming the
4008    /// child-set-drift root cause. Lifting the resolution rule to a
4009    /// typed method on the substrate primitive means every downstream
4010    /// consumer of the Supervisor's per-`:supervisor` static-child-list
4011    /// surface reaches for exactly one typed dispatch — the resolver's
4012    /// accept-set migrates as a unit on any future axis addition.
4013    ///
4014    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4015    /// — the seed for the same "one typed dispatch on the substrate
4016    /// primitive, thin projections at each consumer" discipline the
4017    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
4018    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
4019    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
4020    /// onto the first `Vec`-carry axis on the substrate. The four peer
4021    /// `Vec`-carry axes still unlifted at the time of this seed —
4022    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
4023    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
4024    /// (`Vec<Membro>` per-Aplicacao member list),
4025    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
4026    /// per-Aplicacao WIT-typed edge list),
4027    /// [`crate::UpgradeFromEntry::instructions`]
4028    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4029    /// — inherit this accessor's discipline as future compounding runs
4030    /// migrate their consumers onto the shared slice-return shape.
4031    /// Fourth (and final) accessor on the M2 supervisor-slot
4032    /// `SupervisorSpec` type, sibling to the three `Copy`-return
4033    /// [`SupervisorSpec::estrategia`] (eafb619) /
4034    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
4035    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
4036    /// the last unlifted per-`:supervisor` field axis (the
4037    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
4038    /// per-`:supervisor` reader now routes through a typed dispatch on
4039    /// the substrate primitive. Named `children()` to match the storage
4040    /// field's name verbatim and the tatara-lisp author-surface term
4041    /// (`:children`) the field's own docstring already carries; the
4042    /// accessor's identity maps onto the canonical OTP-shape
4043    /// supervision vocabulary the [`SupervisorSpec::children`] field's
4044    /// docstring already reaches for ("Static children ..."). Returns
4045    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
4046    /// consumer of the child list treats it as a read-only sequence —
4047    /// the slice-view is the narrowest borrow that supports every
4048    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
4049    /// index, `.len()`) without leaking the backing `Vec`'s
4050    /// grow/push/reserve surface that no consumer of the typed view
4051    /// reaches for (the storage-side `Vec` remains reachable through
4052    /// the `pub children` field for the mutation-carrying
4053    /// `Caixa::supervisor_view` fold-in path in
4054    /// `manifest.rs:supervisor_view`).
4055    #[must_use]
4056    pub const fn children(&self) -> &[ChildSpec] {
4057        self.children.as_slice()
4058    }
4059
4060    /// Validate the supervisor's typed shape — strategy ↔ children
4061    /// invariants, max_restarts > 0, restart_window > 0 when set,
4062    /// per-child non-empty + duplicate-free names.
4063    ///
4064    /// Mirrors the value-shape discipline applied to every other
4065    /// typed slot:
4066    ///
4067    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
4068    ///     same "0 means the opposite of what you think" footgun
4069    ///     closed for `:politicas :timeout` (Envoy interprets a zero
4070    ///     timeout as `infinite`), `:politicas :circuit-breaker
4071    ///     :window`, and `:limits :wall-clock`. The
4072    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
4073    ///     `supervisor` requires `Period > 0`; a zero period either
4074    ///     trips on the first failure or never trips depending on
4075    ///     operator interpretation, neither of which is the
4076    ///     author's intent. Omit `:restart-window` to express "no
4077    ///     reset"; carry a positive duration to express the window.
4078    ///   - duplicate `:children` `:caixa` names are the same
4079    ///     graph-node-set / multiset distinction closed for
4080    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
4081    ///     and `:entrada :paths` (eb3456d). Two children with the
4082    ///     same `:caixa` materialize as two ComputeUnits with the
4083    ///     same name in the cluster's HelmRelease values, one
4084    ///     silently overwriting the other. Erlang/OTP's
4085    ///     `child_spec.id` is required-unique per supervisor;
4086    ///     pleme-io enforces the same set-not-multiset shape on
4087    ///     `:caixa` (the load-bearing identity in our renderer).
4088    pub fn validate(&self) -> Result<(), SupervisorError> {
4089        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
4090        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4091        // error carrier's `estrategia:` field through the lifted
4092        // [`SupervisorSpec::estrategia`] accessor rather than the raw
4093        // `self.estrategia` field access — the two production consumers
4094        // of the per-`:supervisor` sibling-restart-strategy scalar now
4095        // key off exactly one typed dispatch on the substrate primitive,
4096        // so any future rebrand on the axis (a per-cluster strategy
4097        // override the operator pins through a future `:supervisor
4098        // :estrategia-overrides` slot, a per-tenant strategy-alias table
4099        // the M4 CR materializer resolves per-CR) migrates as a single
4100        // caixa-core edit rather than a coordinated rewrite of the two
4101        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4102        // (921fe1b) four-consumer migration on the per-`:placement`
4103        // distribution-strategy axis.
4104        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4105        // dispatch's paired `.is_empty()` cross-slot refusal probes
4106        // (the `SimpleOneForOne`-arm
4107        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4108        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4109        // refusal) through the lifted [`SupervisorSpec::children`]
4110        // slice-return accessor rather than the raw `self.children`
4111        // field access — the two paired production consumers of the
4112        // per-`:supervisor` static-child-list scalar-shape now key off
4113        // exactly one typed dispatch on the substrate primitive, so any
4114        // future rebrand on the axis (a per-cluster child-set overlay
4115        // the operator pins through a future `:supervisor
4116        // :children-overrides` slot, a per-tenant child-set-alias table
4117        // the M4 CR materializer resolves per-CR) migrates as a single
4118        // caixa-core edit rather than a coordinated rewrite of the
4119        // paired arms — first slice-return migration on any typed slot,
4120        // seed for the peer per-`:placement :clusters`,
4121        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4122        // :instructions` `Vec`-carry axes.
4123        match self.estrategia() {
4124            RestartStrategy::SimpleOneForOne => {
4125                // SimpleOneForOne: children added at runtime. Static
4126                // list must be empty (one shape declared elsewhere).
4127                if !self.children().is_empty() {
4128                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4129                }
4130            }
4131            _ => {
4132                if self.children().is_empty() {
4133                    return Err(SupervisorError::no_children(self.estrategia()));
4134                }
4135            }
4136        }
4137        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4138        // axis. See [`crate::render::require_positive_bounded_u32`] for
4139        // the ordering discipline (zero-floor arm strictly precedes cap
4140        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4141        // diagnostic with its counter-axis remediation directly named,
4142        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4143        // cap-arm miss). Until this bracket landed the top edge ran all
4144        // the way to `u32::MAX` and a struct-literal
4145        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4146        // equivalent author-surface `:max-restarts 100000` /
4147        // `:max-restarts 4294967295` typo landing in the slot) silently
4148        // passed validate. The runtime substrate consuming the value
4149        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4150        // wasm-operator's per-supervisor restart-intensity counter, the
4151        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4152        // admission webhook) then turned a typed `:max-restarts`
4153        // policy into a no-op supervisor: the escalation threshold is
4154        // structurally so high that no realistic
4155        // restarts-per-`:restart-window` traffic shape can reach it,
4156        // the supervisor never escalates to its parent, and a bad
4157        // child can loop inside the window indefinitely with the
4158        // parent supervisor structurally never receiving the "this
4159        // subtree has exceeded its restart budget" signal the typed
4160        // slot is meant to express. The bracket set is
4161        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4162        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4163        // the sibling `:politicas :circuit-breaker :max-failures` axis:
4164        // both are "trip the next-higher protection layer after N
4165        // events in a rolling window" counters with identical
4166        // degenerate-at-the-high-end shape and now share one canonical
4167        // bracket helper. The bracket precedes the sibling
4168        // `:restart-window` zero-floor / canonical-millisecond arms so
4169        // an over-cap `max_restarts` paired with a structurally invalid
4170        // window surfaces the bracket diagnostic first, mirroring the
4171        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4172        // ordering on the peer `:politicas :circuit-breaker` slot.
4173        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4174        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4175        // accessor rather than the raw `self.max_restarts` field access —
4176        // the one production consumer of the per-`:supervisor`
4177        // restart-budget-count scalar now keys off exactly one typed
4178        // dispatch on the substrate primitive, so any future rebrand on
4179        // the axis (a per-cluster restart-budget override the operator
4180        // pins through a future `:supervisor :max-restarts-overrides`
4181        // slot, a per-tenant restart-budget-alias table the M4 CR
4182        // materializer resolves per-CR) migrates as a single caixa-core
4183        // edit rather than a coordinated rewrite — sibling of the peer M3
4184        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4185        // the per-`:politicas :circuit-breaker :max-failures` axis.
4186        crate::render::require_positive_bounded_u32(
4187            self.max_restarts(),
4188            SUPERVISOR_MAX_RESTARTS_MAX,
4189            || SupervisorError::ZeroMaxRestarts,
4190            SupervisorError::max_restarts_exceeds_cap,
4191        )?;
4192        // Route the [`SupervisorSpec::validate`] `:restart-window`
4193        // zero-floor + integer-millisecond canonical-form + upper-cap
4194        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4195        // accessor rather than the raw `self.restart_window` field access —
4196        // the one production consumer of the per-`:supervisor`
4197        // restart-intensity-denominator scalar now keys off exactly one
4198        // typed dispatch on the substrate primitive, so any future rebrand
4199        // on the axis (a per-cluster restart-window override the operator
4200        // pins through a future `:supervisor :restart-window-overrides`
4201        // slot, a per-tenant restart-window-alias table the M4 CR
4202        // materializer resolves per-CR) migrates as a single caixa-core
4203        // edit rather than a coordinated rewrite — sibling of the peer M2
4204        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4205        // on the per-`:limits :wall-clock` axis and the peer M3
4206        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4207        // per-`:politicas :timeout` axis.
4208        if let Some(w) = self.restart_window() {
4209            // Zero-floor + integer-millisecond canonical-form +
4210            // upper-cap bracket on the typed `:restart-window` axis.
4211            // See
4212            // [`crate::render::require_positive_canonical_bounded_duration`]
4213            // for the full three-arm ordering discipline (zero-floor
4214            // strictly precedes canonical-form so `Duration::ZERO`
4215            // surfaces the self-locating `RestartWindowZero`
4216            // diagnostic; canonical-form strictly precedes the cap arm
4217            // so a sub-millisecond above-cap value surfaces the more
4218            // fundamental round-trip-shape diagnostic first) and the
4219            // three peer typed-`Duration` sites that share this
4220            // canonical bracket ([`crate::MeshPolicy::timeout`],
4221            // [`crate::CircuitBreaker::window`],
4222            // [`crate::LimitsSpec::wall_clock`]). Every validated
4223            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4224            // (1ms..=1h), integer-millisecond granularity.
4225            crate::render::require_positive_canonical_bounded_duration(
4226                w,
4227                SUPERVISOR_RESTART_WINDOW_MAX,
4228                || SupervisorError::RestartWindowZero,
4229                SupervisorError::restart_window_not_canonical,
4230                SupervisorError::restart_window_exceeds_cap,
4231            )?;
4232        }
4233        // Route the per-child DNS-1123 / semver-requirement / duplicate-
4234        // detection fan-out loop through the lifted named per-slot gate
4235        // [`SupervisorSpec::validate_children`] rather than an inline
4236        // three-per-child cascade — every future consumer that wants to
4237        // re-check only the `:children` slot's per-entry axes (the M4
4238        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4239        // admission webhook re-validating one added/renamed child, the
4240        // future wasm-operator's per-child dynamic-add re-validator on
4241        // the `SimpleOneForOne` runtime-add path once dynamic-children
4242        // graduate to a typed slot, a future partial re-validator on a
4243        // per-`:children`-entry patch) reaches every per-entry axis
4244        // through one dispatch rather than re-inlining the three-arm
4245        // cascade in lockstep with `validate` or paying the peer
4246        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4247        // reach one entry check. Sibling of the peer M3 mesh-slot
4248        // per-slot gate family (`validate_membros` — the exact peer on
4249        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4250        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4251        // `validate_placement`; `validate_politicas` routing through
4252        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4253        // per-slot gate discipline now spans both the M3 mesh-slot
4254        // family and the M2 `:children` per-child-cascade axis on one
4255        // shape: one named per-slot gate per typed per-entry loop.
4256        self.validate_children()?;
4257        Ok(())
4258    }
4259
4260    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4261    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4262    /// gate, and duplicate-`:caixa` dedup arm into one call every
4263    /// consumer that wants to re-validate one `:children` entry (or the
4264    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4265    /// admits reaches through.
4266    ///
4267    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4268    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4269    /// three-per-entry shape (DNS-1123 name + semver-requirement +
4270    /// duplicate-`:caixa` dedup), lifted to one named substrate
4271    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4272    /// materializer's admission webhook re-checking one added or renamed
4273    /// child, the future wasm-operator's per-child dynamic-add
4274    /// re-validator on the `SimpleOneForOne` runtime-add path once
4275    /// dynamic-children graduate to a typed slot, a future partial
4276    /// re-validator on a per-`:children`-entry patch — each reaches the
4277    /// three per-entry axes through this one dispatch rather than
4278    /// re-inlining the three-arm cascade in lockstep with `validate`
4279    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4280    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4281    /// reach one entry check.
4282    ///
4283    /// Self-contained on `&self` — resolves its own dedup `HashSet`
4284    /// through [`SupervisorSpec::children`] rather than borrowing one
4285    /// threaded down from `validate`, the same posture the peer M3
4286    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4287    /// [`crate::AplicacaoSpec::validate_contratos`],
4288    /// [`crate::AplicacaoSpec::validate_entrada`],
4289    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4290    /// consumer that reaches this gate directly (without first calling
4291    /// `validate`) still runs the full per-child cascade — pinned by
4292    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4293    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4294    /// + `validate_children_is_self_contained_on_children_slot`.
4295    ///
4296    /// The three per-entry arms run in the same canonical order the
4297    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4298    /// the diagnostic every author-declared per-`:children` entry surfaces
4299    /// through `validate` is byte-equal to the diagnostic this gate
4300    /// surfaces when called directly — the equivalence-pin pair
4301    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4302    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4303    /// asserts the two altitudes discriminate the same set on every
4304    /// per-entry-covered input.
4305    pub fn validate_children(&self) -> Result<(), SupervisorError> {
4306        let mut seen = std::collections::HashSet::new();
4307        for child in self.children() {
4308            // Every emitted cluster artifact's `metadata.name` for a
4309            // supervised child derives from this `:children :caixa` value
4310            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4311            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4312            // label value on every child's pod identity, and the per-
4313            // child K8s [`Service`][svc] `metadata.name` the future
4314            // wasm-operator (M3) provisions for inter-child supervision
4315            // tree wiring. Each apiserver-side schema on each landing
4316            // site enforces the DNS-1123 label rule on admission; a
4317            // structurally invalid child name (`"Worker"`, `"my_worker"`,
4318            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4319            // UUID-shaped mistaken-identity slug) silently passes the
4320            // prior empty-/duplicate-only gate and the failure surfaces
4321            // at `kubectl apply` time as a `metadata.name: Invalid value`
4322            // rejection, far from the source caixa.lisp, with no field
4323            // naming the offending `:children` entry. Lifting the gate
4324            // to caixa-build time mirrors the `:membros :caixa` value-
4325            // shape trajectory (3f9d7a0) and the `:placement :clusters`
4326            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4327            // identifier axis — the supervisor tree's child names —
4328            // through the lifted
4329            // [`crate::render::require_valid_dns_1123_label`] gate the
4330            // seven peer name axes (`:membros :caixa`, `:placement
4331            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4332            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4333            // route through, so drift between the eight axes' accepted
4334            // DNS-1123-label sets is structurally impossible.
4335            //
4336            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4337            crate::render::require_valid_dns_1123_label(
4338                child.nome(),
4339                || SupervisorError::EmptyChildName,
4340                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4341            )?;
4342            // The author surface for `:children :versao` is the same
4343            // Cargo-shaped semver requirement string `:deps :versao` and
4344            // `:membros :versao` carry — and the lacre pipeline resolves
4345            // all three axes through the same
4346            // [`crate::version::parse_requirement`] entry-point. The
4347            // shared [`crate::render::require_valid_versao_requirement`]
4348            // helper brackets the empty-first + parse cascade both peer
4349            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4350            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4351            // :versao`) route through, so drift between the three axes'
4352            // accepted requirement sets is structurally impossible and
4353            // the parse-side no-op the empty-first arm closes (semver's
4354            // empty parse yields an implicit `*`) lives in exactly one
4355            // predicate. Every `ChildSpec::versao` past validate is
4356            // round-trippable through [`crate::parse_requirement`]
4357            // without re-checking at the resolver layer, and the three
4358            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4359            // are now structurally equivalent by construction.
4360            crate::render::require_valid_versao_requirement(
4361                child.versao_requirement(),
4362                || SupervisorError::empty_child_version(child.nome()),
4363                |reason| {
4364                    SupervisorError::child_versao_invalid(
4365                        child.nome(),
4366                        child.versao_requirement(),
4367                        reason,
4368                    )
4369                },
4370            )?;
4371            crate::render::insert_first_seen(&mut seen, child.nome(), || {
4372                SupervisorError::duplicate_child_caixa(child.nome())
4373            })?;
4374        }
4375        Ok(())
4376    }
4377}
4378
4379/// Cross-slot coherence gate on the supervision tree: no
4380/// `:children :caixa` entry may name the supervisor's own `:nome`.
4381///
4382/// A supervisor that lists itself as a child is a degenerate self-parent
4383/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4384/// specs reference *distinct* child processes; a supervisor is never its
4385/// own child), and the wasm-operator's hierarchical reconciliation would
4386/// otherwise be handed a node that is its own parent: a one-node cycle it
4387/// either rejects far from the source `caixa.lisp` or recurses on. Because
4388/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4389/// lacre closure root), a child whose `:caixa` equals the supervisor's
4390/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4391///
4392/// Lives outside [`SupervisorSpec::validate`] because the typed view
4393/// carries the children but not the parent `:nome`; mirrors the
4394/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4395/// (which likewise reads one slot against another at the
4396/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4397/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4398/// node to itself is structurally not a tree/mesh edge" discipline, here
4399/// on the supervision-tree axis.
4400pub fn validate_no_self_supervision(
4401    children: &[ChildSpec],
4402    parent_nome: &str,
4403) -> Result<(), SupervisorError> {
4404    for child in children {
4405        if child.nome() == parent_nome {
4406            return Err(SupervisorError::child_supervises_self(parent_nome));
4407        }
4408    }
4409    Ok(())
4410}
4411
4412#[derive(Debug, Error, PartialEq, Eq)]
4413pub enum SupervisorError {
4414    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4415    NoChildren { estrategia: RestartStrategy },
4416    #[error(
4417        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4418    )]
4419    SimpleOneForOneWithStaticChildren,
4420    #[error(":max-restarts must be > 0")]
4421    ZeroMaxRestarts,
4422    #[error(
4423        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4424         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4425         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4426         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4427         can reach it, so the supervisor never escalates to its parent and a bad child can \
4428         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4429         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4430         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4431         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4432         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4433         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4434         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4435         band) or restructure the supervision tree (split the flaky child into its own \
4436         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4437    )]
4438    MaxRestartsExceedsCap { max_restarts: u32 },
4439    #[error(
4440        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4441         requires Period > 0; a zero window either trips on the first failure or \
4442         never trips depending on operator interpretation. Omit :restart-window to \
4443         express `never reset`; carry a positive duration to express the window."
4444    )]
4445    RestartWindowZero,
4446    #[error(
4447        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4448         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4449         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4450         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4451         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4452    )]
4453    RestartWindowNotCanonical { window: Duration },
4454    #[error(
4455        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4456         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4457         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4458         failure-counting window is structurally so long that transient restarts are never \
4459         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4460         when the child has exceeded its restart budget within the recent window` to `trip the \
4461         parent when the child has exceeded its restart budget over its lifetime`, and the \
4462         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4463         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4464         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4465         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4466         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4467         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4468         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4469         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4470         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4471         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4472         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4473         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4474         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4475         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4476         hiding it behind a rolling-window declaration the cap arm rejects)"
4477    )]
4478    RestartWindowExceedsCap { window: Duration },
4479    #[error("child entry has empty :caixa name")]
4480    EmptyChildName,
4481    #[error(
4482        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4483         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4484         name / label value the child name lands in — the per-child \
4485         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4486         label value, and the future wasm-operator per-child Service `metadata.name` \
4487         — each apiserver-side schema rejects names that don't match; use a \
4488         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4489    )]
4490    ChildCaixaInvalid { caixa: String, reason: String },
4491    #[error("child {caixa:?} has empty :versao constraint")]
4492    EmptyChildVersion { caixa: String },
4493    #[error(
4494        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4495         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4496         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4497         `:membros :versao` carry; the lacre pipeline resolves all three \
4498         through the same parser)"
4499    )]
4500    ChildVersaoInvalid {
4501        caixa: String,
4502        versao: String,
4503        reason: String,
4504    },
4505    #[error(
4506        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4507         child_spec.id per supervisor; duplicate children materialize as duplicate \
4508         ComputeUnits in the rendered chart, one silently overwriting the other)"
4509    )]
4510    DuplicateChildCaixa { caixa: String },
4511    #[error(
4512        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4513         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4514         OTP child specs reference distinct child processes). Since every :nome is a \
4515         globally-unique substrate identity, a child naming the supervisor's own :nome \
4516         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4517         self-referential :children entry or rename it to the actual child caixa."
4518    )]
4519    ChildSupervisesSelf { caixa: String },
4520}
4521
4522// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4523// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4524// and [`validate_no_self_supervision`] onto one substrate primitive per
4525// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4526// `LayoutError`-envelope constructor families the peer
4527// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4528// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4529// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4530// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4531// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4532// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4533// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4534// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4535// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4536// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4537// variants on `{ de, para }`) already at that discipline on the peer
4538// `AplicacaoError` envelopes.
4539//
4540// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4541// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4542// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4543// self-supervision arm) opened the identical
4544// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4545// the exact "same block re-inlined at every consumer" shape the PRIME
4546// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4547// `AplicacaoError` families each closed on their sibling envelopes. The
4548// three variants share one `{ caixa: String }` shape, so the fold routes
4549// each wire-up site through one dispatch per typed variant.
4550//
4551// The macro below generates one static constructor per variant of shape
4552// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4553// collapses onto one dispatch:
4554// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4555// struct-literal on the same `&str` fixture. The uniform one-field
4556// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4557// macro — rather than at every wire-up site. Every constructor is
4558// `#[must_use]` so a caller who mistakenly discards the constructed error
4559// trips a compile warning at the wire-up site.
4560//
4561// Every future consumer that wants to construct one of these three
4562// variants outside `SupervisorSpec::validate_children` /
4563// `validate_no_self_supervision` — a deferred
4564// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4565// webhook re-checking one added/renamed child, a future
4566// `feira validate --supervisor` per-caixa admission verb, a per-child
4567// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4568// once dynamic-children graduate to a typed slot, a per-Supervisor
4569// overlay resolver rejecting a duplicate/self-supervising child against
4570// a cluster-local snapshot — now reaches each variant through one call
4571// rather than re-inlining the three-line struct-literal in lockstep
4572// with the three in-crate wire-up sites.
4573macro_rules! supervisor_caixa_only_ctors {
4574    ($($ctor:ident => $variant:ident),* $(,)?) => {
4575        impl SupervisorError {
4576            $(
4577                #[doc = concat!(
4578                    "Construct a [`SupervisorError::",
4579                    stringify!($variant),
4580                    "`] naming the offending `:children :caixa` (or ",
4581                    "supervisor `:nome`, on the self-supervision arm). ",
4582                    "Folds the uniform `Self::",
4583                    stringify!($variant),
4584                    " { caixa: caixa.to_string() }` one-field ",
4585                    "struct-literal onto one substrate primitive so ",
4586                    "every [`SupervisorSpec::validate_children`] / ",
4587                    "[`validate_no_self_supervision`] wire-up on this ",
4588                    "variant reads through one dispatch rather than the ",
4589                    "pre-lift open-coded struct-literal block."
4590                )]
4591                #[must_use]
4592                pub fn $ctor(caixa: &str) -> Self {
4593                    Self::$variant { caixa: caixa.to_string() }
4594                }
4595            )*
4596        }
4597    };
4598}
4599
4600supervisor_caixa_only_ctors! {
4601    empty_child_version => EmptyChildVersion,
4602    duplicate_child_caixa => DuplicateChildCaixa,
4603    child_supervises_self => ChildSupervisesSelf,
4604}
4605
4606// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4607// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4608// one substrate primitive per typed variant — the M2 supervisor-side siblings
4609// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4610// already lifted through the sibling
4611// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4612// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4613// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4614// String }` two-slot shape the peer seven-variant
4615// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4616// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4617// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4618// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4619// variant carries the `{ caixa: String, versao: String, reason: String }`
4620// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4621// carries on the same `:versao` value-shape.
4622//
4623// Each of the two wire-up sites opened the same closure-shaped
4624// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4625// [versao: child.versao_requirement().to_string(),] reason }` block inside
4626// the paired [`crate::render::require_valid_dns_1123_label`] and
4627// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4628// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4629// as a bug, on the same altitude the peer `AplicacaoError` /
4630// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4631// families already closed on their sibling envelopes.
4632//
4633// The two `#[must_use]` inherent constructors below fold each wire-up onto
4634// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4635// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4636// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4637// The uniform per-field `.to_string()` / `.into()` construction is spelled
4638// once — inside each ctor body — rather than at every wire-up site. The
4639// `reason: impl Into<String>` bound accepts both `&str` literals and
4640// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4641// diagnostic shape at the lift, matching the peer
4642// [`aplicacao_field_reason_ctors!`] and
4643// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4644// sibling envelopes.
4645//
4646// Every future consumer that wants to construct one of these two variants
4647// outside `SupervisorSpec::validate_children` — a deferred
4648// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4649// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4650// `feira validate --supervisor` per-caixa admission verb, a per-child
4651// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4652// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4653// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4654// cluster-local snapshot — now reaches each variant through one call rather
4655// than re-inlining the per-shape struct-literal block in lockstep with the
4656// two in-crate wire-up sites.
4657impl SupervisorError {
4658    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4659    /// offending `:children :caixa` value under the given `reason`. Folds
4660    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4661    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4662    /// primitive so every wire-up on this variant reads through one
4663    /// dispatch, matching the peer
4664    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4665    /// sibling `AplicacaoError { caixa: String, reason: String }`
4666    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4667    /// outputs through the `impl Into<String>` bound.
4668    #[must_use]
4669    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4670        Self::ChildCaixaInvalid {
4671            caixa: caixa.to_string(),
4672            reason: reason.into(),
4673        }
4674    }
4675
4676    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4677    /// offending `:children :caixa` and its `:versao` requirement under
4678    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4679    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4680    /// reason.into() }` three-slot struct-literal onto one substrate
4681    /// primitive so every wire-up on this variant reads through one
4682    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4683    /// { caixa, versao, reason }` three-slot axis on the peer
4684    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4685    /// and `format!(…)` outputs through the `impl Into<String>` bound.
4686    #[must_use]
4687    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4688        Self::ChildVersaoInvalid {
4689            caixa: caixa.to_string(),
4690            versao: versao.to_string(),
4691            reason: reason.into(),
4692        }
4693    }
4694}
4695
4696// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4697// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4698// three bracket-arms — one struct-literal at the `:children`-empty
4699// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4700// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4701// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4702// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4703// [`crate::render::require_positive_canonical_bounded_duration`]
4704// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4705// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4706// primitive per typed variant, matching the sibling
4707// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4708// variants on the same `{ <field>: Duration | u32 }` shape) at that
4709// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4710// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4711// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4712// wire-up site through one dispatch per typed variant without a runtime-
4713// work delta.
4714//
4715// Each of the four wire-up sites opened the identical
4716// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4717// exact "same block re-inlined at every consumer" shape the PRIME
4718// DIRECTIVE names as a bug, on the same altitude the peer
4719// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4720// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4721// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4722// the fold routes each wire-up site through one dispatch per typed
4723// variant.
4724//
4725// The macro below generates one static constructor per variant of shape
4726// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4727// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4728// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4729// fixture — as a direct call at the [`SupervisorSpec::validate`]
4730// `:children`-empty refusal, or as a bare function pointer in the
4731// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4732// [`crate::render::require_positive_bounded_u32`] /
4733// [`crate::render::require_positive_canonical_bounded_duration`] gate
4734// carries — rather than the pre-lift open-coded one-line closure over
4735// the same one-field struct-literal. `const fn` preserves the `Copy`-
4736// pass-through's zero-runtime-work property verbatim. Every constructor
4737// is `#[must_use]` so a caller who mistakenly discards the constructed
4738// error trips a compile warning at the wire-up site.
4739//
4740// Every future consumer that wants to construct one of these four
4741// variants outside `SupervisorSpec::validate` — a deferred
4742// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4743// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4744// `:restart-window` slot against the cap + canonical-form cascade, a
4745// future `feira validate --supervisor` per-caixa admission verb re-
4746// running the shape gates on demand, a per-Supervisor overlay resolver
4747// rejecting an author-supplied slot against a cluster-local snapshot —
4748// now reaches each variant through one call rather than re-inlining the
4749// per-shape struct-literal block in lockstep with the four in-crate
4750// wire-up sites.
4751macro_rules! supervisor_scalar_ctors {
4752    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4753        impl SupervisorError {
4754            $(
4755                #[doc = concat!(
4756                    "Construct a [`SupervisorError::",
4757                    stringify!($variant),
4758                    "`] naming the offending per-`:supervisor` `",
4759                    stringify!($field),
4760                    "` scalar. Folds the uniform `Self::",
4761                    stringify!($variant),
4762                    " { ",
4763                    stringify!($field),
4764                    " }` one-field `Copy`-pass-through struct-literal onto ",
4765                    "one substrate primitive so every per-axis wire-up on ",
4766                    "this variant reads through one dispatch — as a direct ",
4767                    "call (`SupervisorError::",
4768                    stringify!($ctor),
4769                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4770                    "the same `Copy`-`",
4771                    stringify!($ty),
4772                    "` fixture) or as a bare function pointer in the ",
4773                    "`impl FnOnce(",
4774                    stringify!($ty),
4775                    ") -> SupervisorError` bracket-closure slot every ",
4776                    "`crate::render::require_positive_bounded_*` / ",
4777                    "`crate::render::require_positive_canonical_bounded_*` ",
4778                    "gate carries — rather than the pre-lift open-coded ",
4779                    "one-line closure over the same one-field struct-",
4780                    "literal. `const fn` preserves the `Copy`-pass-through's ",
4781                    "zero-runtime-work property verbatim."
4782                )]
4783                #[must_use]
4784                pub const fn $ctor($field: $ty) -> Self {
4785                    Self::$variant { $field }
4786                }
4787            )*
4788        }
4789    };
4790}
4791
4792supervisor_scalar_ctors! {
4793    no_children => NoChildren { estrategia: RestartStrategy },
4794    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4795    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4796    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4797}
4798
4799/// Shared duration string codec for the typed slots that take a
4800/// duration (`restart_window`, `MeshPolicy::timeout`,
4801/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4802/// reuse it without duplicating the parser.
4803pub mod duration_codec {
4804    use super::Duration;
4805    use serde::{Deserializer, Serializer};
4806
4807    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4808        // Route through the canonical [`crate::render::serialize_option_via_str`]
4809        // — the substrate-side single-owner primitive for the forward
4810        // arm of the typed-magnitude codec family. See its docstring
4811        // for the full sibling roster.
4812        crate::render::serialize_option_via_str(v, s, render)
4813    }
4814
4815    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4816        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4817        // — the substrate-side single-owner primitive for the reverse
4818        // arm of the typed-magnitude codec family. See its docstring
4819        // for the full sibling roster.
4820        crate::render::deserialize_option_via_str(d, parse)
4821    }
4822
4823    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4824        // Paired whitespace-rejection arm — same canonical-form
4825        // render-determinism discipline as the peer
4826        // `limits::parse_byte_size` / `limits::parse_duration` /
4827        // `limits::parse_millicores` /
4828        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4829        // byte-scan closes the WhatWG-conformant whitespace bytes
4830        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4831        // `char::is_whitespace` scan closes the strictly-complementary
4832        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4833        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4834        // codepoints) that `str::trim` at parse entry silently strips.
4835        // Either drift class would round-trip through `render` to a
4836        // *different* canonical form on next emit — breaking the
4837        // THEORY.md Part V render-determinism contract on three typed-
4838        // duration slots at once (`:supervisor :restart-window`,
4839        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4840        // via the shared codec.
4841        //
4842        // Routed through the lifted [`crate::render::reject_whitespace`]
4843        // primitive — the substrate-side single-owner paired-arm gate
4844        // every typed-magnitude codec in caixa-core shares.
4845        crate::render::reject_whitespace::<String, _, _>(
4846            s,
4847            |b| {
4848                format!(
4849                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4850                 authoring form for the typed duration slots routed through this shared codec \
4851                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4852                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4853                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4854                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4855                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4856                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4857                 Part V render-determinism contract every typed slot carries. Strip every \
4858                 whitespace byte (write `\"30s\"` verbatim)"
4859                )
4860            },
4861            |ch| {
4862                format!(
4863                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4864                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4865                 duration slots routed through this shared codec (`:supervisor \
4866                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4867                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4868                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4869                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4870                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4871                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4872                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4873                 strips it at parse entry, and the value round-trips through `render` to \
4874                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4875                 the THEORY.md Part V render-determinism contract every typed slot \
4876                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4877                 verbatim with only ASCII bytes)",
4878                    cp = ch as u32
4879                )
4880            },
4881        )?;
4882        let s = s.trim();
4883        // Routed through the lifted
4884        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4885        // the single-owner split every ASCII-alphabetic-unit typed-
4886        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4887        // `limits::parse_duration` / this shared duration codec) shares.
4888        // See its docstring for the full sibling roster on the same
4889        // primitive altitude.
4890        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4891        let num_trim = num_part.trim();
4892        // The canonical authoring form for every typed slot routed
4893        // through this shared codec — `:supervisor :restart-window`,
4894        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4895        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4896        // non-negative integer with no decimal point and no leading
4897        // sign, so the parser's accepted set must match for
4898        // serialize/deserialize to round-trip without canonical-form
4899        // drift. Until this gate landed the parser accepted any
4900        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4901        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4902        // tripped the value to a *different* canonical string on the
4903        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4904        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4905        // — breaking the THEORY.md Part V render-determinism contract
4906        // on three typed slots at once. Same canonical-form discipline
4907        // `crate::limits::parse_duration` (818dd38, the immediate
4908        // predecessor on the peer `:limits :wall-clock` codec) applies;
4909        // this gate lifts the discipline onto the shared codec that
4910        // backs the remaining three typed-duration slots in caixa-core.
4911        //
4912        // Strict canonical form: every byte of the magnitude is an
4913        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4914        // inputs the gate distinguishes "non-canonical-but-numeric"
4915        // (parses as f64 or i64 — surfaced with a self-locating
4916        // diagnostic naming the canonical authoring form, the
4917        // round-trip drift each rejected shape would produce on first
4918        // serialize, and the canonical-form remediation) from
4919        // "garbage" (parses as neither — surfaced with the existing
4920        // narrower "bad duration magnitude" wording so its diagnostic
4921        // shape remains stable for the parser-shape footgun case).
4922        // The pre-existing `num < 0.0` arm is now unreachable — the
4923        // digit-only gate strictly precedes magnitude parsing, and a
4924        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4925        // non-canonical-but-numeric branch with the `-30` named
4926        // verbatim in the diagnostic rather than the prior
4927        // value-laundered "negative duration in \"-30s\"" wording.
4928        //
4929        // Routed through the lifted
4930        // [`crate::render::is_digit_only_magnitude`] predicate — the
4931        // same source of truth the four peer typed-magnitude codec
4932        // sites share.
4933        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4934        if !digit_only {
4935            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4936            if numeric {
4937                return Err(format!(
4938                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4939                     canonical authoring form for the typed duration slots routed through \
4940                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4941                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4942                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4943                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4944                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4945                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4946                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4947                     THEORY.md Part V render-determinism contract every typed slot carries. \
4948                     Pick an integer magnitude in the unit that divides cleanly (write \
4949                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4950                ));
4951            }
4952            return Err(format!("bad duration magnitude in {s:?}"));
4953        }
4954        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4955        // zero arm (4f46830) on the same canonical-form render-
4956        // determinism axis. The digit-only gate accepts `"030s"`,
4957        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4958        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4959        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4960        // *different* canonical string on the next emit, breaking the
4961        // THEORY.md Part V render-determinism contract the same way
4962        // `"+30s"` did before the leading-`+` arm landed. The single-
4963        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4964        // losslessly through `render` (`render(Duration::ZERO)` emits
4965        // `"0s"`) — the downstream semantic-zero gates (e.g.
4966        // `SupervisorError::ZeroRestartWindow` on
4967        // `:supervisor :restart-window`,
4968        // `AplicacaoError::PolicyTimeoutZero` /
4969        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4970        // duration slots) refuse zero-magnitude authoring at the typed-
4971        // validate layer above, so the single-byte `"0"` stays in the
4972        // accepted set at this codec layer and the diagnostic
4973        // partitioning between canonical-form drift (this arm) and
4974        // semantic-zero (the downstream gates) remains stable.
4975        // Peer with the future leading-zero arms on the two remaining
4976        // typed-magnitude codecs the trajectory acknowledges:
4977        // `limits::parse_duration` backing `:limits :wall-clock`,
4978        // `limits::parse_byte_size` backing `:limits :memory` — each
4979        // carries the same canonical-form-drift class today; this
4980        // gate lands the discipline on the shared duration codec
4981        // first because the `rate_limit_codec` predecessor on the
4982        // same canonical-form-drift axis is the closest peer on the
4983        // trajectory.
4984        //
4985        // Routed through the lifted
4986        // [`crate::render::is_leading_zero_padded_magnitude`]
4987        // predicate — the same source of truth the four peer
4988        // typed-magnitude codec sites share.
4989        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4990            return Err(format!(
4991                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4992                 canonical authoring form for the typed duration slots routed through \
4993                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4994                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4995                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4996                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4997                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4998                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4999                 serialize — breaking the THEORY.md Part V render-determinism contract \
5000                 every typed slot carries. Strip the leading zeros (write \
5001                 `\"30s\"` instead of `\"030s\"`)"
5002            ));
5003        }
5004        // The digit-only gate guarantees every byte is `[0-9]`, and
5005        // the leading-zero arm above guarantees the magnitude is
5006        // either the single byte `"0"` or starts with `[1-9]`, so
5007        // the only way `u64::from_str` can fail here is overflow (the
5008        // magnitude exceeds `u64::MAX`). Surface that with an
5009        // overflow-shaped wording so the diagnostic names the offending
5010        // magnitude verbatim rather than collapsing onto the
5011        // non-canonical arm. The codec now operates on `u64` end-to-end
5012        // — every accepted magnitude is integer-exact; no f64 mantissa
5013        // drift between author-supplied magnitude and the consumer's
5014        // `Duration` value. Same shape `crate::limits::parse_duration`
5015        // (818dd38) carries on the peer `:limits :wall-clock` axis.
5016        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
5017            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
5018        })?;
5019        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
5020        // unit-arm dispatch through the canonical
5021        // [`crate::render::duration_from_integer_magnitude_and_unit`]
5022        // primitive — the substrate-side single-owner unit-dispatch
5023        // table every typed-duration codec in caixa-core routes
5024        // through (peer: `crate::limits::parse_duration` backing
5025        // `:limits :wall-clock`). Every unit conversion is integer-
5026        // exact for an integer magnitude; overflow surfaces via the
5027        // typed `DurationUnitError::Overflow { multiplier }`
5028        // discriminant so this arm reconstructs the pre-lift
5029        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
5030        // wording verbatim from `num` / `unit_trim` / the returned
5031        // `multiplier`, and the unknown-unit arm reconstructs the
5032        // pre-lift `"unknown duration unit \"<other>\""` wording from
5033        // the caller-scoped `unit_trim`. Load-bearing pinned by
5034        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
5035        let unit_trim = unit.trim();
5036        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
5037            |e| match e {
5038                crate::render::DurationUnitError::Overflow { multiplier } => format!(
5039                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
5040                ),
5041                crate::render::DurationUnitError::UnknownUnit => {
5042                    format!("unknown duration unit {unit_trim:?}")
5043                }
5044            },
5045        )?;
5046        Ok(dur)
5047    }
5048
5049    /// Render a [`Duration`] in the canonical pleme-io duration string
5050    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
5051    /// caixa typed-duration slot serializes to and the same form K8s
5052    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
5053    /// EnvoyConfig per-route timeouts both expect (an integer
5054    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
5055    /// `+`). Lifted to `pub` so caixa-side renderers
5056    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
5057    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
5058    /// emitter, the future caixa-otel collector pipeline emitter) can
5059    /// consume the same canonical formatter without re-inlining the
5060    /// magnitude/unit decision tree (and inheriting the same drift
5061    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
5062    /// downstream apply-time parsing in non-obvious ways).
5063    pub fn render(d: Duration) -> String {
5064        let total_ms = d.as_millis();
5065        if total_ms == 0 {
5066            return "0s".into();
5067        }
5068        if total_ms.is_multiple_of(3600 * 1000) {
5069            return format!("{}h", total_ms / (3600 * 1000));
5070        }
5071        if total_ms.is_multiple_of(60 * 1000) {
5072            return format!("{}m", total_ms / (60 * 1000));
5073        }
5074        if total_ms.is_multiple_of(1000) {
5075            return format!("{}s", total_ms / 1000);
5076        }
5077        format!("{total_ms}ms")
5078    }
5079
5080    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
5081    ///
5082    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
5083    /// largest divisor unit, so any sub-millisecond residue
5084    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
5085    /// §V.2.7 render-determinism contract:
5086    ///
5087    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
5088    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
5089    ///     `1_000_000` ns ≠ original `1_500_000` ns;
5090    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
5091    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
5092    ///     on every typed-`Duration` slot then rejects on re-validate.
5093    ///
5094    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
5095    /// the codec's round-trippable accepted set lives in exactly one place —
5096    /// every typed-`Duration` slot that routes through this shared codec
5097    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
5098    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
5099    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
5100    /// every typed-`Duration` slot whose own codec shares the same
5101    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5102    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5103    /// pair) calls this predicate from its `validate()` to bracket the
5104    /// accepted set against the codec's accepted set, structurally. Drift
5105    /// between the codec's granularity and any typed slot's accepted set is
5106    /// then a single-source-of-truth edit at this predicate rather than a
5107    /// silent round-trip break the next consumer discovers at apply time.
5108    ///
5109    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5110    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5111    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5112    /// family — same "typed-slot's valid set matches its codec's accepted
5113    /// set, structurally" discipline carried at the codec layer.
5114    #[must_use]
5115    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5116        d.subsec_nanos().is_multiple_of(1_000_000)
5117    }
5118}
5119
5120/// Required-Duration variant for fields that aren't Option<Duration>.
5121pub mod duration_codec_required {
5122    use super::Duration;
5123    use serde::{Deserialize, Deserializer, Serializer};
5124
5125    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5126        s.serialize_str(&super::duration_codec::render(*v))
5127    }
5128
5129    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5130        let s = String::deserialize(d)?;
5131        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5132    }
5133}
5134
5135#[cfg(test)]
5136mod tests {
5137    use super::*;
5138
5139    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5140        ChildSpec {
5141            caixa: name.into(),
5142            versao: ver.into(),
5143            restart,
5144        }
5145    }
5146
5147    #[test]
5148    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5149        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5150        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5151        // posture. Each accessor projects the per-`:children :caixa`
5152        // / per-`:children :versao` [`String`] storage through the
5153        // `pub const fn` [`String::as_str`] (const-stable since Rust
5154        // 1.87, well within the workspace MSRV) — any future
5155        // accidental downgrade to non-`const` fails the corresponding
5156        // `<name>_via_const_fn` wrapper at caixa-core build time with
5157        // E0015 (`cannot call non-const method`), strictly stronger
5158        // than a runtime `assert!`. Sibling of the peer
5159        // per-M2/M3/universal-axis `String → &str` scalar-accessor
5160        // family pins on the sibling `const`-eval-surface passes
5161        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5162        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5163        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5164        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5165        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5166        // [`crate::aplicacao::Entrada::destination`] at the M3
5167        // ingress axis,
5168        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5169        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5170        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5171        // axis, and the per-`:contratos`
5172        // [`crate::aplicacao::WitContract::source`] /
5173        // [`crate::aplicacao::WitContract::destination`] /
5174        // [`crate::aplicacao::WitContract::world_ref`] trio the
5175        // sibling pin at 279823b already anchors).
5176        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5177            c.nome()
5178        }
5179        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5180            c.versao_requirement()
5181        }
5182        for (caixa, versao) in [
5183            ("worker-a", "^0.1"),
5184            ("worker-b", "~0.2.3"),
5185            ("collector", "*"),
5186        ] {
5187            let c = child(caixa, versao, RestartPolicy::Permanent);
5188            assert_eq!(nome_via_const_fn(&c), c.nome());
5189            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5190            assert_eq!(c.nome(), caixa);
5191            assert_eq!(c.versao_requirement(), versao);
5192        }
5193    }
5194
5195    #[test]
5196    fn supervisor_children_slice_return_accessor_is_const_fn() {
5197        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5198        // `const`-eval-surface posture. The accessor destructures the
5199        // per-`:children` `Vec<ChildSpec>` storage through the
5200        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5201        // 1.66, well within the workspace MSRV) — any future
5202        // accidental downgrade to non-`const` fails
5203        // `children_via_const_fn` at caixa-core build time with E0015
5204        // (`cannot call non-const method`), strictly stronger than a
5205        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5206        // `Vec → &[T]` slice-return accessor family pin
5207        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5208        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5209        // per-`:membros` / per-`:contratos` slice-return axes, and of
5210        // the peer M2 upgrade-appup axis pin
5211        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5212        // on the per-`:upgrade-from :instructions` slice-return axis.
5213        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5214            s.children()
5215        }
5216        // Sweep both the empty-children (leaf-supervisor with no
5217        // static children — the `SimpleOneForOne` dynamic-child
5218        // arm's canonical shape) and the populated-children
5219        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5220        // arm's canonical shape) axes so the accessor carries a
5221        // const-dispatch pin on both arms.
5222        let s_empty = SupervisorSpec {
5223            estrategia: RestartStrategy::SimpleOneForOne,
5224            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5225            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5226            children: vec![],
5227        };
5228        assert!(children_via_const_fn(&s_empty).is_empty());
5229        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5230        let s_full = SupervisorSpec {
5231            estrategia: RestartStrategy::OneForOne,
5232            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5233            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5234            children: vec![
5235                child("worker-a", "^0.1", RestartPolicy::Permanent),
5236                child("worker-b", "~0.2.3", RestartPolicy::Transient),
5237                child("collector", "*", RestartPolicy::Temporary),
5238            ],
5239        };
5240        assert_eq!(children_via_const_fn(&s_full).len(), 3);
5241        assert_eq!(children_via_const_fn(&s_full), s_full.children());
5242    }
5243
5244    #[test]
5245    fn default_has_one_for_one_and_5_restarts_in_60s() {
5246        let s = SupervisorSpec::default();
5247        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5248        assert_eq!(s.max_restarts, 5);
5249        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5250        assert!(s.children.is_empty());
5251    }
5252
5253    #[test]
5254    fn validate_one_for_one_requires_children() {
5255        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5256        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5257        // struct-update to name the axis under test at construction, and this shape matches
5258        // it. Also keeps the "empty children is the axis under test" intent visible at the
5259        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5260        let mut s = SupervisorSpec {
5261            children: vec![],
5262            ..SupervisorSpec::default()
5263        };
5264        assert!(matches!(
5265            s.validate().unwrap_err(),
5266            SupervisorError::NoChildren { .. }
5267        ));
5268        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5269        s.validate().unwrap();
5270    }
5271
5272    #[test]
5273    fn validate_simple_one_for_one_forbids_static_children() {
5274        let mut s = SupervisorSpec {
5275            estrategia: RestartStrategy::SimpleOneForOne,
5276            ..SupervisorSpec::default()
5277        };
5278        s.children
5279            .push(child("w", "^0.1", RestartPolicy::Permanent));
5280        assert_eq!(
5281            s.validate().unwrap_err(),
5282            SupervisorError::SimpleOneForOneWithStaticChildren
5283        );
5284        s.children.clear();
5285        s.validate().unwrap();
5286    }
5287
5288    #[test]
5289    fn validate_rejects_zero_max_restarts() {
5290        let s = SupervisorSpec {
5291            max_restarts: 0,
5292            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5293            ..SupervisorSpec::default()
5294        };
5295        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5296    }
5297
5298    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5299    //
5300    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5301    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5302    // `:supervisor :max-restarts` axis — both fields are "trip the
5303    // next-higher protection layer after N events in a rolling window"
5304    // counters with identical degenerate-at-the-high-end shape, so the
5305    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5306    // exactly as it lies in `1..=1000` on the breaker side.
5307
5308    #[test]
5309    fn validate_rejects_max_restarts_above_cap() {
5310        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5311        // 1` is structurally one past the cap and silently passed
5312        // validate on every pre-gate codebase because the typed slot's
5313        // only check was the zero-floor arm. The no-op-supervisor vector
5314        // only surfaced at the runtime substrate (Erlang/OTP
5315        // MaxIntensity/Period ratio, the future wasm-operator's
5316        // per-supervisor restart-intensity counter) far from the source
5317        // caixa.lisp with no field naming the offending supervisor.
5318        let s = SupervisorSpec {
5319            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5320            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5321            ..SupervisorSpec::default()
5322        };
5323        assert_eq!(
5324            s.validate().unwrap_err(),
5325            SupervisorError::MaxRestartsExceedsCap {
5326                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5327            }
5328        );
5329    }
5330
5331    #[test]
5332    fn validate_rejects_max_restarts_far_above_cap() {
5333        // The `u32::MAX` worst case — the four-billion-restart
5334        // threshold a typo (`:max-restarts 4294967295`) or a
5335        // struct-literal copy-paste lands in the slot. Pin the cap
5336        // arm's coverage explicitly across the full `u32` overflow so
5337        // a future relaxation that drops the upper bound surfaces
5338        // here. Same shape every other typed-cap arm on this surface
5339        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5340        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5341        let s = SupervisorSpec {
5342            max_restarts: u32::MAX,
5343            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5344            ..SupervisorSpec::default()
5345        };
5346        assert_eq!(
5347            s.validate().unwrap_err(),
5348            SupervisorError::MaxRestartsExceedsCap {
5349                max_restarts: u32::MAX,
5350            }
5351        );
5352    }
5353
5354    #[test]
5355    fn validate_accepts_max_restarts_at_cap() {
5356        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5357        // must validate. The cap is inclusive on the top edge,
5358        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5359        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5360        // discipline on the sibling capped axes. Pin the boundary
5361        // explicitly so a future off-by-one tightening
5362        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5363        // here as a test failure rather than a silent contract
5364        // narrowing.
5365        let s = SupervisorSpec {
5366            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5367            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5368            ..SupervisorSpec::default()
5369        };
5370        s.validate()
5371            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5372    }
5373
5374    #[test]
5375    fn validate_accepts_max_restarts_typical_values() {
5376        // The documented production-playbook band positive-control
5377        // sweep — every value Erlang/OTP / Elixir / Riak Core /
5378        // RabbitMQ recommend (1..=100) must pass, plus a sweep
5379        // through the hyperscale band (200, 500, 1000) the cap
5380        // accepts. Pin the inclusive validated set explicitly so a
5381        // future tightening of the ceiling surfaces here.
5382        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5383            let s = SupervisorSpec {
5384                max_restarts: n,
5385                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5386                ..SupervisorSpec::default()
5387            };
5388            s.validate()
5389                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5390        }
5391    }
5392
5393    #[test]
5394    fn zero_max_restarts_takes_precedence_over_cap() {
5395        // The cross-arm ordering pin: `0` is structurally outside
5396        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5397        // (cap), but the zero-floor diagnostic is the more
5398        // self-locating one (it directly names the counter-axis
5399        // remediation), so the validate gate must fire on zero first.
5400        // Same shape every other zero-then-shape ordering on this
5401        // surface uses (PolicyRetriesZero then
5402        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5403        // PolicyBreakerMaxFailuresExceedsCap).
5404        let s = SupervisorSpec {
5405            max_restarts: 0,
5406            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5407            ..SupervisorSpec::default()
5408        };
5409        assert_eq!(
5410            s.validate().unwrap_err(),
5411            SupervisorError::ZeroMaxRestarts,
5412            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5413        );
5414    }
5415
5416    #[test]
5417    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5418        // The cross-arm ordering pin between the cap and the sibling
5419        // `:restart-window` gates (zero-window, canonical-window). A
5420        // supervisor carrying both an over-cap `max_restarts` AND a
5421        // structurally invalid window (zero, sub-ms) must surface the
5422        // cap diagnostic first — the cap arm is wired immediately
5423        // after the zero-restart arm and strictly before the window
5424        // arms, so the offending value the diagnostic names matches
5425        // the order the author would discover the gates by reading
5426        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5427        // order so a future refactor that reorders the arms surfaces
5428        // here as a test failure rather than a silent diagnostic
5429        // regression. Peer of
5430        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5431        // on the sibling `:politicas :circuit-breaker` slot.
5432        let s = SupervisorSpec {
5433            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5434            restart_window: Some(Duration::ZERO),
5435            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5436            ..SupervisorSpec::default()
5437        };
5438        assert_eq!(
5439            s.validate().unwrap_err(),
5440            SupervisorError::MaxRestartsExceedsCap {
5441                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5442            },
5443            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5444        );
5445    }
5446
5447    #[test]
5448    fn max_restarts_cap_diagnostic_carries_offending_value() {
5449        // The diagnostic-shape pin: the offending `u32` is carried
5450        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5451        // variant so the surfaced error message names the value the
5452        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5453        // supervisor-policy ceiling …"`), not just the cap. Same
5454        // self-locating diagnostic shape every other typed-cap arm on
5455        // this surface carries
5456        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5457        // the offending failure count verbatim,
5458        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5459        // retries count verbatim).
5460        let s = SupervisorSpec {
5461            max_restarts: 50_000,
5462            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5463            ..SupervisorSpec::default()
5464        };
5465        let err = s.validate().unwrap_err();
5466        assert!(
5467            matches!(
5468                err,
5469                SupervisorError::MaxRestartsExceedsCap {
5470                    max_restarts: 50_000
5471                }
5472            ),
5473            "got {err:?}"
5474        );
5475        let msg = err.to_string();
5476        assert!(
5477            msg.contains("50000"),
5478            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5479        );
5480    }
5481
5482    #[test]
5483    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5484        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5485        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5486        // half of Learn You Some Erlang's worker-supervisor default,
5487        // sibling of the `60s` `Period` half that the paired
5488        // [`Default for SupervisorSpec`] impl already pins on the
5489        // sibling `restart_window` axis. Pinning the literal here
5490        // surfaces a future rebrand (a tightening to Elixir's `3`,
5491        // a widening to a per-cluster overlay the operator pins
5492        // through a future `:max-restarts-overrides` slot) as a
5493        // deliberate test edit, not a silent contract migration.
5494        // Peer of the sibling
5495        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5496        // upper-bracket pin on the same axis.
5497        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5498    }
5499
5500    #[test]
5501    fn default_max_restarts_helper_routes_through_lifted_default() {
5502        // Composition pin: the private `default_max_restarts()`
5503        // serde-`#[serde(default = "…")]` helper on
5504        // [`SupervisorSpec::max_restarts`] must route through the
5505        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5506        // typed `pub const` rather than a raw `5` literal. Prior to
5507        // the lift the helper carried an inline `5` with no compile-
5508        // time link back to the shared default, so the wire-format
5509        // author-omitted arm and the caixa-core
5510        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5511        // arm could silently split on any future default rebrand.
5512        // Byte-parity against the lifted constant closes the split.
5513        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5514    }
5515
5516    #[test]
5517    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5518        // Composition pin: the [`Default for SupervisorSpec`] impl's
5519        // struct-literal `max_restarts` field must route through the
5520        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5521        // typed `pub const` (via the private helper this test's
5522        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5523        // already pins onto the constant). Structurally: every
5524        // `SupervisorSpec::default()` call must yield a
5525        // `max_restarts` field byte-equal to the lifted constant
5526        // (the two paired defaults — the serde-side wire-format arm
5527        // and the struct-literal default arm — cannot silently split
5528        // on any future default rebrand). Peer of the sibling
5529        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5530        // — this pin closes the byte-parity arm on the two paired
5531        // altitude entry points onto the shared substrate constant.
5532        assert_eq!(
5533            SupervisorSpec::default().max_restarts(),
5534            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5535        );
5536    }
5537
5538    #[test]
5539    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5540        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5541        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5542        // Learn You Some Erlang's worker-supervisor default, paired
5543        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5544        // `MaxIntensity` half this constant is the sliding-window
5545        // denominator of on the same `MaxIntensity / Period`
5546        // restart-intensity ratio. Pinning the literal here surfaces a
5547        // future coherent rebrand of the paired default (Elixir's
5548        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5549        // the operator pins through a future
5550        // `:restart-window-overrides` slot) as a deliberate test edit,
5551        // not a silent contract migration. Peer of the sibling
5552        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5553        // paired-half pin on the same OTP-canonical default and the
5554        // [`supervisor_restart_window_cap_pins_canonical_value`]
5555        // upper-bracket pin on the same axis.
5556        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5557    }
5558
5559    #[test]
5560    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5561        // Composition pin: the [`Default for SupervisorSpec`] impl's
5562        // struct-literal `restart_window` field must route through the
5563        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5564        // typed `pub const` rather than a raw
5565        // `Duration::from_secs(60)` literal. Prior to this lift the
5566        // paired `{intensity, 5, 60}` OTP-canonical default was split
5567        // across two altitudes with no compile-time link between the
5568        // halves — the `MaxIntensity` half rode through the lifted
5569        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5570        // `Period` half rode as an open-coded literal at the
5571        // composition site, so a future coherent rebrand of the paired
5572        // canonical would have had to migrate one half through the
5573        // constant and the other through a raw literal in lockstep.
5574        // Byte-parity against the lifted constant on the `Period` half
5575        // closes the split — the paired OTP-canonical default now
5576        // migrates as one unit on any future axis change. Peer of the
5577        // sibling
5578        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5579        // byte-parity pin on the paired `MaxIntensity` half.
5580        assert_eq!(
5581            SupervisorSpec::default().restart_window(),
5582            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5583        );
5584    }
5585
5586    #[test]
5587    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5588        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5589        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5590        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5591        // canonical default, paired with the sibling
5592        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5593        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5594        // this constant is the strategy discriminator of on the same
5595        // OTP-canonical worker-supervisor default. Pinning the arm here
5596        // surfaces a future coherent rebrand of the paired triple (Elixir's
5597        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5598        // intensity/period axes leaving this strategy arm untouched, an OTP
5599        // `rest_for_one` widening once the substrate discovers startup-
5600        // order-coupled child cohorts as the more common worker-supervisor
5601        // shape, a per-cluster overlay the operator pins through a future
5602        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5603        // supervision-canary roadmap acknowledges) as a deliberate test
5604        // edit, not a silent contract migration. Peer of the sibling
5605        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5606        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5607        // paired-half pins on the same OTP-canonical default.
5608        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5609    }
5610
5611    #[test]
5612    fn restart_strategy_default_routes_through_lifted_default() {
5613        // Composition pin: the [`Default for RestartStrategy`] impl's
5614        // return arm must route through the substrate-canonical
5615        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5616        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5617        // an inline `Self::OneForOne` with no compile-time link back to
5618        // the shared OTP-canonical `one_for_one` strategy the paired
5619        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5620        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5621        // `.unwrap_or_default()` (now
5622        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5623        // so a future rebrand of the OTP-canonical strategy default (an
5624        // OTP `rest_for_one` widening once the substrate discovers
5625        // startup-order-coupled child cohorts as the more common worker-
5626        // supervisor shape, a per-cluster overlay the operator pins
5627        // through a future `:estrategia-overrides` slot) would have had to
5628        // be threaded through the `Default` impl and the two peer routes
5629        // in lockstep or the three consumers would silently split. Byte-
5630        // parity against the lifted constant closes the split. Peer of
5631        // the sibling
5632        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5633        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5634        // composition pins on the paired `MaxIntensity` + `Period` halves.
5635        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5636    }
5637
5638    #[test]
5639    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5640        // Composition pin: the [`Default for SupervisorSpec`] impl's
5641        // struct-literal `estrategia` field must route through the
5642        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5643        // `pub const` (either directly, or via the
5644        // [`RestartStrategy::default`] impl that the sibling
5645        // `restart_strategy_default_routes_through_lifted_default` pin
5646        // already routes onto the constant). Structurally: every
5647        // `SupervisorSpec::default()` call must yield an `estrategia`
5648        // field byte-equal to the lifted constant (the three paired
5649        // defaults — the [`Default for RestartStrategy`] impl arm, the
5650        // struct-literal default arm here, and the
5651        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5652        // silently split on any future default rebrand). Peer of the
5653        // sibling
5654        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5655        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5656        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5657        // of the same `SupervisorSpec::default()` composed altitude.
5658        assert_eq!(
5659            SupervisorSpec::default().estrategia(),
5660            SUPERVISOR_ESTRATEGIA_DEFAULT,
5661        );
5662    }
5663
5664    #[test]
5665    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5666        // Composition pin: the [`Default for SupervisorSpec`] impl must
5667        // route through the substrate-canonical
5668        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5669        // rather than a re-hand-authored struct-literal cascade. Sharpens
5670        // the sibling per-arm
5671        // `supervisor_spec_default_*_routes_through_lifted_default` pins
5672        // from a per-field lift into a whole-struct one-source-of-truth
5673        // pin — the derived-until-now [`Default::default`] and the
5674        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5675        // construction, not by coincidence.
5676        //
5677        // A future extension of the OTP-canonical baseline (a fifth
5678        // `restart_intensity` field the Erlang/OTP `#supervisor` record
5679        // grows, a per-child-cohort split of the `restart_window` /
5680        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5681        // CR materializer's admission-time overlay pass) reaches both
5682        // paths through exactly one edit on
5683        // [`SupervisorSpec::otp_canonical`] — the derived path could
5684        // silently disagree with the constructor's shape on any new
5685        // field whose [`Default::default`] resolves to a different arm
5686        // than the OTP-canonical baseline the constructor names, while
5687        // this delegated impl reaches the constructor directly and
5688        // picks up every future extension by construction.
5689        //
5690        // Fourth peer on the M2 / M3 typed-slot-spec
5691        // [`Default`]-through-const-ctor fold family — sibling of the
5692        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5693        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5694        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5695        // (91641a4), and [`crate::BehaviorSpec`]
5696        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5697        // per-`Option`-only-typed-slot folds — extended here onto the
5698        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5699        // is not "everything `None`" but the Erlang/OTP-canonical
5700        // `{one_for_one, 5, 60}` worker-supervisor triple.
5701        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5702    }
5703
5704    #[test]
5705    fn supervisor_spec_otp_canonical_byte_equals_default() {
5706        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5707        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5708        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5709        // pin already asserts against the [`Default::default`] path.
5710        // Sharpens the pair-invariant into a per-constructor pin so a
5711        // future extension of [`SupervisorSpec`] with a fifth field
5712        // whose OTP-canonical shape is non-`Default::default`-equivalent
5713        // trips at caixa-core test time rather than at a downstream
5714        // consumer that composed [`SupervisorSpec::otp_canonical`] with
5715        // [`SupervisorSpec::validate`] as its "canonical baseline
5716        // seed".
5717        let canonical = SupervisorSpec::otp_canonical();
5718        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5719        assert_eq!(canonical.max_restarts, 5);
5720        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5721        assert!(canonical.children.is_empty());
5722    }
5723
5724    #[test]
5725    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5726        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5727        // remain callable from a `const`-bound position so downstream
5728        // `const`-context callers wanting a canonical OTP-baseline seed
5729        // can construct one at compile time without runtime dispatch on
5730        // the derived [`Default::default`]. Peer of the sibling
5731        // `pub const fn` [`crate::LimitsSpec::empty`] /
5732        // [`crate::aplicacao::MeshPolicy::empty`] /
5733        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5734        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5735        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5736        // (a non-`const` field-default helper, a non-`const`-stable
5737        // container type promotion), this evaluation fails at
5738        // build time on this file rather than at a downstream
5739        // `const`-context call site.
5740        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5741        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5742        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5743        assert_eq!(
5744            CANONICAL.restart_window,
5745            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5746        );
5747        assert!(CANONICAL.children.is_empty());
5748    }
5749
5750    #[test]
5751    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5752        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5753        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5754        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5755        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5756        // half of the same OTP-shape supervisor-tree default set whose
5757        // per-`:supervisor` halves the sibling
5758        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5759        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5760        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5761        // arm here surfaces a future rebrand of the per-child default (an
5762        // OTP-`transient` widening once the substrate discovers clean-
5763        // completion-aware children as the more common child shape, a
5764        // per-cluster overlay the operator pins through a future
5765        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5766        // supervision-canary roadmap acknowledges) as a deliberate test
5767        // edit, not a silent contract migration. Peer of the sibling
5768        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5769        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5770        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5771        // value pins on the per-`:supervisor` halves.
5772        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5773    }
5774
5775    #[test]
5776    fn restart_policy_default_routes_through_lifted_default() {
5777        // Composition pin: the [`Default for RestartPolicy`] impl's return
5778        // arm must route through the substrate-canonical
5779        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5780        // than a raw `Self::Permanent` arm. Prior to the lift the impl
5781        // carried an inline `Self::Permanent` with no compile-time link
5782        // back to the OTP-shape supervisor-tree default set whose three
5783        // per-`:supervisor` halves already rode through lifted constants
5784        // — so a future coherent rebrand of the set would have had to
5785        // migrate three halves through typed constants and this fourth
5786        // through a raw enum arm in lockstep or the supervisor-level and
5787        // child-level defaults would silently drift apart. Byte-parity
5788        // against the lifted constant closes the split. Peer of the
5789        // sibling
5790        // [`restart_strategy_default_routes_through_lifted_default`]
5791        // composition pin on the per-`:supervisor` `:estrategia` axis.
5792        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5793    }
5794
5795    #[test]
5796    fn child_spec_serde_default_restart_routes_through_lifted_default() {
5797        // Composition pin: the serde-side `#[serde(default)]` on
5798        // [`ChildSpec::restart`] — the wire-format author-omitted
5799        // `:children :restart` arm — must resolve onto the substrate-
5800        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5801        // (via the [`Default for RestartPolicy`] impl the sibling
5802        // `restart_policy_default_routes_through_lifted_default` pin
5803        // already routes onto the constant). Structurally: a `ChildSpec`
5804        // deserialized from a payload that omits the `restart` key must
5805        // yield a `restart` field byte-equal to the lifted constant, so
5806        // the wire-format author-omitted arm and the
5807        // [`RestartPolicy::default`] impl arm cannot silently split on any
5808        // future default rebrand. Peer of the sibling
5809        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5810        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5811        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5812        // byte-parity pins on the per-`:supervisor` halves of the same
5813        // author-omitted-slot resolution surface.
5814        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5815            .expect("ChildSpec must deserialize with the restart key omitted");
5816        assert_eq!(
5817            omitted.restart(),
5818            SUPERVISOR_CHILD_RESTART_DEFAULT,
5819            "an author-omitted :children :restart slot must degrade onto \
5820             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5821             {:?}, expected {:?})",
5822            omitted.restart(),
5823            SUPERVISOR_CHILD_RESTART_DEFAULT,
5824        );
5825    }
5826
5827    #[test]
5828    fn supervisor_max_restarts_cap_pins_canonical_value() {
5829        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5830        // 1000 — the same ceiling the peer
5831        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5832        // `:politicas :circuit-breaker :max-failures` axis (both are
5833        // "trip the next-higher protection layer after N events in a
5834        // rolling window" counters with identical
5835        // degenerate-at-the-high-end shape; uniform top edge so the
5836        // M4 CR materializers and the wasm-operator reconciler reach
5837        // for either field knowing the value is in `1..=1000`). Two
5838        // orders of magnitude above every documented Erlang/OTP /
5839        // Elixir / Riak Core / RabbitMQ production-playbook
5840        // recommendation band and below the clearly-pathological
5841        // "effectively no escalation" floor (10_000, 100_000,
5842        // u32::MAX). Pinning the literal value here surfaces a future
5843        // drift (a relaxation to 10_000, a tightening to 100) as a
5844        // deliberate test edit, not a silent contract narrowing.
5845        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5846    }
5847
5848    #[test]
5849    fn validate_rejects_empty_child_name() {
5850        let s = SupervisorSpec {
5851            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5852            ..SupervisorSpec::default()
5853        };
5854        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5855    }
5856
5857    #[test]
5858    fn validate_rejects_empty_child_version() {
5859        let s = SupervisorSpec {
5860            children: vec![child("w", "", RestartPolicy::Permanent)],
5861            ..SupervisorSpec::default()
5862        };
5863        assert!(matches!(
5864            s.validate().unwrap_err(),
5865            SupervisorError::EmptyChildVersion { .. }
5866        ));
5867    }
5868
5869    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5870
5871    #[test]
5872    fn validate_rejects_invalid_child_versao_requirement() {
5873        // The fail-before-pass-after pin: a non-empty but malformed
5874        // semver requirement (`"^bad-version"`) silently passed
5875        // `validate()` on every pre-gate codebase because the prior
5876        // shape only refused the empty string. The parse failure
5877        // surfaced far downstream at lacre-resolve time with a
5878        // `semver::Error` that didn't name which `:children` entry
5879        // carried the typo. The new gate moves the check to caixa-build
5880        // time at the source caixa.lisp — the third `:versao` typed
5881        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5882        // structural parity.
5883        let s = SupervisorSpec {
5884            children: vec![
5885                child("worker", "^0.1", RestartPolicy::Permanent),
5886                child("cache", "^bad-version", RestartPolicy::Transient),
5887            ],
5888            ..SupervisorSpec::default()
5889        };
5890        let err = s.validate().unwrap_err();
5891        assert!(
5892            matches!(
5893                err,
5894                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5895                    if caixa == "cache" && versao == "^bad-version"
5896            ),
5897            "got {err:?}"
5898        );
5899    }
5900
5901    #[test]
5902    fn validate_rejects_child_versao_with_double_caret_typo() {
5903        // `"^^0.1"` is the canonical doubled-caret typo — looks
5904        // Cargo-shaped on first glance but fails the parser because
5905        // semver doesn't accept stacked operators. Pin this
5906        // adjacent-shape footgun explicitly so a future relaxation that
5907        // accepts "looks-canonical-but-isn't" forms surfaces here.
5908        let s = SupervisorSpec {
5909            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5910            ..SupervisorSpec::default()
5911        };
5912        let err = s.validate().unwrap_err();
5913        assert!(
5914            matches!(
5915                err,
5916                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5917                    if caixa == "worker" && versao == "^^0.1"
5918            ),
5919            "got {err:?}"
5920        );
5921    }
5922
5923    #[test]
5924    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5925        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5926        // semver requirement slot" typo — an author copies the
5927        // publish-side git-tag string verbatim into `:versao`, but
5928        // Cargo's semver parser rejects the leading `v`. Same
5929        // adjacent-shape footgun pinned for `:membros :versao`
5930        // (9888b13).
5931        let s = SupervisorSpec {
5932            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5933            ..SupervisorSpec::default()
5934        };
5935        let err = s.validate().unwrap_err();
5936        assert!(
5937            matches!(
5938                err,
5939                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5940                    if caixa == "worker" && versao == "v0.1"
5941            ),
5942            "got {err:?}"
5943        );
5944    }
5945
5946    #[test]
5947    fn validate_accepts_canonical_child_versao_forms() {
5948        // The Cargo-shaped requirement forms `:deps :versao` and
5949        // `:membros :versao` already accept via
5950        // `crate::parse_requirement` must pass the children gate
5951        // without re-validating at the resolver layer. Pin every leg so
5952        // a future tightening of the canonical set surfaces here as a
5953        // test failure.
5954        for form in [
5955            "^0.1",      // caret — minor-range pin (the most common shape)
5956            "~0.1.2",    // tilde — patch-range pin
5957            "0.1.0",     // exact — single-version pin
5958            "*",         // wildcard — any version (semver::VersionReq::STAR)
5959            ">=0.1, <2", // multi-range — comma-separated comparators
5960        ] {
5961            let s = SupervisorSpec {
5962                children: vec![child("worker", form, RestartPolicy::Permanent)],
5963                ..SupervisorSpec::default()
5964            };
5965            s.validate()
5966                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5967        }
5968    }
5969
5970    #[test]
5971    fn child_versao_empty_takes_precedence_over_invalid() {
5972        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5973        // doesn't try to parse) fires before the new
5974        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5975        // `:versao` keeps its narrower error message —
5976        // `parse_requirement` would also reject `""`, but the
5977        // empty-string arm is the more self-locating diagnostic for the
5978        // author. Same ordering discipline as
5979        // `membro_versao_empty_takes_precedence_over_invalid` in
5980        // aplicacao.rs.
5981        let s = SupervisorSpec {
5982            children: vec![child("worker", "", RestartPolicy::Permanent)],
5983            ..SupervisorSpec::default()
5984        };
5985        let err = s.validate().unwrap_err();
5986        assert!(
5987            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5988            "got {err:?}"
5989        );
5990    }
5991
5992    #[test]
5993    fn child_versao_invalid_fires_before_duplicate_check() {
5994        // Order pin: a malformed requirement on a non-duplicate entry
5995        // surfaces *its own* diagnostic (which names the offending
5996        // `:versao` string), even when a later entry would otherwise
5997        // collapse onto an earlier name. The per-entry shape gate runs
5998        // inline before the duplicate-key insert — parallel to
5999        // `membro_versao_invalid_fires_before_duplicate_check` in
6000        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
6001        let s = SupervisorSpec {
6002            children: vec![
6003                child("worker", "^bad", RestartPolicy::Permanent),
6004                child("cache", "^0.1", RestartPolicy::Transient),
6005                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6006            ],
6007            ..SupervisorSpec::default()
6008        };
6009        let err = s.validate().unwrap_err();
6010        assert!(
6011            matches!(
6012                err,
6013                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
6014            ),
6015            "got {err:?}"
6016        );
6017    }
6018
6019    #[test]
6020    fn child_versao_invalid_diagnostic_carries_offending_versao() {
6021        // The diagnostic-shape pin: the error names the offending
6022        // `:versao` value verbatim so the author can grep their
6023        // caixa.lisp without re-running the build, and carries a
6024        // non-empty `reason` from `semver::VersionReq::parse` so the
6025        // parser's own wording flows through to the diagnostic.
6026        let s = SupervisorSpec {
6027            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
6028            ..SupervisorSpec::default()
6029        };
6030        let err = s.validate().unwrap_err();
6031        let SupervisorError::ChildVersaoInvalid {
6032            caixa,
6033            versao,
6034            reason,
6035        } = err
6036        else {
6037            panic!("expected ChildVersaoInvalid, got other variant");
6038        };
6039        assert_eq!(caixa, "worker");
6040        assert_eq!(versao, "not-a-req");
6041        assert!(
6042            !reason.is_empty(),
6043            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
6044        );
6045    }
6046
6047    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
6048
6049    #[test]
6050    fn validate_rejects_child_caixa_with_uppercase() {
6051        // The canonical "I copied the Servico's display name verbatim"
6052        // typo — child caixa names are lowercase per K8s DNS-1123 label
6053        // rule. The diagnostic names the offending name and suggests the
6054        // lower-cased fix in one edit, mirroring the
6055        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
6056        let s = SupervisorSpec {
6057            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
6058            ..SupervisorSpec::default()
6059        };
6060        let err = s.validate().unwrap_err();
6061        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6062            panic!("expected ChildCaixaInvalid, got other variant");
6063        };
6064        assert_eq!(caixa, "Worker");
6065        assert!(
6066            reason.contains("uppercase"),
6067            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
6068        );
6069        assert!(
6070            reason.contains("\"worker\""),
6071            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
6072        );
6073    }
6074
6075    #[test]
6076    fn validate_rejects_child_caixa_with_underscore() {
6077        // The canonical "I'm thinking of a Python module / Postgres
6078        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
6079        // label schema. K8s rejects `metadata.name: my_worker` at
6080        // admission time with an opaque `field is invalid` (no source-
6081        // citing diagnostic). The gate moves it to caixa-build time.
6082        let s = SupervisorSpec {
6083            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
6084            ..SupervisorSpec::default()
6085        };
6086        let err = s.validate().unwrap_err();
6087        assert!(
6088            matches!(
6089                err,
6090                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6091                    if caixa == "my_worker" && reason.contains('_')
6092            ),
6093            "got {err:?}"
6094        );
6095    }
6096
6097    #[test]
6098    fn validate_rejects_child_caixa_with_dot() {
6099        // A `:children :caixa` entry is a single DNS-1123 label, not a
6100        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6101        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6102        // (3f9d7a0) on the peer name axis.
6103        let s = SupervisorSpec {
6104            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6105            ..SupervisorSpec::default()
6106        };
6107        let err = s.validate().unwrap_err();
6108        assert!(
6109            matches!(
6110                err,
6111                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6112                    if caixa == "team.worker" && reason.contains('.')
6113            ),
6114            "got {err:?}"
6115        );
6116    }
6117
6118    #[test]
6119    fn validate_rejects_child_caixa_with_leading_hyphen() {
6120        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6121        // with an alphanumeric. The K8s apiserver rejects `-worker`
6122        // outright; the renderer would emit a `metadata.name: "-worker"`
6123        // that fails admission far from the source caixa.lisp.
6124        let s = SupervisorSpec {
6125            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6126            ..SupervisorSpec::default()
6127        };
6128        let err = s.validate().unwrap_err();
6129        assert!(
6130            matches!(
6131                err,
6132                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6133                    if caixa == "-worker" && reason.contains("start and end")
6134            ),
6135            "got {err:?}"
6136        );
6137    }
6138
6139    #[test]
6140    fn validate_rejects_child_caixa_with_trailing_hyphen() {
6141        // The symmetric arm of the boundary rule. Pin separately so
6142        // both ends of the label are covered against a future relaxation
6143        // that only checks one boundary.
6144        let s = SupervisorSpec {
6145            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6146            ..SupervisorSpec::default()
6147        };
6148        let err = s.validate().unwrap_err();
6149        assert!(
6150            matches!(
6151                err,
6152                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6153                    if caixa == "worker-"
6154            ),
6155            "got {err:?}"
6156        );
6157    }
6158
6159    #[test]
6160    fn validate_rejects_child_caixa_with_unicode() {
6161        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6162        // (`xn--…`) by the author before it reaches K8s. The byte-by-
6163        // byte ASCII validity check rejects multi-byte UTF-8 sequences
6164        // by the first byte that fails the `[a-z0-9-]` predicate.
6165        let s = SupervisorSpec {
6166            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6167            ..SupervisorSpec::default()
6168        };
6169        let err = s.validate().unwrap_err();
6170        assert!(
6171            matches!(
6172                err,
6173                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6174                    if caixa == "café"
6175            ),
6176            "got {err:?}"
6177        );
6178    }
6179
6180    #[test]
6181    fn validate_rejects_child_caixa_with_whitespace() {
6182        // Whitespace is the canonical "I pasted from a sketch / doc"
6183        // footgun. The apiserver rejects every `metadata.name` value
6184        // carrying whitespace; pin the gate fires at the right boundary.
6185        let s = SupervisorSpec {
6186            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6187            ..SupervisorSpec::default()
6188        };
6189        let err = s.validate().unwrap_err();
6190        assert!(
6191            matches!(
6192                err,
6193                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6194                    if caixa == "my worker"
6195            ),
6196            "got {err:?}"
6197        );
6198    }
6199
6200    #[test]
6201    fn validate_rejects_child_caixa_too_long() {
6202        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6203        // 63 bytes; the K8s apiserver rejects every `metadata.name`
6204        // axis over the limit at admission time. The diagnostic names
6205        // both the cap and the actual length so the author can shorten
6206        // in one edit, mirroring `rejects_membro_caixa_too_long`
6207        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6208        let too_long = "a".repeat(64);
6209        let s = SupervisorSpec {
6210            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6211            ..SupervisorSpec::default()
6212        };
6213        let err = s.validate().unwrap_err();
6214        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6215            panic!("expected ChildCaixaInvalid, got other variant");
6216        };
6217        assert_eq!(caixa, too_long);
6218        assert!(
6219            reason.contains("63"),
6220            "diagnostic must name the 63-byte cap (got: {reason:?})"
6221        );
6222        assert!(
6223            reason.contains("64"),
6224            "diagnostic must name the actual length (got: {reason:?})"
6225        );
6226    }
6227
6228    #[test]
6229    fn child_caixa_max_length_validates() {
6230        // The 63-byte boundary control pin — exactly-at-the-cap is
6231        // accepted, mirroring `membro_caixa_max_length_validates`
6232        // (3f9d7a0) and `placement_cluster_max_length_validates`
6233        // (6cbb900). Pinned separately so a future off-by-one tightening
6234        // surfaces here.
6235        let max_label = "a".repeat(63);
6236        let s = SupervisorSpec {
6237            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6238            ..SupervisorSpec::default()
6239        };
6240        s.validate().unwrap();
6241    }
6242
6243    #[test]
6244    fn validate_accepts_canonical_child_caixa_forms() {
6245        // The realistic shapes a supervised child's `:caixa` carries —
6246        // single-word `worker`, version-suffixed `cache-v2`, single-char
6247        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6248        // `payment-retry`, all-digit `0`. Pin every leg so a future
6249        // tightening (e.g. requiring a leading lowercase letter) surfaces
6250        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6251        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6252        // (6cbb900).
6253        for form in [
6254            "worker",
6255            "cache-v2",
6256            "a",
6257            "db",
6258            "2-pool",
6259            "payment-retry",
6260            "0",
6261        ] {
6262            let s = SupervisorSpec {
6263                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6264                ..SupervisorSpec::default()
6265            };
6266            s.validate()
6267                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6268        }
6269    }
6270
6271    #[test]
6272    fn child_caixa_empty_takes_precedence_over_invalid() {
6273        // Order pin: the existing `EmptyChildName` diagnostic (which
6274        // doesn't try to parse the DNS-1123 shape) fires before the new
6275        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6276        // its narrower error message — `is_dns_1123_label` would reject
6277        // the empty string too (boundary check on the first byte), but
6278        // the empty-string arm is the more self-locating diagnostic for
6279        // the author. Same ordering discipline as
6280        // `membro_caixa_empty_takes_precedence_over_invalid` in
6281        // aplicacao.rs.
6282        let s = SupervisorSpec {
6283            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6284            ..SupervisorSpec::default()
6285        };
6286        let err = s.validate().unwrap_err();
6287        assert_eq!(err, SupervisorError::EmptyChildName);
6288    }
6289
6290    #[test]
6291    fn child_caixa_invalid_fires_before_versao_check() {
6292        // Order pin: the per-axis shape gate runs inline before the
6293        // per-entry versao check, so a malformed `:caixa` on an entry
6294        // whose `:versao` would also fail surfaces the more self-
6295        // locating name-axis diagnostic first. Parallel to
6296        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6297        // and `placement_cluster_invalid_fires_before_duplicate_check`
6298        // (6cbb900).
6299        let s = SupervisorSpec {
6300            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6301            ..SupervisorSpec::default()
6302        };
6303        let err = s.validate().unwrap_err();
6304        assert!(
6305            matches!(
6306                err,
6307                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6308            ),
6309            "got {err:?}"
6310        );
6311    }
6312
6313    #[test]
6314    fn child_caixa_invalid_fires_before_duplicate_check() {
6315        // Order pin: a malformed name on a non-duplicate entry surfaces
6316        // its own diagnostic, even when a later entry would otherwise
6317        // collapse onto an earlier name. The per-entry shape gate runs
6318        // inline before the duplicate-key HashSet insert, mirroring
6319        // `placement_cluster_invalid_fires_before_duplicate_check`
6320        // (6cbb900).
6321        let s = SupervisorSpec {
6322            children: vec![
6323                child("Worker", "^0.1", RestartPolicy::Permanent),
6324                child("cache", "^0.1", RestartPolicy::Transient),
6325                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6326            ],
6327            ..SupervisorSpec::default()
6328        };
6329        let err = s.validate().unwrap_err();
6330        assert!(
6331            matches!(
6332                err,
6333                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6334            ),
6335            "got {err:?}"
6336        );
6337    }
6338
6339    #[test]
6340    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6341        // The diagnostic-shape pin: the error names the offending
6342        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6343        // the author can grep their caixa.lisp without re-running the
6344        // build. Mirrors the diagnostic-shape sweep on every prior
6345        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6346        let s = SupervisorSpec {
6347            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6348            ..SupervisorSpec::default()
6349        };
6350        let err = s.validate().unwrap_err();
6351        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6352            panic!("expected ChildCaixaInvalid, got other variant");
6353        };
6354        assert_eq!(caixa, "My_Worker");
6355        assert!(
6356            !reason.is_empty(),
6357            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6358        );
6359    }
6360
6361    // ── value-shape: zero restart_window + duplicate child names ──────────
6362
6363    #[test]
6364    fn validate_accepts_none_restart_window() {
6365        // Omitted `:restart-window` is the "never reset" sentinel —
6366        // valid by design. Mirrors :limits axes where None = unbounded.
6367        let s = SupervisorSpec {
6368            restart_window: None,
6369            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6370            ..SupervisorSpec::default()
6371        };
6372        s.validate().unwrap();
6373    }
6374
6375    #[test]
6376    fn validate_rejects_zero_restart_window() {
6377        // Same "0 means the opposite of what you think" footgun closed
6378        // for :politicas :timeout (Envoy treats 0s as infinite) and
6379        // :limits :wall-clock (wasmtime traps before the call starts).
6380        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6381        let s = SupervisorSpec {
6382            restart_window: Some(Duration::ZERO),
6383            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6384            ..SupervisorSpec::default()
6385        };
6386        assert_eq!(
6387            s.validate().unwrap_err(),
6388            SupervisorError::RestartWindowZero
6389        );
6390    }
6391
6392    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6393    //
6394    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6395    // the integer-millisecond canonical-form gate — peer with
6396    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6397    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6398    // path is already gated at the shared codec layer (see
6399    // `restart_window_serde_rejects_fractional_seconds`); this arm
6400    // closes the programmatic-struct-literal path the codec gate can't
6401    // see.
6402
6403    #[test]
6404    fn validate_rejects_sub_millisecond_restart_window() {
6405        // The fail-before-pass-after pin: a programmatic
6406        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6407        // `validate` on every pre-gate codebase, then truncated to
6408        // `as_millis() == 1` on first serialize — the shared codec
6409        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6410        // 1_000_000 ns, the typed `restart_window` no longer matches
6411        // its rendered form.
6412        let s = SupervisorSpec {
6413            restart_window: Some(Duration::from_micros(1500)),
6414            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6415            ..SupervisorSpec::default()
6416        };
6417        match s.validate().unwrap_err() {
6418            SupervisorError::RestartWindowNotCanonical { window } => {
6419                assert_eq!(window, Duration::from_micros(1500));
6420            }
6421            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6422        }
6423    }
6424
6425    #[test]
6426    fn validate_rejects_one_nanosecond_restart_window() {
6427        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6428        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6429        // so the shared codec emits the literal `"0s"` — the next
6430        // serde round-trip would parse back to `Duration::ZERO`, which
6431        // the `RestartWindowZero` arm then rejects on re-validate. The
6432        // canonical-form gate at this layer surfaces a self-locating
6433        // diagnostic naming the offending Duration verbatim rather
6434        // than a downstream `RestartWindowZero` whose remediation
6435        // points at omitting the slot.
6436        let s = SupervisorSpec {
6437            restart_window: Some(Duration::from_nanos(1)),
6438            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6439            ..SupervisorSpec::default()
6440        };
6441        match s.validate().unwrap_err() {
6442            SupervisorError::RestartWindowNotCanonical { window } => {
6443                assert_eq!(window, Duration::from_nanos(1));
6444            }
6445            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6446        }
6447    }
6448
6449    #[test]
6450    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6451        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6452        // 1_000_001 ns is structurally past the integer-ms granularity
6453        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6454        // trip would truncate to `1ms` and the consumer would observe
6455        // a 1-ns drift on every emit. Same boundary the peer
6456        // `validate_rejects_nanosecond_past_canonical_boundary` test
6457        // in limits.rs pins for the `:limits :wall-clock` axis.
6458        let w = Duration::from_nanos(1_000_001);
6459        let s = SupervisorSpec {
6460            restart_window: Some(w),
6461            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6462            ..SupervisorSpec::default()
6463        };
6464        assert_eq!(
6465            s.validate().unwrap_err(),
6466            SupervisorError::RestartWindowNotCanonical { window: w }
6467        );
6468    }
6469
6470    #[test]
6471    fn validate_accepts_integer_millisecond_restart_window_values() {
6472        // The positive-control sweep: every `Duration` the shared
6473        // codec can round-trip losslessly — the canonical
6474        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6475        // pair emits and accepts — passes `validate` without
6476        // surfacing the new canonical-form arm. Mirrors
6477        // `validate_accepts_integer_millisecond_wall_clock_values` on
6478        // the sibling `:limits :wall-clock` axis.
6479        for w in [
6480            Duration::from_millis(1),
6481            Duration::from_millis(500),
6482            Duration::from_millis(1500),
6483            Duration::from_secs(1),
6484            Duration::from_secs(30),
6485            Duration::from_secs(60),
6486            Duration::from_secs(120),
6487            Duration::from_secs(3600),
6488        ] {
6489            let s = SupervisorSpec {
6490                restart_window: Some(w),
6491                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6492                ..SupervisorSpec::default()
6493            };
6494            s.validate()
6495                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6496        }
6497    }
6498
6499    #[test]
6500    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6501        // Cross-arm ordering pin: `Duration::ZERO` has
6502        // `subsec_nanos() == 0` and would otherwise pass the
6503        // canonical-form arm — the zero-floor arm must fire first so
6504        // the more self-locating `RestartWindowZero` diagnostic (with
6505        // its omit-axis remediation directly named) leads. Same
6506        // posture every peer zero-then-shape gate uses
6507        // (`WallClockZero` → `WallClockNotCanonical`,
6508        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6509        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6510        let s = SupervisorSpec {
6511            restart_window: Some(Duration::ZERO),
6512            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6513            ..SupervisorSpec::default()
6514        };
6515        assert_eq!(
6516            s.validate().unwrap_err(),
6517            SupervisorError::RestartWindowZero
6518        );
6519    }
6520
6521    #[test]
6522    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6523        // Diagnostic-shape pin: the canonical-form arm names the
6524        // offending `Duration` verbatim so the author's grep lands on
6525        // the field's value, not a generic "duration not canonical"
6526        // message. Same shape every other typed-canonical-form arm
6527        // on this surface carries (`WallClockNotCanonical` carries
6528        // the offending `Duration` verbatim,
6529        // `PolicyTimeoutNotCanonical` carries the offending
6530        // `Duration` verbatim).
6531        let w = Duration::from_micros(500);
6532        let s = SupervisorSpec {
6533            restart_window: Some(w),
6534            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6535            ..SupervisorSpec::default()
6536        };
6537        let err = s.validate().unwrap_err();
6538        let msg = err.to_string();
6539        assert!(
6540            msg.contains("500"),
6541            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6542        );
6543        assert!(
6544            msg.contains("sub-millisecond"),
6545            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6546        );
6547    }
6548
6549    #[test]
6550    fn restart_window_validated_value_round_trips_through_codec() {
6551        // The structural property the canonical-ms gate enforces:
6552        // every `SupervisorSpec::restart_window` past
6553        // `SupervisorSpec::validate` round-trips losslessly through
6554        // the shared duration codec (serialize → string →
6555        // deserialize → equal value). Pin this end-to-end so a future
6556        // change to either side (the validate gate's accepted
6557        // granularity, the codec's parse/render unit set) that breaks
6558        // the alignment surfaces here. Peer of
6559        // `wall_clock_validated_value_round_trips_through_codec` on
6560        // the sibling `:limits :wall-clock` axis.
6561        for w in [
6562            Duration::from_millis(1),
6563            Duration::from_millis(1500),
6564            Duration::from_secs(30),
6565            Duration::from_secs(3600),
6566        ] {
6567            let s = SupervisorSpec {
6568                restart_window: Some(w),
6569                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6570                ..SupervisorSpec::default()
6571            };
6572            s.validate().unwrap();
6573            let json = serde_json::to_string(&s).unwrap();
6574            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6575            assert_eq!(back.restart_window, Some(w));
6576        }
6577    }
6578
6579    // ── value-shape: upper cap on :restart-window ─────────────────────────
6580    //
6581    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6582    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6583    // `:politicas :timeout` (2e8ee7e), and `:politicas
6584    // :circuit-breaker :window` (379a814). Brackets the typed
6585    // `:restart-window` axis structurally: every validated value lies
6586    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6587    // granularity, closing the
6588    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6589    // zero-floor-and-canonical-form-only checks left open.
6590
6591    #[test]
6592    fn validate_rejects_restart_window_above_cap() {
6593        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6594        // structurally one canonical-tick past the
6595        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6596        // integer-millisecond magnitude the canonical-form arm above
6597        // accepts cleanly, that the shared duration codec round-trips
6598        // losslessly as `"3601s"`, and that silently passed validate on
6599        // every pre-gate codebase because the typed slot's only checks
6600        // were the zero-floor and canonical-form arms. The runtime
6601        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6602        // Period reconciler, the future wasm-operator's per-supervisor
6603        // restart-intensity counter) reaches for a `Duration` so long
6604        // no realistic restart-recovery pattern resets the counter,
6605        // far from the source caixa.lisp.
6606        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6607        let s = SupervisorSpec {
6608            restart_window: Some(w),
6609            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6610            ..SupervisorSpec::default()
6611        };
6612        assert_eq!(
6613            s.validate().unwrap_err(),
6614            SupervisorError::RestartWindowExceedsCap { window: w }
6615        );
6616    }
6617
6618    #[test]
6619    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6620        // Boundary case: exactly 1ms past the cap (the granularity the
6621        // canonical-form gate enforces). Catches a future "strictly
6622        // less than" half-measure and pins the diagnostic to name the
6623        // offending `Duration` verbatim. Peer of
6624        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6625        // `rejects_policy_timeout_one_millisecond_above_cap` /
6626        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6627        // on the sibling typed-`Duration` axes' top edges.
6628        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6629        let s = SupervisorSpec {
6630            restart_window: Some(w),
6631            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6632            ..SupervisorSpec::default()
6633        };
6634        assert_eq!(
6635            s.validate().unwrap_err(),
6636            SupervisorError::RestartWindowExceedsCap { window: w }
6637        );
6638    }
6639
6640    #[test]
6641    fn validate_rejects_restart_window_far_above_cap() {
6642        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6643        // `(:restart-window "7d")`, or any "I want a lifetime counter
6644        // but wrote a `<integer>h` magnitude anyway" typo — values the
6645        // canonical-form arm accepts as integer-millisecond magnitudes,
6646        // the codec round-trips losslessly through serde, but the
6647        // operator's `MaxIntensity / Period` reconciler cannot honor
6648        // as a meaningful rolling window. Until this gate landed
6649        // validate accepted them. Pin the common above-cap values (24h,
6650        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6651        // surfaces here.
6652        for w in [
6653            Duration::from_secs(86_400),    // 24h
6654            Duration::from_secs(604_800),   // 7d
6655            Duration::from_secs(1_000_000), // ~11.5 days
6656        ] {
6657            let s = SupervisorSpec {
6658                restart_window: Some(w),
6659                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6660                ..SupervisorSpec::default()
6661            };
6662            assert_eq!(
6663                s.validate().unwrap_err(),
6664                SupervisorError::RestartWindowExceedsCap { window: w }
6665            );
6666        }
6667    }
6668
6669    #[test]
6670    fn validate_accepts_restart_window_at_cap() {
6671        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6672        // (1h) — must validate. The cap is inclusive on the top edge,
6673        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6674        // [`crate::POLICY_TIMEOUT_MAX`] /
6675        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6676        // capped axes. Pin the boundary explicitly so a future
6677        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6678        // instead of `>`) surfaces here as a test failure rather than a
6679        // silent contract narrowing.
6680        let s = SupervisorSpec {
6681            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6682            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6683            ..SupervisorSpec::default()
6684        };
6685        s.validate()
6686            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6687    }
6688
6689    #[test]
6690    fn validate_accepts_restart_window_typical_values() {
6691        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6692        // per-supervisor production-playbook band positive-control
6693        // sweep — every value Learn You Some Erlang's `{intensity, 5,
6694        // 60}` worker-supervisor `Period = 60s` default, Elixir's
6695        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6696        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6697        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6698        // default recommend (5s..=300s) must pass, plus a sweep
6699        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6700        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6701        // on the sibling `:limits :wall-clock` axis.
6702        for w in [
6703            Duration::from_millis(1),
6704            Duration::from_millis(500),
6705            Duration::from_secs(1),
6706            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
6707            Duration::from_secs(10), // Riak Core lower
6708            Duration::from_secs(30),
6709            Duration::from_secs(60),  // Learn You Some Erlang default
6710            Duration::from_secs(120), // OTP supervisor MaxT typical
6711            Duration::from_secs(300), // Riak Core upper
6712            Duration::from_secs(900), // 15m
6713            Duration::from_secs(1800),
6714            Duration::from_secs(3600), // exactly 1h, the cap
6715        ] {
6716            let s = SupervisorSpec {
6717                restart_window: Some(w),
6718                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6719                ..SupervisorSpec::default()
6720            };
6721            s.validate()
6722                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6723        }
6724    }
6725
6726    #[test]
6727    fn restart_window_zero_takes_precedence_over_cap() {
6728        // The cross-arm ordering pin: `Duration::ZERO` is structurally
6729        // outside both `>= 1ms` (zero-floor) and `<=
6730        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6731        // diagnostic is the more self-locating one (it directly names
6732        // the omit-axis remediation), so the validate gate must fire
6733        // on zero first. Same shape every other zero-then-cap ordering
6734        // on this surface uses (`WallClockZero` then
6735        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6736        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6737        // `PolicyBreakerWindowExceedsCap`).
6738        let s = SupervisorSpec {
6739            restart_window: Some(Duration::ZERO),
6740            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6741            ..SupervisorSpec::default()
6742        };
6743        assert_eq!(
6744            s.validate().unwrap_err(),
6745            SupervisorError::RestartWindowZero,
6746            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6747        );
6748    }
6749
6750    #[test]
6751    fn restart_window_canonical_takes_precedence_over_cap() {
6752        // The cross-arm ordering pin: a `Duration` that is *both*
6753        // sub-millisecond (non-canonical-form) and structurally above
6754        // the cap surfaces the canonical-form diagnostic first,
6755        // because the round-trip-shape break is the more fundamental
6756        // issue (the value can't even round-trip through the codec,
6757        // so the cap diagnostic naming `1ms..=1h` would be misleading
6758        // — there's no integer-ms form of the offending value). Pin
6759        // the order so a future refactor that reorders the arms
6760        // surfaces here as a test failure rather than a silent
6761        // diagnostic regression. Peer of
6762        // `wall_clock_canonical_takes_precedence_over_cap` /
6763        // `policy_timeout_canonical_takes_precedence_over_cap`.
6764        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6765        let s = SupervisorSpec {
6766            restart_window: Some(w),
6767            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6768            ..SupervisorSpec::default()
6769        };
6770        assert_eq!(
6771            s.validate().unwrap_err(),
6772            SupervisorError::RestartWindowNotCanonical { window: w },
6773            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6774        );
6775    }
6776
6777    #[test]
6778    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6779        // The cross-arm ordering pin between the `:max-restarts` cap
6780        // and the sibling `:restart-window` cap. A supervisor carrying
6781        // both an over-cap `max_restarts` AND an over-cap window must
6782        // surface the `MaxRestartsExceedsCap` diagnostic first — the
6783        // cap arm is wired immediately after the zero-restart arm and
6784        // strictly before every window-axis arm (zero / canonical /
6785        // cap), so the offending value the diagnostic names matches
6786        // the order the author would discover the gates by reading
6787        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6788        // order so a future refactor that reorders the arms surfaces
6789        // here as a test failure rather than a silent diagnostic
6790        // regression. Peer of
6791        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6792        // on the sibling zero / canonical window arms.
6793        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6794        let s = SupervisorSpec {
6795            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6796            restart_window: Some(w),
6797            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6798            ..SupervisorSpec::default()
6799        };
6800        assert_eq!(
6801            s.validate().unwrap_err(),
6802            SupervisorError::MaxRestartsExceedsCap {
6803                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6804            },
6805            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6806        );
6807    }
6808
6809    #[test]
6810    fn restart_window_cap_diagnostic_carries_offending_value() {
6811        // The diagnostic-shape pin: the offending `Duration` is
6812        // carried verbatim into the
6813        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6814        // surfaced error message names the value the author wrote,
6815        // not just the cap. Same self-locating diagnostic shape every
6816        // other typed-cap arm on this surface carries
6817        // (`WallClockExceedsCap` carries the offending `Duration`
6818        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6819        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6820        // the offending `Duration` verbatim).
6821        let w = Duration::from_secs(7200); // 2h
6822        let s = SupervisorSpec {
6823            restart_window: Some(w),
6824            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6825            ..SupervisorSpec::default()
6826        };
6827        let err = s.validate().unwrap_err();
6828        assert!(
6829            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6830            "got {err:?}"
6831        );
6832        let msg = err.to_string();
6833        assert!(
6834            msg.contains("7200"),
6835            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6836        );
6837    }
6838
6839    #[test]
6840    fn supervisor_restart_window_cap_pins_canonical_value() {
6841        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6842        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6843        // shared duration codec emits as a clean canonical string
6844        // (`"<n>h"`). Pinning the literal value here surfaces a future
6845        // drift (a relaxation to 24h, a tightening to 5m) as a
6846        // deliberate test edit, not a silent contract narrowing.
6847        //
6848        // The four typed-`Duration` caps on the validation surface
6849        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6850        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6851        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6852        // single uniform top edge at the codec's largest emitted unit
6853        // — a structural-property invariant the equality assertions
6854        // here enshrine, so a future drift on any of the four
6855        // surfaces as a deliberate test edit. Same shape every other
6856        // typed-cap value pin uses
6857        // (`wall_clock_cap_pins_canonical_value`,
6858        // `policy_timeout_cap_pins_canonical_value`,
6859        // `circuit_breaker_window_cap_pins_canonical_value`).
6860        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6861        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6862        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6863        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6864        assert_eq!(
6865            SUPERVISOR_RESTART_WINDOW_MAX,
6866            crate::POLICY_BREAKER_WINDOW_MAX
6867        );
6868    }
6869
6870    #[test]
6871    fn restart_window_cap_value_round_trips_through_codec() {
6872        // The codec round-trip property the cap arm preserves: the
6873        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6874        // through the shared duration codec — every value at the cap
6875        // serializes to the canonical `"1h"` form and parses back
6876        // identically. Pin the round-trip so a future change to the
6877        // codec's unit set or to the cap's magnitude that breaks the
6878        // round-trip property surfaces here. Peer of
6879        // `wall_clock_cap_value_round_trips_through_codec` on the
6880        // sibling `:limits :wall-clock` axis.
6881        let s = SupervisorSpec {
6882            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6883            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6884            ..SupervisorSpec::default()
6885        };
6886        s.validate().unwrap();
6887        let json = serde_json::to_string(&s).unwrap();
6888        assert!(
6889            json.contains("\"1h\""),
6890            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6891        );
6892        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6893        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6894    }
6895
6896    #[test]
6897    fn validate_rejects_duplicate_child_caixa() {
6898        // Two children with the same :caixa render to two ComputeUnits
6899        // with the same name in the cluster's HelmRelease values —
6900        // one silently overwrites the other. Erlang/OTP's child_spec.id
6901        // is required-unique per supervisor; same set-not-multiset
6902        // discipline applied here as for :membros / :placement
6903        // :clusters / :entrada :paths.
6904        let s = SupervisorSpec {
6905            children: vec![
6906                child("worker", "^0.1", RestartPolicy::Permanent),
6907                child("cache", "^0.1", RestartPolicy::Transient),
6908                child("worker", "^0.2", RestartPolicy::Permanent),
6909            ],
6910            ..SupervisorSpec::default()
6911        };
6912        let err = s.validate().unwrap_err();
6913        assert!(
6914            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6915            "got {err:?}"
6916        );
6917    }
6918
6919    #[test]
6920    fn validate_duplicate_child_diagnostic_names_first_collision() {
6921        // Iteration walks the :children list in declaration order —
6922        // the diagnostic names the first repeat, deterministically,
6923        // even when multiple names duplicate.
6924        let s = SupervisorSpec {
6925            children: vec![
6926                child("a", "^0.1", RestartPolicy::Permanent),
6927                child("b", "^0.1", RestartPolicy::Permanent),
6928                child("a", "^0.1", RestartPolicy::Permanent),
6929                child("b", "^0.1", RestartPolicy::Permanent),
6930            ],
6931            ..SupervisorSpec::default()
6932        };
6933        let err = s.validate().unwrap_err();
6934        assert!(
6935            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6936            "got {err:?}"
6937        );
6938    }
6939
6940    // ── self-supervision cross-slot gate ──────────────────────────
6941
6942    #[test]
6943    fn validate_no_self_supervision_rejects_self_referential_child() {
6944        // A supervisor whose `:children` lists its own `:nome` is a
6945        // one-node reconciliation cycle — rejected, naming the parent.
6946        let children = vec![
6947            child("worker", "^0.1", RestartPolicy::Permanent),
6948            child("orquestra", "^0.1", RestartPolicy::Permanent),
6949        ];
6950        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6951        assert!(
6952            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6953            "got {err:?}"
6954        );
6955    }
6956
6957    #[test]
6958    fn validate_no_self_supervision_accepts_distinct_children() {
6959        // Positive control: distinct child names (including a child that
6960        // is itself a supervisor — nested trees are valid OTP) pass.
6961        let children = vec![
6962            child("worker", "^0.1", RestartPolicy::Permanent),
6963            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6964        ];
6965        validate_no_self_supervision(&children, "orquestra").unwrap();
6966    }
6967
6968    #[test]
6969    fn validate_no_self_supervision_empty_children_is_ok() {
6970        // SimpleOneForOne / no-static-children supervisors have nothing
6971        // to self-reference — the gate is vacuously satisfied.
6972        validate_no_self_supervision(&[], "orquestra").unwrap();
6973    }
6974
6975    #[test]
6976    fn validate_simple_one_for_one_skips_uniqueness_check() {
6977        // SimpleOneForOne supervisors carry no static children — the
6978        // duplicate-child loop never runs. A zero-window declaration
6979        // on a SimpleOneForOne supervisor still trips the window check
6980        // (window applies to dynamic children too).
6981        let s = SupervisorSpec {
6982            estrategia: RestartStrategy::SimpleOneForOne,
6983            restart_window: None,
6984            children: vec![],
6985            ..SupervisorSpec::default()
6986        };
6987        s.validate().unwrap();
6988        let s_zero = SupervisorSpec {
6989            estrategia: RestartStrategy::SimpleOneForOne,
6990            restart_window: Some(Duration::ZERO),
6991            children: vec![],
6992            ..SupervisorSpec::default()
6993        };
6994        assert_eq!(
6995            s_zero.validate().unwrap_err(),
6996            SupervisorError::RestartWindowZero
6997        );
6998    }
6999
7000    #[test]
7001    fn validate_zero_window_runs_after_max_restarts_check() {
7002        // Pin the order: max_restarts == 0 fires before
7003        // restart_window == 0s, so an author with both wrong sees the
7004        // counter-axis diagnostic first (matches the order in the
7005        // struct and in the doc comment).
7006        let s = SupervisorSpec {
7007            max_restarts: 0,
7008            restart_window: Some(Duration::ZERO),
7009            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7010            ..SupervisorSpec::default()
7011        };
7012        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
7013    }
7014
7015    #[test]
7016    fn round_trip_all_strategies() {
7017        for &strat in RestartStrategy::ALL {
7018            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7019            // shape partition through the [`gen_platform::IsVariant`]
7020            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
7021            // predicate rather than the raw
7022            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
7023            // open-coded pattern-match — same closed-set-typed-enum
7024            // arm-discriminator dispatch discipline the sibling
7025            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
7026            // (915a934) extended onto its two paired positive / negated
7027            // `matches!` filter sites, and the sibling
7028            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7029            // predicate convergence (766ec63) extended onto the M3 mesh-
7030            // slot per-`:placement` distribution-strategy `matches!`
7031            // discriminator axis. See the sibling
7032            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7033            // fixture and the peer `manifest::tests::
7034            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7035            // fixture — all three sites (the last unlifted
7036            // `matches!`-based arm-discriminator axis on the OTP-shape
7037            // supervisor sibling-restart-strategy closed-set typed enum,
7038            // acknowledged in 915a934's Prior-commits footnote as the
7039            // outstanding follow-up) now consult one typed dispatch on
7040            // the substrate primitive.
7041            let s = SupervisorSpec {
7042                estrategia: strat,
7043                children: if strat.is_simple_one_for_one() {
7044                    vec![]
7045                } else {
7046                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
7047                },
7048                ..SupervisorSpec::default()
7049            };
7050            let json = serde_json::to_string(&s).unwrap();
7051            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7052            assert_eq!(s, back);
7053        }
7054    }
7055
7056    #[test]
7057    fn round_trip_all_restart_policies() {
7058        for policy in [
7059            RestartPolicy::Permanent,
7060            RestartPolicy::Temporary,
7061            RestartPolicy::Transient,
7062        ] {
7063            let c = child("w", "^0.1", policy);
7064            let json = serde_json::to_string(&c).unwrap();
7065            let back: ChildSpec = serde_json::from_str(&json).unwrap();
7066            assert_eq!(c, back);
7067        }
7068    }
7069
7070    #[test]
7071    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
7072        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
7073        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
7074        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
7075        // is the only variant that satisfies `.is_simple_one_for_one()`;
7076        // every static-children-bearing arm (`OneForOne` / `OneForAll`
7077        // / `RestForOne`) returns `false`. This pin makes the partition
7078        // invariant load-bearing at caixa-core test time so a future
7079        // derive regression (a hole that returns `false` for
7080        // `SimpleOneForOne` too, or a byte-collision that flips a second
7081        // variant to `true`) trips here rather than laundering the arm
7082        // at the three test-fixture builder sites (a hole flips the
7083        // `SimpleOneForOne` fixture to carry a non-empty children list
7084        // and the subsequent `SupervisorSpec::validate` would refuse the
7085        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
7086        // a collision flips a peer strategy's fixture to carry an empty
7087        // children list and the subsequent `validate` would refuse with
7088        // [`SupervisorError::NoChildren`] — either way, the pin fires
7089        // here, at the derive site, rather than at the fixture-refusal
7090        // site far away). Peer of the sibling
7091        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
7092        // (915a934) pin on the M2 OTP-appup axis and the sibling
7093        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
7094        // pin on the M0 `:kind` axis.
7095        let cases: &[(RestartStrategy, bool)] = &[
7096            (RestartStrategy::OneForOne, false),
7097            (RestartStrategy::OneForAll, false),
7098            (RestartStrategy::RestForOne, false),
7099            (RestartStrategy::SimpleOneForOne, true),
7100        ];
7101        for (variant, expected) in cases {
7102            assert_eq!(
7103                variant.is_simple_one_for_one(),
7104                *expected,
7105                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7106                 return {expected} (partition invariant on the \
7107                 IsVariant-derived arm-discriminator predicate — every \
7108                 test-fixture site that partitions the `:children` slot \
7109                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7110                 off this typed dispatch, so a derive regression must \
7111                 surface here rather than at the fixture-refusal site)"
7112            );
7113        }
7114    }
7115
7116    #[test]
7117    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7118        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7119        // fixture-shape partition against the pre-lift
7120        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7121        // pattern-match every test-fixture builder site previously
7122        // coupled to inline. Asserts the two projections agree byte-for-
7123        // byte on every arm of the enum, so a future derive regression
7124        // that flipped either predicate's arm-set would surface here at
7125        // caixa-core test time rather than at the three fixture-builder
7126        // sites (`supervisor::tests::round_trip_all_strategies`,
7127        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7128        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7129        // far from the derive site. Same peer-shape byte-identity pin
7130        // every sibling `IsVariant`-derive-routed convergence carries on
7131        // the substrate's closed-set typed-enum surface (peer of
7132        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7133        // on the M2 OTP-appup axis).
7134        for &strat in RestartStrategy::ALL {
7135            let via_predicate = strat.is_simple_one_for_one();
7136            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7137            assert_eq!(
7138                via_predicate, via_matches,
7139                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7140                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7141                 the pre-lift open-coded pattern and the \
7142                 IsVariant-derived predicate are the same axis, \
7143                 one typed dispatch"
7144            );
7145        }
7146    }
7147
7148    #[test]
7149    fn duration_codec_round_trip_canonical_units() {
7150        // Note the canonical-form rule: durations serialize to the
7151        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7152        // "60s" — but the round-trip preserves the underlying Duration.
7153        let cases = [
7154            ("30s", Duration::from_secs(30)),
7155            ("5m", Duration::from_secs(300)),
7156            ("1h", Duration::from_secs(3600)),
7157            ("500ms", Duration::from_millis(500)),
7158        ];
7159        for (lit, dur) in cases {
7160            let s = SupervisorSpec {
7161                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7162                restart_window: Some(dur),
7163                ..SupervisorSpec::default()
7164            };
7165            let json = serde_json::to_string(&s).unwrap();
7166            assert!(
7167                json.contains(&format!("\"{lit}\"")),
7168                "expected \"{lit}\" in {json}"
7169            );
7170            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7171            assert_eq!(back.restart_window, Some(dur));
7172        }
7173    }
7174
7175    #[test]
7176    fn duration_canonicalizes_to_largest_unit() {
7177        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7178        // typed Duration still equals 60s on the way back.
7179        let s = SupervisorSpec {
7180            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7181            restart_window: Some(Duration::from_secs(60)),
7182            ..SupervisorSpec::default()
7183        };
7184        let json = serde_json::to_string(&s).unwrap();
7185        assert!(json.contains("\"1m\""), "{json}");
7186        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7187        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7188    }
7189
7190    #[test]
7191    fn three_child_one_for_one_validates() {
7192        let s = SupervisorSpec {
7193            estrategia: RestartStrategy::OneForOne,
7194            max_restarts: 5,
7195            restart_window: Some(Duration::from_secs(60)),
7196            children: vec![
7197                child("worker", "^0.1", RestartPolicy::Permanent),
7198                child("cache", "^0.1", RestartPolicy::Transient),
7199                child("scratch", "^0.1", RestartPolicy::Temporary),
7200            ],
7201        };
7202        s.validate().unwrap();
7203    }
7204
7205    #[test]
7206    fn json_uses_pascal_case_for_strategy_and_policy() {
7207        // Variant names are PascalCase by default in serde, matching
7208        // tatara-lisp's enum convention (`:estrategia OneForOne`).
7209        let c = child("w", "^0.1", RestartPolicy::Permanent);
7210        let json = serde_json::to_string(&c).unwrap();
7211        assert!(json.contains("\"Permanent\""));
7212        assert!(!json.contains("\"permanent\""));
7213
7214        let s = SupervisorSpec {
7215            estrategia: RestartStrategy::OneForOne,
7216            children: vec![c],
7217            ..SupervisorSpec::default()
7218        };
7219        let json = serde_json::to_string(&s).unwrap();
7220        assert!(json.contains("\"estrategia\":\"OneForOne\""));
7221    }
7222
7223    // ── shared duration codec: integer-magnitude canonical-form gate ──
7224    //
7225    // The gate lifts the discipline `crate::limits::parse_duration`
7226    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7227    // the shared codec backing the remaining three typed-duration
7228    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7229    // `:politicas :circuit-breaker :window`. Every magnitude `render`
7230    // emits is a non-negative integer with no decimal point and no
7231    // leading sign, so the codec's accepted set must match for
7232    // serialize/deserialize to round-trip without canonical-form
7233    // drift.
7234
7235    #[test]
7236    fn parse_accepts_integer_canonical_units() {
7237        // Pin the happy-path: every canonical author shape `render`
7238        // ever emits parses to the same `Duration` value, so the
7239        // codec's accepted set is at least a superset of its emitted
7240        // set on the canonical-unit axis.
7241        for (lit, dur) in [
7242            ("30s", Duration::from_secs(30)),
7243            ("500ms", Duration::from_millis(500)),
7244            ("2m", Duration::from_secs(120)),
7245            ("1h", Duration::from_secs(3600)),
7246            ("0s", Duration::ZERO),
7247        ] {
7248            assert_eq!(
7249                duration_codec::parse(lit).unwrap(),
7250                dur,
7251                "parse({lit:?}) should be {dur:?}"
7252            );
7253        }
7254    }
7255
7256    #[test]
7257    fn parse_accepts_bare_integer_as_seconds() {
7258        // The `"s" | ""` arm: a bare integer with no unit is read as
7259        // seconds. Pin this so the unit-empty form keeps parsing (it
7260        // renders to `"<n>s"` on serialize — that's a unit-choice
7261        // drift the integer-magnitude gate does NOT close, matching
7262        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7263        // the peer `:limits :memory` codec).
7264        assert_eq!(
7265            duration_codec::parse("30").unwrap(),
7266            Duration::from_secs(30)
7267        );
7268    }
7269
7270    #[test]
7271    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7272        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7273        // on first serialize — DRIFT. The integer-magnitude gate names
7274        // the offending `"1.5"` verbatim and points at the canonical
7275        // remediation `"1500ms"`.
7276        let err = duration_codec::parse("1.5s").unwrap_err();
7277        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7278        assert!(
7279            err.contains("not a non-negative integer"),
7280            "missing canonical-form reason in {err:?}"
7281        );
7282        assert!(
7283            err.contains("\"1500ms\""),
7284            "missing canonical-form remediation in {err:?}"
7285        );
7286    }
7287
7288    #[test]
7289    fn parse_rejects_decimal_shaped_integer_seconds() {
7290        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7291        // `1s` exactly, so the round-trip looks correct — but the
7292        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7293        // decimal-shape-with-integer-value form so author intent is
7294        // never silently rewritten.
7295        let err = duration_codec::parse("1.0s").unwrap_err();
7296        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7297        assert!(
7298            err.contains("not a non-negative integer"),
7299            "missing canonical-form reason in {err:?}"
7300        );
7301    }
7302
7303    #[test]
7304    fn parse_rejects_half_unit_minute() {
7305        // `"0.5m"` is the unit-fraction footgun — author writes a
7306        // human-readable half-minute, serde silently rewrites to
7307        // `"30s"` on next emit. The gate names the offending
7308        // magnitude `"0.5"` and points at the integer-in-smaller-unit
7309        // form.
7310        let err = duration_codec::parse("0.5m").unwrap_err();
7311        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7312        assert!(
7313            err.contains("\"30s\""),
7314            "missing canonical-form remediation in {err:?}"
7315        );
7316    }
7317
7318    #[test]
7319    fn parse_rejects_leading_plus_sign() {
7320        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7321        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7322        // cleanly to 30s and round-tripped to `"30s"` on next emit
7323        // (DRIFT). The digit-only gate closes the leading-sign class
7324        // first; the diagnostic names `"+30"` verbatim.
7325        let err = duration_codec::parse("+30s").unwrap_err();
7326        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7327        assert!(
7328            err.contains("not a non-negative integer"),
7329            "missing canonical-form reason in {err:?}"
7330        );
7331    }
7332
7333    #[test]
7334    fn parse_rejects_leading_minus_sign() {
7335        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7336        // rejected with `"negative duration in \"-30s\""`. Under the
7337        // integer-magnitude gate the diagnostic is unified — `-30` is
7338        // non-digit-only, f64-numeric, and surfaces with the canonical-
7339        // form reason (no leading `+` / `-` sign) naming the offending
7340        // `"-30"` verbatim. Same diagnostic shape as every other
7341        // rejected non-integer magnitude.
7342        let err = duration_codec::parse("-30s").unwrap_err();
7343        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7344        assert!(
7345            err.contains("not a non-negative integer"),
7346            "missing canonical-form reason in {err:?}"
7347        );
7348    }
7349
7350    #[test]
7351    fn parse_garbage_still_falls_through_to_bad_magnitude() {
7352        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7353        // through to the narrower "bad duration magnitude" arm — the
7354        // canonical-form diagnostic is reserved for the parser-shape
7355        // footgun case, not the "not a number at all" case. Same
7356        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7357        // the peer `:limits :memory` codec.
7358        let err = duration_codec::parse("--1s").unwrap_err();
7359        assert!(
7360            err.contains("bad duration magnitude"),
7361            "expected bad-magnitude wording in {err:?}"
7362        );
7363    }
7364
7365    #[test]
7366    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7367        // The accepted set is now closed under `u64`-exact integer
7368        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7369        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7370        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7371        // possible. Pin the integer-exact arms across the four unit
7372        // suffixes so a future refactor that reaches back for f64
7373        // (`from_secs_f64`, `mul_f64`) surfaces here.
7374        assert_eq!(
7375            duration_codec::parse("3600s").unwrap(),
7376            Duration::from_secs(3600)
7377        );
7378        assert_eq!(
7379            duration_codec::parse("60m").unwrap(),
7380            Duration::from_secs(3600)
7381        );
7382        assert_eq!(
7383            duration_codec::parse("1h").unwrap(),
7384            Duration::from_secs(3600)
7385        );
7386        assert_eq!(
7387            duration_codec::parse("999ms").unwrap(),
7388            Duration::from_millis(999)
7389        );
7390    }
7391
7392    #[test]
7393    fn restart_window_serde_rejects_fractional_seconds() {
7394        // The shared codec backs `SupervisorSpec::restart_window`
7395        // (`with = "duration_codec"`) — so the gate applies on serde
7396        // deserialize for the typed Supervisor slot. A
7397        // `{"restartWindow":"1.5s"}` payload that previously round-
7398        // tripped to a different canonical string on next serialize
7399        // is now refused at deserialize with the integer-magnitude
7400        // diagnostic.
7401        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7402            "restartWindow":"1.5s",
7403            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7404        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7405        let msg = err.to_string();
7406        assert!(
7407            msg.contains("not a non-negative integer"),
7408            "expected integer-magnitude diagnostic in {msg:?}"
7409        );
7410        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7411    }
7412
7413    #[test]
7414    fn restart_window_serde_rejects_leading_plus() {
7415        // The `u64::from_str` leading-`+` permissiveness gap that
7416        // motivated the digit-only gate (the `f64`-side accepted
7417        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7418        // is now closed on the shared codec — surfaces as a structured
7419        // diagnostic at the serde layer for every typed-duration slot.
7420        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7421            "restartWindow":"+30s",
7422            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7423        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7424        let msg = err.to_string();
7425        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7426        assert!(
7427            msg.contains("not a non-negative integer"),
7428            "missing canonical-form reason in {msg:?}"
7429        );
7430    }
7431
7432    #[test]
7433    fn parse_rejects_leading_zero_magnitude() {
7434        // `"030s"` is digit-only, so the existing non-digit-only / sign
7435        // / fractional arm doesn't catch it — `u64::from_str("030")`
7436        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7437        // `Duration::from_secs(30)` and round-tripped through `render`
7438        // to `"30s"` — a *different* canonical string on the next emit,
7439        // breaking the THEORY.md Part V render-determinism contract
7440        // exactly the way `"+30s"` did before the leading-`+` arm
7441        // landed. Peer with the `rate_limit_codec` leading-zero arm
7442        // (4f46830) on the same canonical-form-drift axis.
7443        let err = duration_codec::parse("030s").unwrap_err();
7444        assert!(
7445            err.contains("non-canonical leading zero"),
7446            "expected leading-zero diagnostic in {err:?}"
7447        );
7448        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7449        assert!(
7450            err.contains("\"30s\""),
7451            "missing canonical-form remediation in {err:?}"
7452        );
7453        assert!(
7454            err.contains("THEORY.md"),
7455            "missing render-determinism citation in {err:?}"
7456        );
7457    }
7458
7459    #[test]
7460    fn parse_rejects_multi_digit_zero_magnitude() {
7461        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7462        // digit-only, parse losslessly to `Duration::ZERO`, but render
7463        // back to `"0s"` (the single-byte canonical form) on the next
7464        // emit. The leading-zero arm refuses the drift class at the
7465        // codec layer; the semantic-zero gate downstream
7466        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7467        // the single-byte canonical form `"0s"` separately on the
7468        // typed-validate layer.
7469        let err = duration_codec::parse("00s").unwrap_err();
7470        assert!(
7471            err.contains("non-canonical leading zero"),
7472            "expected leading-zero diagnostic in {err:?}"
7473        );
7474        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7475    }
7476
7477    #[test]
7478    fn parse_rejects_leading_zero_per_hour_window() {
7479        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7480        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7481        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7482        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7483        // `h` / bare-integer-as-seconds) inherits the same gate.
7484        let err = duration_codec::parse("01h").unwrap_err();
7485        assert!(
7486            err.contains("non-canonical leading zero"),
7487            "expected leading-zero diagnostic in {err:?}"
7488        );
7489        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7490    }
7491
7492    #[test]
7493    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7494        // The `parse_accepts_bare_integer_as_seconds` happy-path
7495        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7496        // multi-byte starts-with-`0`, parses losslessly to
7497        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7498        // bare-integer surface accepts permissive unit-empty
7499        // shorthand but still must reject leading-zero padding.
7500        let err = duration_codec::parse("030").unwrap_err();
7501        assert!(
7502            err.contains("non-canonical leading zero"),
7503            "expected leading-zero diagnostic in {err:?}"
7504        );
7505        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7506    }
7507
7508    #[test]
7509    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7510        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7511        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7512        // each round-trips losslessly through `render`
7513        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7514        // accepts them. The downstream semantic-zero gates
7515        // (`SupervisorError::ZeroRestartWindow`,
7516        // `AplicacaoError::PolicyTimeoutZero`,
7517        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7518        // zero-magnitude authoring at the typed-validate layer above,
7519        // peer with the `rate_limit_codec` codec-layer / typed-
7520        // validate-layer partition for `"0/s"`.
7521        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7522        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7523        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7524    }
7525
7526    #[test]
7527    fn parse_accepts_canonical_magnitude_with_leading_one() {
7528        // The complementary boundary: a future tightening cannot
7529        // drift into rejecting valid canonical magnitudes that
7530        // happen to start with `1` (or any digit `[1-9]`). Pin
7531        // every canonical-unit suffix so the leading-zero arm
7532        // remains strictly narrower than the digit-only arm.
7533        assert_eq!(
7534            duration_codec::parse("100ms").unwrap(),
7535            Duration::from_millis(100)
7536        );
7537        assert_eq!(
7538            duration_codec::parse("100s").unwrap(),
7539            Duration::from_secs(100)
7540        );
7541        assert_eq!(
7542            duration_codec::parse("10m").unwrap(),
7543            Duration::from_secs(600)
7544        );
7545        assert_eq!(
7546            duration_codec::parse("10h").unwrap(),
7547            Duration::from_secs(36_000)
7548        );
7549    }
7550
7551    #[test]
7552    fn restart_window_serde_rejects_leading_zero() {
7553        // The shared codec backs `SupervisorSpec::restart_window`
7554        // (`with = "duration_codec"`) — so the leading-zero arm
7555        // applies on serde deserialize for the typed Supervisor slot.
7556        // A `{"restartWindow":"030s"}` payload that previously round-
7557        // tripped to a different canonical string on next serialize
7558        // is now refused at deserialize with the leading-zero
7559        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7560        // / `restart_window_serde_rejects_fractional_seconds` on the
7561        // same canonical-form-drift axis.
7562        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7563            "restartWindow":"030s",
7564            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7565        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7566        let msg = err.to_string();
7567        assert!(
7568            msg.contains("non-canonical leading zero"),
7569            "expected leading-zero diagnostic in {msg:?}"
7570        );
7571        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7572    }
7573
7574    #[test]
7575    fn parse_rejects_leading_whitespace() {
7576        // `" 30s"` — the canonical paste-from-aligned-doc /
7577        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7578        // gate the top-level `s.trim()` at parse entry silently ate
7579        // the leading space and parsed the value to
7580        // `Duration::from_secs(30)`, which then round-tripped through
7581        // `render` to `"30s"` (a *different* canonical string on the
7582        // next emit) — the exact canonical-form-drift class the
7583        // leading-`+` / leading-zero arms already close, extended
7584        // to the whitespace-byte class. Peer with the sibling
7585        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7586        // the M3 `:politicas` axis.
7587        let err = duration_codec::parse(" 30s").unwrap_err();
7588        assert!(
7589            err.contains("contains whitespace byte"),
7590            "expected whitespace diagnostic in {err:?}"
7591        );
7592        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7593        assert!(
7594            err.contains("THEORY.md"),
7595            "missing render-determinism contract citation in {err:?}"
7596        );
7597    }
7598
7599    #[test]
7600    fn parse_rejects_trailing_whitespace() {
7601        // `"30s "` — the canonical shell-history / trailing-space
7602        // paste footgun. Before this gate the top-level `s.trim()`
7603        // silently ate the trailing space and parsed to
7604        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7605        // next emit — same canonical-form drift as the leading-space
7606        // sibling, closed on the same whitespace-byte arm.
7607        let err = duration_codec::parse("30s ").unwrap_err();
7608        assert!(
7609            err.contains("contains whitespace byte"),
7610            "expected whitespace diagnostic in {err:?}"
7611        );
7612        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7613    }
7614
7615    #[test]
7616    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7617        // `"30 s"` — the canonical typographically-spaced author
7618        // shape (the same idiom every prose reference to a duration
7619        // renders as, mistakenly retained when the value is pasted
7620        // into a codec-shaped slot). Before this gate the per-part
7621        // `num_part.trim()` / `unit.trim()` calls silently ate the
7622        // whitespace between the magnitude and the unit and parsed
7623        // the value to `Duration::from_secs(30)`, round-tripping to
7624        // `"30s"` — the codec's *internal* whitespace-tolerance
7625        // vector, orthogonal to the leading / trailing surface but
7626        // the same canonical-form-drift class. Pins the arm as
7627        // strictly stronger than the pre-existing top-level
7628        // `s.trim()` behavior: it fires on whitespace anywhere in
7629        // the value, not just at the string boundary.
7630        let err = duration_codec::parse("30 s").unwrap_err();
7631        assert!(
7632            err.contains("contains whitespace byte"),
7633            "expected whitespace diagnostic in {err:?}"
7634        );
7635        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7636    }
7637
7638    #[test]
7639    fn parse_rejects_tab_byte() {
7640        // `"\t30s"` — the canonical paste-from-indented-doc /
7641        // paste-from-YAML-block-scalar footgun where a tab byte leads
7642        // the magnitude. Pins that the gate covers tab (`0x09`) as
7643        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7644        // members and both would be silently swallowed by `s.trim()`
7645        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7646        // space alone to the full ASCII-whitespace set (space `0x20`,
7647        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7648        // the tab arm as a representative of the non-space members.
7649        let err = duration_codec::parse("\t30s").unwrap_err();
7650        assert!(
7651            err.contains("contains whitespace byte"),
7652            "expected whitespace diagnostic in {err:?}"
7653        );
7654        assert!(
7655            err.contains("0x09"),
7656            "missing offending tab byte in {err:?}"
7657        );
7658    }
7659
7660    #[test]
7661    fn restart_window_serde_rejects_whitespace() {
7662        // The shared codec backs `SupervisorSpec::restart_window`
7663        // (`with = "duration_codec"`) — so the whitespace arm
7664        // applies on serde deserialize for the typed Supervisor slot.
7665        // A `{"restartWindow":" 30s"}` payload that previously round-
7666        // tripped to a different canonical string on next serialize
7667        // is now refused at deserialize with the whitespace-byte
7668        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7669        // / `restart_window_serde_rejects_leading_plus` /
7670        // `restart_window_serde_rejects_fractional_seconds` on the
7671        // same canonical-form-drift axis.
7672        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7673            "restartWindow":" 30s",
7674            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7675        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7676        let msg = err.to_string();
7677        assert!(
7678            msg.contains("contains whitespace byte"),
7679            "expected whitespace diagnostic in {msg:?}"
7680        );
7681        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7682    }
7683
7684    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7685    //
7686    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7687    // duration codec — closes the strictly-complementary class the
7688    // byte-scan cannot see, through the lifted
7689    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7690    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7691    // and `:politicas :circuit-breaker :window` simultaneously via
7692    // this shared codec.
7693
7694    #[test]
7695    fn duration_codec_parse_rejects_leading_nbsp() {
7696        // NBSP prefix — the strictly-complementary drift class the
7697        // ASCII byte-scan cannot see. `str::trim` strips it silently
7698        // and the value drifts to `"30s"` on next serialize.
7699        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7700        assert!(
7701            err.contains("non-ASCII Unicode whitespace character"),
7702            "expected non-ASCII whitespace diagnostic in {err:?}"
7703        );
7704        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7705    }
7706
7707    #[test]
7708    fn duration_codec_parse_rejects_trailing_line_separator() {
7709        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7710        // footgun.
7711        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7712        assert!(
7713            err.contains("non-ASCII Unicode whitespace character"),
7714            "expected non-ASCII whitespace diagnostic in {err:?}"
7715        );
7716        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7717    }
7718
7719    #[test]
7720    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7721        // Positive-control pin: every ASCII-only canonical form the
7722        // renderer emits stays accepted through the new arm.
7723        assert_eq!(
7724            duration_codec::parse("30s").unwrap(),
7725            Duration::from_secs(30)
7726        );
7727        assert_eq!(
7728            duration_codec::parse("500ms").unwrap(),
7729            Duration::from_millis(500)
7730        );
7731        assert_eq!(
7732            duration_codec::parse("1h").unwrap(),
7733            Duration::from_secs(3600)
7734        );
7735    }
7736
7737    #[test]
7738    fn restart_window_serde_rejects_non_ascii_whitespace() {
7739        // The shared codec backs `SupervisorSpec::restart_window` — so
7740        // the new non-ASCII Unicode whitespace arm applies on serde
7741        // deserialize for the typed Supervisor slot. A
7742        // `{"restartWindow":" 30s"}` payload that previously
7743        // survived the ASCII byte-scan (only ASCII whitespace was
7744        // refused) is now refused at deserialize with the
7745        // non-ASCII-whitespace-and-codepoint diagnostic.
7746        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7747            \"restartWindow\":\"\u{00A0}30s\",\
7748            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7749        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7750        let msg = err.to_string();
7751        assert!(
7752            msg.contains("non-ASCII Unicode whitespace character"),
7753            "expected non-ASCII whitespace diagnostic in {msg:?}"
7754        );
7755        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7756    }
7757
7758    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7759
7760    #[test]
7761    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7762        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7763        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7764        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7765        // name the exact camelCase JSON keys the
7766        // `#[serde(rename_all = "camelCase")]` attribute on
7767        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7768        // field carries `Some(_)` / non-empty) and pin that each canonical
7769        // byte-sequence appears verbatim in the JSON — a future accidental
7770        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7771        // name flip at the derive attribute (any of which would silently
7772        // break every downstream JSON consumer that reaches for one of the
7773        // four consts via `Value::get(...)`) surfaces here as a build-time
7774        // test failure at `supervisor.rs`, not as an apply-time
7775        // `.get(<stale-canonical-const>)` returning `None` far from the
7776        // derive-attr drift's commit. Peer with the sibling
7777        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7778        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7779        // M2 typed-slot family established, extended here to close the
7780        // top-level Supervisor axis.
7781        let spec = SupervisorSpec {
7782            estrategia: RestartStrategy::OneForOne,
7783            max_restarts: 5,
7784            restart_window: Some(Duration::from_secs(60)),
7785            children: vec![ChildSpec {
7786                caixa: "w".into(),
7787                versao: "^0.1".into(),
7788                restart: RestartPolicy::Permanent,
7789            }],
7790        };
7791        let json = serde_json::to_string(&spec).unwrap();
7792        for key in [
7793            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7794            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7795            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7796            crate::render::SUPERVISOR_KEY_CHILDREN,
7797        ] {
7798            let quoted = format!("\"{key}\"");
7799            assert!(
7800                json.contains(&quoted),
7801                "serialized SupervisorSpec must carry the lifted \
7802                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7803                 the JSON emission (got: {json})",
7804            );
7805        }
7806    }
7807
7808    #[test]
7809    fn supervisor_key_consts_are_pairwise_distinct() {
7810        // Cross-axis drift-detection pin: a future collapse of two
7811        // canonical top-level byte-strings onto the same value (e.g. an
7812        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7813        // also read `"estrategia"`) would silently reroute every
7814        // downstream probe on one axis onto the sibling axis's overlay
7815        // entry and pass every propagation-probe test that expected only
7816        // the stale axis's value. Peer of the sibling four-way distinct
7817        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7818        let all = [
7819            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7820            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7821            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7822            crate::render::SUPERVISOR_KEY_CHILDREN,
7823        ];
7824        for (i, a) in all.iter().enumerate() {
7825            for b in all.iter().skip(i + 1) {
7826                assert_ne!(
7827                    a, b,
7828                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7829                     canonical byte-sequences — got `{a}` == `{b}`",
7830                );
7831            }
7832        }
7833    }
7834
7835    #[test]
7836    fn supervisor_key_consts_are_lower_camel_case_shape() {
7837        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7838        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7839        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7840        // capital, no whitespace / dots) — the canonical shape the
7841        // `#[serde(rename_all = "camelCase")]` derive produces on
7842        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7843        // at the derive surfaces both here (this test fails on the
7844        // stale-constant shape) and at
7845        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7846        // (that test fails on the mismatch between const and derive).
7847        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7848        // (d8b8b4f) on the sibling M2 `:limits` axis.
7849        for key in [
7850            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7851            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7852            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7853            crate::render::SUPERVISOR_KEY_CHILDREN,
7854        ] {
7855            assert!(
7856                !key.is_empty(),
7857                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7858            );
7859            let first = key.chars().next().unwrap();
7860            assert!(
7861                first.is_ascii_lowercase(),
7862                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7863                 (got {key:?}, leads with {first:?})",
7864            );
7865            assert!(
7866                key.chars().all(|c| c.is_ascii_alphanumeric()),
7867                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7868                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7869            );
7870        }
7871    }
7872
7873    #[test]
7874    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7875        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7876        // (camelCase JSON keys, no leading colon) must never collide
7877        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7878        // consts (kebab-case author-facing labels with leading colon)
7879        // that sit next to them at `caixa_core::render`. Both families
7880        // cover the same four typed Supervisor slots on two distinct
7881        // axes (author-side kebab vs renderer-side camelCase);
7882        // collapsing either family onto the other's byte-shape would
7883        // silently reroute the render-side probe onto the author-facing
7884        // surface, or vice versa. Peer of the byte-distinctness
7885        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7886        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7887        let pairs = [
7888            (
7889                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7890                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7891            ),
7892            (
7893                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7894                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7895            ),
7896            (
7897                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7898                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7899            ),
7900            (
7901                crate::render::SUPERVISOR_KEY_CHILDREN,
7902                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7903            ),
7904        ];
7905        for (json_key, author_key) in pairs {
7906            assert_ne!(
7907                json_key, author_key,
7908                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7909                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7910                 got JSON `{json_key}` == author `{author_key}`",
7911            );
7912        }
7913    }
7914
7915    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7916
7917    #[test]
7918    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7919        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7920        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7921        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7922        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7923        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7924        // pin that each canonical byte-sequence appears verbatim in the
7925        // JSON — a future accidental `rename_all = "snake_case"` /
7926        // `"kebab-case"` / verbatim-field-name flip at the derive
7927        // attribute (any of which would silently break every downstream
7928        // JSON consumer that reaches for one of the three consts via
7929        // `Value::get(...)`) surfaces here as a build-time test failure at
7930        // `supervisor.rs`, not as an apply-time
7931        // `.get(<stale-canonical-const>)` returning `None` far from the
7932        // derive-attr drift's commit. Peer with the enclosing
7933        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7934        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7935        // discipline the SupervisorSpec top-level lift established,
7936        // extended here to the sibling per-`:children` entry `ChildSpec`
7937        // derive so the last M2 typed-struct sub-block
7938        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7939        // surface without a lifted serde-key peer joins the substrate's
7940        // "one canonical byte-string per typed serialized-key axis"
7941        // discipline.
7942        let c = ChildSpec {
7943            caixa: "worker".into(),
7944            versao: "^0.1".into(),
7945            restart: RestartPolicy::Permanent,
7946        };
7947        let json = serde_json::to_string(&c).unwrap();
7948        for key in [
7949            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7950            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7951            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7952        ] {
7953            let quoted = format!("\"{key}\"");
7954            assert!(
7955                json.contains(&quoted),
7956                "serialized ChildSpec must carry the lifted \
7957                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7958                 in the JSON emission (got: {json})",
7959            );
7960        }
7961    }
7962
7963    #[test]
7964    fn supervisor_child_key_consts_are_pairwise_distinct() {
7965        // Cross-axis drift-detection pin: a future collapse of two
7966        // canonical `ChildSpec` per-entry byte-strings onto the same
7967        // value (e.g. an accidental copy-paste flip of
7968        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7969        // silently reroute every downstream probe on one axis onto the
7970        // sibling axis's overlay entry and pass every propagation-probe
7971        // test that expected only the stale axis's value. Peer of the
7972        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7973        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7974        // pair (ce80ca0).
7975        let all = [
7976            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7977            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7978            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7979        ];
7980        for (i, a) in all.iter().enumerate() {
7981            for b in all.iter().skip(i + 1) {
7982                assert_ne!(
7983                    a, b,
7984                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7985                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7986                );
7987            }
7988        }
7989    }
7990
7991    #[test]
7992    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7993        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7994        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7995        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7996        // capital, no whitespace / dots) — the canonical shape the
7997        // `#[serde(rename_all = "camelCase")]` derive produces on
7998        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7999        // derive surfaces both here (this test fails on the
8000        // stale-constant shape) and at
8001        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
8002        // (that test fails on the mismatch between const and derive).
8003        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
8004        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
8005        for key in [
8006            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8007            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8008            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8009        ] {
8010            assert!(
8011                !key.is_empty(),
8012                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
8013            );
8014            let first = key.chars().next().unwrap();
8015            assert!(
8016                first.is_ascii_lowercase(),
8017                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
8018                 byte (got {key:?}, leads with {first:?})",
8019            );
8020            assert!(
8021                key.chars().all(|c| c.is_ascii_alphanumeric()),
8022                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
8023                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8024            );
8025        }
8026    }
8027
8028    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
8029
8030    #[test]
8031    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
8032        // The fail-before-pass-after pin: pre-lift there was no
8033        // single-source binding between the [`RestartStrategy`] variant
8034        // name the un-`rename`d `Serialize` derive emits under
8035        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
8036        // every downstream cluster-side dispatcher (the future
8037        // wasm-operator's per-supervisor sibling-restart branch, the
8038        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8039        // admission-time enum-arm bind, the `caixa-operator`'s
8040        // hierarchical reconciliation scheduler's per-strategy fan-out)
8041        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
8042        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
8043        // override, or a variant rename in the source — would silently
8044        // rebrand the emitted scalar under one spelling while every
8045        // downstream dispatcher still probed the other, with the failure
8046        // surfacing at the operator's reconcile posture (subtrees coming
8047        // up under the `default()` `OneForOne` arm rather than the typed
8048        // slot's declared strategy — a bad child would then only take
8049        // itself down instead of the sibling set the author intended, so
8050        // shared-state children fall out of sync) far from the source
8051        // rebrand commit and with no field naming the drift. Pinning the
8052        // two paths (the `Serialize` derive's serialized string AND the
8053        // [`RestartStrategy::as_str`] helper) to the same four lifted
8054        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
8055        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
8056        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
8057        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
8058        // byte-strings makes any future drift on either endpoint fail
8059        // here at caixa-core build time. Peer of the M3
8060        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8061        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
8062        // three-path-convergence discipline, extended to close the
8063        // OTP-shaped per-supervisor sibling-restart axis.
8064        for (variant, expected) in [
8065            (
8066                RestartStrategy::OneForOne,
8067                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8068            ),
8069            (
8070                RestartStrategy::OneForAll,
8071                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8072            ),
8073            (
8074                RestartStrategy::RestForOne,
8075                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8076            ),
8077            (
8078                RestartStrategy::SimpleOneForOne,
8079                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8080            ),
8081        ] {
8082            let json = serde_json::to_string(&variant).unwrap();
8083            assert_eq!(
8084                json,
8085                format!("\"{expected}\""),
8086                "RestartStrategy::{variant:?} must serialize to {expected:?}"
8087            );
8088            assert_eq!(
8089                variant.as_str(),
8090                expected,
8091                "RestartStrategy::{variant:?}.as_str() must return the lifted \
8092                 SUPERVISOR_ESTRATEGIA_* constant"
8093            );
8094        }
8095    }
8096
8097    #[test]
8098    fn supervisor_estrategia_consts_are_pairwise_distinct() {
8099        // Cross-arm drift-detection pin: a future collapse of two
8100        // canonical variant byte-strings onto the same value (e.g. an
8101        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8102        // to also read `"OneForOne"`) would silently reroute every
8103        // downstream operator's per-strategy dispatch onto the sibling
8104        // arm's reconcile branch and pass every propagation-probe test
8105        // that expected only the stale arm's value — the mis-strategied
8106        // subtree would come up with the wrong sibling-restart posture
8107        // on every subsequent failure. Peer of the sibling four-way
8108        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8109        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8110        let all = [
8111            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8112            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8113            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8114            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8115        ];
8116        for (i, a) in all.iter().enumerate() {
8117            for (j, b) in all.iter().enumerate() {
8118                if i != j {
8119                    assert_ne!(
8120                        a, b,
8121                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8122                         — got duplicate {a:?} at indices {i} and {j}",
8123                    );
8124                }
8125            }
8126        }
8127    }
8128
8129    #[test]
8130    fn restart_strategy_display_routes_through_as_str_helper() {
8131        // The fail-before-pass-after pin on the first half of the
8132        // three-path convergence: pre-convergence the sibling
8133        // OTP-shape typed enum [`RestartStrategy`] carried a
8134        // [`std::fmt::Display`] surface via its
8135        // `#[discriminant(also_display)]` gen-platform derive route,
8136        // which arrived kebab-case as `"one-for-one"` /
8137        // `"one-for-all"` / `"rest-for-one"` /
8138        // `"simple-one-for-one"` while the wire format ran as
8139        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8140        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8141        // Every consumer reaching for a strategy byte-string past the
8142        // wire format had to pick between three paths
8143        // ([`RestartStrategy::as_str`], the `Serialize` derive's
8144        // serialized string, or `format!("{v}")` on the
8145        // discriminant-Display route), any two of which a future
8146        // variant rename or `#[serde(rename_all = "kebab-case")]`
8147        // attribute would silently desynchronize. Wiring
8148        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8149        // closes the third path: every `format!("{v}")` call reaches
8150        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8151        // const the wire format and the [`RestartStrategy::as_str`]
8152        // helper already route through, so a future variant rename
8153        // lands at exactly one place. Pin the routing here so a future
8154        // `impl std::fmt::Display for RestartStrategy`
8155        // reimplementation that hand-rolls the arms instead of
8156        // delegating to [`RestartStrategy::as_str`] fails at
8157        // caixa-core build time. Peer of the M3
8158        // `placement_strategy_display_routes_through_as_str_helper`
8159        // (cc8f749) which the M3 axis converged first.
8160        for &variant in RestartStrategy::ALL {
8161            assert_eq!(
8162                variant.to_string(),
8163                variant.as_str(),
8164                "RestartStrategy::{variant:?} Display must route through \
8165                 RestartStrategy::as_str (single source of truth: the lifted \
8166                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8167            );
8168        }
8169    }
8170
8171    #[test]
8172    fn restart_strategy_display_matches_serialized_wire_byte_string() {
8173        // The fail-before-pass-after pin on the second half of the
8174        // three-path convergence: `Display` (user-facing text) agrees
8175        // byte-for-byte with the `Serialize` derive's wire format
8176        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8177        // scalar) on every variant. Pre-convergence the two paths
8178        // were structurally independent — a future
8179        // `#[serde(rename_all = "kebab-case")]` attribute on the
8180        // enum would silently rebrand the emitted wire scalar
8181        // (`one-for-one`, `one-for-all`, `rest-for-one`,
8182        // `simple-one-for-one`) while every consumer that
8183        // pretty-prints the strategy (the future wasm-operator's
8184        // per-supervisor sibling-restart-strategy diagnostic line,
8185        // the future `feira app graph` per-supervisor strategy line,
8186        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8187        // materializer's admission-webhook rejection body) would
8188        // still emit the PascalCase form the `as_str` / `Display`
8189        // route returns, with the mismatch surfacing at consumer
8190        // parse time / operator dispatch time far from the source
8191        // rebrand commit. Pin the two paths byte-for-byte here so any
8192        // future serde-attribute or variant-rename drift is a
8193        // caixa-core-build-time test failure at this call, not a
8194        // silent per-consumer dispatch miss. Peer of the M3
8195        // `placement_strategy_display_matches_serialized_wire_byte_string`
8196        // (cc8f749) which the M3 axis converged first.
8197        for &variant in RestartStrategy::ALL {
8198            let wire = serde_json::to_string(&variant).unwrap();
8199            let unquoted = wire
8200                .strip_prefix('"')
8201                .and_then(|s| s.strip_suffix('"'))
8202                .expect("serialized RestartStrategy is a JSON string");
8203            assert_eq!(
8204                variant.to_string(),
8205                unquoted,
8206                "RestartStrategy::{variant:?} Display byte-string must match the \
8207                 Serialize derive's wire byte-string (three-path convergence: \
8208                 Display + as_str + Serialize all resolve to the same \
8209                 SUPERVISOR_ESTRATEGIA_* const)"
8210            );
8211        }
8212    }
8213
8214    #[test]
8215    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8216        // Fail-before-pass-after byte-parity pin on the lifted
8217        // `impl AsRef<str> for RestartStrategy` — asserts the
8218        // standard-library trait impl and the substrate-primitive
8219        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8220        // to the same `&str` per instance across the four-arm
8221        // closed set, so any future silent detour that routes the
8222        // impl through a divergent projection (a per-arm inline
8223        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8224        // re-inlining that opens a compile-time link to the un-lifted
8225        // arm-literal, a swap onto the kebab-case
8226        // [`gen_platform::Discriminant`] catalog identity that would
8227        // collide the wire axis with the dispatcher-catalog axis) trips
8228        // at caixa-core test time under `PartialEq` rather than at a
8229        // downstream `impl AsRef<str>`-bound consumer's silent split.
8230        // Sweeps every one of the four arms
8231        // [`RestartStrategy::ALL`] carries so no arm's projection is
8232        // covered only by the sibling wire-format `Serialize` derive
8233        // path. Peer of the sibling
8234        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8235        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8236        // top-level `:versao` typed newtype — the two pins together
8237        // cover the substrate primitive's `AsRef<str>` projection axis
8238        // on the paired newtype + closed-set-typed-enum surface.
8239        for &variant in RestartStrategy::ALL {
8240            assert_eq!(
8241                <RestartStrategy as AsRef<str>>::as_ref(&variant),
8242                variant.as_str(),
8243                "AsRef<str> impl on RestartStrategy::{variant:?} must \
8244                 byte-equal RestartStrategy::as_str on the same instance \
8245                 — divergence signals a silent detour off the substrate-\
8246                 primitive accessor"
8247            );
8248        }
8249    }
8250
8251    #[test]
8252    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8253        // Fail-before-pass-after byte-parity pin on the three-path
8254        // convergence discipline the M2 sibling-restart primitive now
8255        // carries on the `&str`-projection axis:
8256        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8257        // lifted impl), `format!("{s}")` (the pre-existing
8258        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8259        // primitive `pub const fn` accessor both trait impls delegate
8260        // through) must resolve to the same byte-string on every
8261        // instance across the four-arm closed set. Refuses any future
8262        // divergence between the two trait impls (a stray
8263        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8264        // rather than delegating through the shared accessor; a
8265        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8266        // literal cascade) that would silently split the two
8267        // projection paths of the same closed-set typed enum. Mirrors
8268        // the sibling three-path-convergence discipline the peer
8269        // [`crate::CaixaVersion`] typed newtype carries on its
8270        // `AsRef<str>` / `Display` / `as_str` triple
8271        // (version.rs pin
8272        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8273        // 16d5c7e).
8274        for &variant in RestartStrategy::ALL {
8275            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8276            let via_display: String = format!("{variant}");
8277            let via_accessor: &str = variant.as_str();
8278            assert_eq!(via_as_ref, via_accessor);
8279            assert_eq!(via_display, via_accessor);
8280            assert_eq!(via_as_ref, via_display.as_str());
8281        }
8282    }
8283
8284    #[test]
8285    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8286        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8287        // exhaustive-iteration surface: every variant appears exactly
8288        // once, and the slice length matches the arm count of the
8289        // closed set. Every consumer that walks the accepted-strategy
8290        // set (a future `feira supervisor --estrategia …` CLI-side
8291        // arg-parse's "did you mean" hint, a future M4 admission-
8292        // webhook's rejection body naming the accepted-`:estrategia`
8293        // list, the [`RestartStrategy::from_wire`] reverse-projection
8294        // consumers that iterate the accept-set for diagnostic
8295        // rendering) reads through this slice, so a future arm addition
8296        // that grows the enum but forgets to grow [`Self::ALL`]
8297        // silently truncates every downstream consumer's accept-set at
8298        // the same pre-addition boundary — this pin fails at caixa-core
8299        // build time on the pairwise-distinct + arm-count invariants.
8300        //
8301        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8302        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8303        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8304        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8305        // pins on the peer closed-set typed-enum axes.
8306        let all: &[RestartStrategy] = RestartStrategy::ALL;
8307        assert_eq!(
8308            all.len(),
8309            4,
8310            "RestartStrategy::ALL must enumerate every variant of the \
8311             four-arm closed set (OneForOne, OneForAll, RestForOne, \
8312             SimpleOneForOne); got {all:?}"
8313        );
8314        for (i, a) in all.iter().enumerate() {
8315            for (j, b) in all.iter().enumerate() {
8316                if i != j {
8317                    assert_ne!(
8318                        a, b,
8319                        "RestartStrategy::ALL must carry every variant exactly \
8320                         once — got duplicate {a:?} at indices {i} and {j}"
8321                    );
8322                }
8323            }
8324        }
8325        for variant in [
8326            RestartStrategy::OneForOne,
8327            RestartStrategy::OneForAll,
8328            RestartStrategy::RestForOne,
8329            RestartStrategy::SimpleOneForOne,
8330        ] {
8331            assert!(
8332                all.contains(&variant),
8333                "RestartStrategy::ALL must contain {variant:?} — a future arm \
8334                 addition that grows the enum but forgets to grow the ALL slice \
8335                 silently truncates every downstream consumer's accept-set at \
8336                 the pre-addition boundary"
8337            );
8338        }
8339    }
8340
8341    #[test]
8342    fn restart_strategy_wire_names_covers_every_arm() {
8343        // Load-bearing pin on the substrate-canonical
8344        // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8345        // on the `PascalCase` wire byte-string axis: every variant of
8346        // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8347        // surface must project through [`RestartStrategy::as_str`] onto
8348        // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8349        // and the roster's length must byte-equal
8350        // `RestartStrategy::ALL.len()` so a silent skew between the
8351        // [`RestartStrategy::as_str`] match's arm-set and the roster's
8352        // arm-set trips here at caixa-core test time rather than at a
8353        // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8354        // admission-webhook rejection body's wire-form `:estrategia`
8355        // accepted-set enumeration miss / a `feira supervisor
8356        // --estrategia …` "did you mean" hint drift / a future
8357        // wasm-operator per-reconcile-step diagnostic log line's
8358        // accepted-wire-form enumeration miss. A future arm addition
8359        // (an OTP-`rest_for_all` arm the theory
8360        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
8361        // might reach for once the four canonical OTP strategies stop
8362        // covering the substrate's discovered load-shape) extends
8363        // [`RestartStrategy::ALL`] as a single edit and this pin
8364        // sweeps the new arm by iteration; the paired
8365        // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
8366        // or this assertion trips. Every entry is further pinned to
8367        // open with an ASCII uppercase byte so a silent collapse of
8368        // the wire-form axis with the peer kebab-case
8369        // dispatcher-catalog axis (an entry byte-identical to a
8370        // sibling [`Self::discriminant`] kebab byte-string that would
8371        // let a wire-axis consumer accept the dispatcher-catalog
8372        // vocabulary) trips here rather than at a downstream K8s-CR
8373        // round-trip miss.
8374        //
8375        // Peer of the sibling
8376        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
8377        // (bd708bd) pin on the top-level typed-kind discriminator's
8378        // `PascalCase` wire byte-string axis, and of the sibling
8379        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
8380        // (cc42c0e) /
8381        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
8382        // (1898d77) pins on the OTP-appup discriminator's two-axis
8383        // roster split — the same closed-set exhaustive-roster
8384        // coverage discipline extended here onto the first M2
8385        // OTP-shape sibling-restart closed-set typed enum.
8386        //
8387        // Fail-before-pass-after locally verified by mutating one arm
8388        // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8389        // const family (e.g. dropping the trailing `e` from
8390        // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
8391        // but the `contains` check fires on the mutated arm; and by
8392        // shortening the roster to three entries — the length pin
8393        // fires first.
8394        assert_eq!(
8395            RestartStrategy::WIRE_NAMES.len(),
8396            RestartStrategy::ALL.len(),
8397            "RestartStrategy::WIRE_NAMES.len() must byte-equal \
8398             RestartStrategy::ALL.len() — a mismatch means the roster \
8399             and the enum's arm-set have drifted; downstream consumers \
8400             that fan through both will silently disagree on the \
8401             accepted arm-set"
8402        );
8403        for &variant in RestartStrategy::ALL {
8404            let wire = variant.as_str();
8405            assert!(
8406                RestartStrategy::WIRE_NAMES.contains(&wire),
8407                "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
8408                 be a member of RestartStrategy::WIRE_NAMES — the \
8409                 emitter and the roster have drifted out of lockstep"
8410            );
8411        }
8412        for tag in RestartStrategy::WIRE_NAMES {
8413            let first = tag.chars().next().unwrap_or_else(|| {
8414                panic!(
8415                    "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
8416                     a non-empty PascalCase byte-string"
8417                )
8418            });
8419            assert!(
8420                first.is_ascii_uppercase(),
8421                "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
8422                 with an ASCII uppercase byte (PascalCase wire form) — \
8423                 a lowercase entry would collide the wire-form axis \
8424                 with the peer kebab-case dispatcher-catalog axis \
8425                 [`RestartStrategy::discriminant`] serves"
8426            );
8427        }
8428    }
8429
8430    #[test]
8431    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8432        // Fail-before-pass-after pin on the forward accept-set of the
8433        // [`RestartStrategy::from_wire`] reverse projection: every
8434        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8435        // constant the [`RestartStrategy::as_str`] emitter walks parses
8436        // back to its paired variant. Any future arm addition that
8437        // grows the emitter's `as_str` match but forgets to grow the
8438        // parser's `from_wire` match silently splits the two halves of
8439        // the round-trip — the wire byte-string one non-serde consumer
8440        // parses from the one the emitter wrote — with the failure
8441        // surfacing at parse time far from the rebrand commit. Pinning
8442        // the four-arm accept-set here catches the drift at caixa-core
8443        // build time.
8444        //
8445        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8446        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8447        // accept-set pins on the peer closed-set typed-enum `str → Self`
8448        // axes.
8449        for (wire, expected) in [
8450            (
8451                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8452                RestartStrategy::OneForOne,
8453            ),
8454            (
8455                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8456                RestartStrategy::OneForAll,
8457            ),
8458            (
8459                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8460                RestartStrategy::RestForOne,
8461            ),
8462            (
8463                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8464                RestartStrategy::SimpleOneForOne,
8465            ),
8466        ] {
8467            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8468                panic!(
8469                    "RestartStrategy::from_wire({wire:?}) must accept every \
8470                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8471                     lifted canonical byte-string that RestartStrategy::{expected:?} \
8472                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8473                )
8474            });
8475            assert_eq!(
8476                parsed, expected,
8477                "RestartStrategy::from_wire({wire:?}) must return \
8478                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8479            );
8480        }
8481    }
8482
8483    #[test]
8484    fn restart_strategy_from_wire_round_trips_through_as_str() {
8485        // Fail-before-pass-after pin on the closed round-trip between
8486        // the forward [`RestartStrategy::as_str`] emitter and the
8487        // reverse [`RestartStrategy::from_wire`] parser: for every
8488        // variant in [`RestartStrategy::ALL`], parsing the emitter's
8489        // output must return exactly the same variant. Any per-arm
8490        // divergence — a future arm added to `as_str` but not
8491        // `from_wire`, an accidental copy-paste flip in one but not
8492        // the other — silently splits the emit and parse halves and
8493        // the failure surfaces at consumer parse time far from the
8494        // drift site. The `ALL`-iterating shape means a future arm
8495        // addition picks up the coverage by construction.
8496        //
8497        // Peer of the sibling
8498        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8499        // (18c7342) round-trip pin on
8500        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8501        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8502        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8503        for &variant in RestartStrategy::ALL {
8504            let wire = variant.as_str();
8505            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8506                panic!(
8507                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8508                     must be Some({variant:?}) — the two halves of the round-trip \
8509                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8510                     got None on wire byte-string {wire:?}"
8511                )
8512            });
8513            assert_eq!(
8514                parsed, variant,
8515                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8516                 must round-trip to the same variant; got {parsed:?}"
8517            );
8518        }
8519    }
8520
8521    #[test]
8522    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8523        // Fail-before-pass-after pin on the closed-set refusal
8524        // discipline of [`RestartStrategy::from_wire`]: every
8525        // byte-string outside the four-arm accept-set returns `None`
8526        // rather than silently collapsing onto the [`Default`]
8527        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8528        // exercised here sweeps the load-bearing drift shapes: the
8529        // empty string (a stripped serde-attribute drift), all-
8530        // whitespace strings (the canonical text-editor accidental
8531        // padding shape), the kebab-case dispatcher-catalog identities
8532        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8533        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8534        // derived [`std::str::FromStr`] accept-set, which parses the
8535        // *other* axis of this enum's two-axis split and must not leak
8536        // into the `from_wire` PascalCase-wire accept-set), the
8537        // lowercased single-word forms (`"oneforone"`), the padded
8538        // canonical scalar (`" OneForOne "`), the trailing-newline
8539        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8540        // (`"AllForOne"` — the canonical typo direction).
8541        //
8542        // Peer of the sibling
8543        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8544        // (2aa6d23) +
8545        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8546        // (18c7342) refusal pins on the peer closed-set typed-enum
8547        // axes.
8548        for bad in [
8549            "",
8550            " ",
8551            "\n",
8552            "\t",
8553            "one-for-one",
8554            "one-for-all",
8555            "rest-for-one",
8556            "simple-one-for-one",
8557            "oneforone",
8558            "OneForOnes",
8559            "one_for_one",
8560            "one for one",
8561            "ONEFORONE",
8562            "OneForOne ",
8563            " OneForOne",
8564            " SimpleOneForOne ",
8565            "OneForOne\n",
8566            "restforone",
8567            "REST_FOR_ONE",
8568            "AllForOne",
8569            "Simple",
8570            "?",
8571        ] {
8572            assert!(
8573                RestartStrategy::from_wire(bad).is_none(),
8574                "RestartStrategy::from_wire({bad:?}) must return None — the \
8575                 parser's accept-set is exactly the four RestartStrategy::as_str \
8576                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8577                 and this byte-string is outside that closed set"
8578            );
8579        }
8580    }
8581
8582    #[test]
8583    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8584        // Fail-before-pass-after pin on the fourth path of the four-path
8585        // convergence: `from_wire` (the reverse projection) inverts the
8586        // `Serialize` derive's wire byte-string on every variant.
8587        // Together with the pre-existing three-path convergence
8588        // (`Display` + `as_str` + `Serialize` all resolve to the same
8589        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8590        // pinned by
8591        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8592        // this closes the round-trip: the wire byte-string the
8593        // `Serialize` derive emits parses back to the same variant
8594        // through `from_wire`, so any future serde-attribute or variant-
8595        // rename drift on the emit half now surfaces as a matched drift
8596        // on the parse half at caixa-core build time — the two halves
8597        // migrate as a unit through the lifted consts on any future
8598        // rename, and the round-trip cannot silently split.
8599        //
8600        // Peer of the sibling
8601        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8602        // (18c7342) wire-format pin on
8603        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8604        for &variant in RestartStrategy::ALL {
8605            let wire = serde_json::to_string(&variant).unwrap();
8606            let unquoted = wire
8607                .strip_prefix('"')
8608                .and_then(|s| s.strip_suffix('"'))
8609                .expect("serialized RestartStrategy is a JSON string");
8610            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8611                panic!(
8612                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8613                     Serialize derive's wire byte-string for \
8614                     RestartStrategy::{variant:?} — the four-path convergence \
8615                     (Display + as_str + Serialize + from_wire) resolves through \
8616                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8617                )
8618            });
8619            assert_eq!(
8620                parsed, variant,
8621                "RestartStrategy::from_wire of the Serialize derive's wire \
8622                 byte-string for RestartStrategy::{variant:?} must round-trip \
8623                 to the same variant; got {parsed:?}"
8624            );
8625        }
8626    }
8627
8628    #[test]
8629    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8630        // Fail-before-pass-after byte-parity pin on the newly lifted
8631        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8632        // library trait impl and the substrate-primitive
8633        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8634        // the same four-arm accept-set across every arm the exhaustive
8635        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8636        // detour that routes the trait impl through a divergent projection
8637        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8638        // … }` re-inlining that opens a compile-time link to the un-
8639        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8640        // attribute drift that silently splits the wire byte-string from
8641        // every consumer that reaches for this typed dispatch, an
8642        // accidental swap onto the kebab-case dispatcher-catalog axis the
8643        // pre-existing [`std::str::FromStr`] impl parses through and which
8644        // would collide the two-axis wire/catalog split the sibling
8645        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8646        // trips at caixa-core test time under `assert_eq!` rather than at
8647        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8648        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8649        // carries so no arm's projection is covered only by the sibling
8650        // method-named `from_wire` path. Peer of the sibling
8651        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8652        // (3c83606),
8653        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8654        // (bf33136), and the M3
8655        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8656        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8657        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8658        // surface.
8659        for &variant in RestartStrategy::ALL {
8660            let wire = variant.as_str();
8661            assert_eq!(
8662                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8663                Ok(variant),
8664                "TryFrom<&str> impl on RestartStrategy must round-trip \
8665                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8666                 Ok(RestartStrategy::{variant:?}) — divergence from \
8667                 RestartStrategy::from_wire signals a silent detour off \
8668                 the substrate-primitive accessor"
8669            );
8670            assert_eq!(
8671                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8672                RestartStrategy::from_wire(wire),
8673                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8674                 RestartStrategy::from_wire on the same input"
8675            );
8676        }
8677    }
8678
8679    #[test]
8680    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8681        // Rejection witness on the `impl TryFrom<&str> for
8682        // RestartStrategy` — sweeps a candidate set of byte-strings
8683        // outside the four-arm PascalCase wire accept-set the sibling
8684        // [`RestartStrategy::as_str`] emits and asserts every one lands on
8685        // `Err(())`, so a future accidental widening of the trait impl's
8686        // accept-set (a stray additional
8687        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8688        // path, a silent inclusion of the kebab-case dispatcher-catalog
8689        // byte-string the pre-existing [`std::str::FromStr`] impl the
8690        // [`gen_platform::FromStrKind`] derive installs parses onto the
8691        // wire axis — which would collide the two-axis
8692        // wire/dispatcher-catalog split the sibling
8693        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8694        // an English-rebrand or plural-arm silent alias that would
8695        // widen the wire accept-set past the OTP-canonical four) trips at
8696        // caixa-core test time. The candidate set includes the empty
8697        // string, whitespace-only padding, the kebab-case dispatcher-
8698        // catalog byte-strings on the sibling axis (a caller who confuses
8699        // the two axes trips here rather than at a downstream consumer's
8700        // silent reject), a lowercase / uppercase / mixed-case fold of
8701        // each PascalCase arm (a caller who assumes case-fold acceptance
8702        // trips here), leading/trailing whitespace padding, the trailing-
8703        // newline shape, quote-wrapped candidates, and a residual set of
8704        // plausible-but-wrong English rebrand candidates. Peer of the
8705        // sibling
8706        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8707        // (3c83606) and
8708        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8709        // (6fd00cd) rejection witnesses.
8710        let rejected: &[&str] = &[
8711            "",
8712            " ",
8713            "\n",
8714            "\t",
8715            "one-for-one",
8716            "one-for-all",
8717            "rest-for-one",
8718            "simple-one-for-one",
8719            "oneforone",
8720            "one_for_one",
8721            "OneForOnes",
8722            "ONEFORONE",
8723            "oneforall",
8724            "restforone",
8725            "simpleoneforone",
8726            "OneForOne ",
8727            " OneForOne",
8728            " OneForAll ",
8729            "OneForOne\n",
8730            "RestForOne\t",
8731            "OneForEach",
8732            "AllForOne",
8733            "one for one",
8734            "\"OneForOne\"",
8735            "?",
8736        ];
8737        for &input in rejected {
8738            assert_eq!(
8739                <RestartStrategy as TryFrom<&str>>::try_from(input),
8740                Err(()),
8741                "TryFrom<&str> impl on RestartStrategy must reject the \
8742                 non-wire byte-string {input:?} — silent acceptance signals \
8743                 an accept-set widening off the paired \
8744                 RestartStrategy::from_wire resolver"
8745            );
8746        }
8747    }
8748
8749    #[test]
8750    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8751        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8752        // `from_wire` reverse projections must resolve identically on
8753        // *every* input, not just the ones [`RestartStrategy::ALL`]
8754        // enumerates. Sweeps a mixed candidate set spanning accepted
8755        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8756        // dispatcher-catalog byte-strings, empty, whitespace-padded,
8757        // quoted, English-rebrand candidates) inputs and asserts the
8758        // trait's `Result::ok()` projection byte-equals the method-named
8759        // resolver's `Option<Self>` return-shape on each, locking the two
8760        // paths together by construction so any future detour (a stray
8761        // `try_from` special-case that widens or narrows the accept-set
8762        // outside the paired `from_wire` resolver, an accidental swap
8763        // onto the kebab-case [`std::str::FromStr`] impl the
8764        // [`gen_platform::FromStrKind`] derive installs on the sibling
8765        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8766        // the sibling
8767        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8768        // pin — extends the round-trip discipline onto the M2-OTP-shape
8769        // sibling-restart axis.
8770        let candidates: &[&str] = &[
8771            "OneForOne",
8772            "OneForAll",
8773            "RestForOne",
8774            "SimpleOneForOne",
8775            "",
8776            "one-for-one",
8777            "one-for-all",
8778            "rest-for-one",
8779            "simple-one-for-one",
8780            "oneforone",
8781            "unknown",
8782            "OneForOne ",
8783            " OneForOne",
8784            "\"OneForOne\"",
8785            "OneForEach",
8786            "?",
8787        ];
8788        for &input in candidates {
8789            let via_trait: Option<RestartStrategy> =
8790                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8791            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8792            assert_eq!(
8793                via_trait, via_method,
8794                "TryFrom<&str> and from_wire must resolve identically on \
8795                 input {input:?} — divergence signals the two reverse-\
8796                 projection paths have drifted onto different accept-sets"
8797            );
8798        }
8799    }
8800
8801    #[test]
8802    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8803        // Fail-before-pass-after byte-parity pin on the newly lifted
8804        // `impl From<RestartStrategy> for &'static str` — asserts the
8805        // standard-library trait impl and the substrate-primitive
8806        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8807        // the same four-arm emit-set across every arm the exhaustive
8808        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8809        // detour that routes the trait impl through a divergent
8810        // projection (a per-arm inline `match strategy { OneForOne =>
8811        // "OneForOne", … }` re-inlining that opens a compile-time link to
8812        // the un-lifted arm-literal, an accidental swap onto the sibling
8813        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8814        // would collide the two-axis wire/catalog split the sibling
8815        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8816        // at caixa-core test time under `assert_eq!` rather than at a
8817        // downstream `impl Into<&'static str>`-bound consumer's silent
8818        // split. Sweeps every one of the four arms
8819        // [`RestartStrategy::ALL`] carries so no arm's projection is
8820        // covered only by the sibling method-named `as_str` /
8821        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8822        // `<&'static str as From<RestartStrategy>>::from` output in a
8823        // `const`-shape binding to make the `'static` lifetime promise a
8824        // build-time invariant — a future accidental downgrade of any of
8825        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8826        // constants to a non-`&'static str` (a `String::leak()`-produced
8827        // return, a `Box::leak`-cast) trips at caixa-core build time
8828        // rather than at a downstream `'static`-bound consumer.
8829        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8830        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8831        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8832        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8833        for &variant in RestartStrategy::ALL {
8834            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8835            let via_method: &'static str = variant.as_str();
8836            assert_eq!(
8837                via_trait, via_method,
8838                "From<RestartStrategy> for &'static str impl must round-trip \
8839                 RestartStrategy::{variant:?} to the same lifted \
8840                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8841                 divergence signals a silent detour off the substrate-primitive \
8842                 accessor"
8843            );
8844            let via_into: &'static str = variant.into();
8845            assert_eq!(
8846                via_into, via_method,
8847                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8848                 byte-equal RestartStrategy::as_str on the same input — the \
8849                 blanket-derived Into shape must resolve to the same as_str \
8850                 dispatch as the explicit From impl"
8851            );
8852        }
8853        assert_eq!(
8854            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8855            [
8856                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8857                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8858                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8859                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8860            ],
8861            "const-context RestartStrategy::as_str must resolve to the four \
8862             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8863             downgrade of any arm to a non-const or non-static byte-string \
8864             breaks the `&'static str`-lifetime promise the paired \
8865             From<RestartStrategy> for &'static str impl carries by \
8866             construction"
8867        );
8868    }
8869
8870    #[test]
8871    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8872        // Cross-axis partition pin: the paired trait-idiomatic
8873        // `From<RestartStrategy> for &'static str` forward projection and
8874        // the method-named [`RestartStrategy::as_str`] forward projection
8875        // must resolve identically on *every* arm, not just the ones
8876        // named in the primary byte-parity pin above. Sweeps every
8877        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8878        // output byte-equals the method-named accessor's return-value on
8879        // each, locking the two forward-projection paths together by
8880        // construction so any future detour (a stray `From` special-case
8881        // that lands on a divergent per-arm literal outside the paired
8882        // `as_str` dispatch, a hypothetical rebrand touching one axis
8883        // without the other) trips at caixa-core test time. Peer of the
8884        // sibling reverse-projection partition pin
8885        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8886        // — extends the round-trip discipline onto the trait-idiomatic
8887        // *forward* axis, closing the two-way `Self ↔ &'static str`
8888        // round-trip on the trait-idiomatic pair
8889        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8890        // well as the pre-existing method-named pair
8891        // (`as_str` + `from_wire`).
8892        for &variant in RestartStrategy::ALL {
8893            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8894            let via_method: &'static str = variant.as_str();
8895            assert_eq!(
8896                via_trait, via_method,
8897                "From<RestartStrategy> for &'static str and \
8898                 RestartStrategy::as_str must resolve identically on \
8899                 RestartStrategy::{variant:?} — divergence signals the \
8900                 two forward-projection paths have drifted onto different \
8901                 emit-sets"
8902            );
8903        }
8904        // Round-trip witness: every arm's forward `From` output re-parses
8905        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8906        // to the original variant. Closes the two-way `RestartStrategy ↔
8907        // &'static str` round-trip on the trait-idiomatic axis pair,
8908        // mirroring the pre-existing method-named `as_str` + `from_wire`
8909        // round-trip on the substrate-primitive axis pair.
8910        for &variant in RestartStrategy::ALL {
8911            let emitted: &'static str = variant.into();
8912            let re_parsed: Result<RestartStrategy, ()> =
8913                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8914            assert_eq!(
8915                re_parsed,
8916                Ok(variant),
8917                "trait-idiomatic axis pair must round-trip \
8918                 RestartStrategy::{variant:?} through `.into::<&'static \
8919                 str>()` and back through `TryFrom<&str>` — a break signals \
8920                 the forward-emit and reverse-parse axes have drifted onto \
8921                 different vocabularies"
8922            );
8923        }
8924    }
8925
8926    #[test]
8927    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8928        // Fail-before-pass-after byte-parity pin on the newly lifted
8929        // `impl From<&RestartStrategy> for &'static str` — asserts the
8930        // borrowed-input standard-library trait impl and the substrate-
8931        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8932        // resolve to the same four-arm emit-set across every arm the
8933        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8934        // `From` trait does not auto-derive the borrowed-input sibling
8935        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8936        // where T: Copy, U: From<T>` blanket in `core`), so the
8937        // borrowed-input axis is a distinct trait-idiomatic surface
8938        // that a `.iter().map(Into::into)` shape over
8939        // [`RestartStrategy::ALL`] (whose iterator yields
8940        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8941        // this impl and no other — the paired owned-input
8942        // [`From<RestartStrategy>`] impl requires an explicit
8943        // `.copied()` / dereference before the trait fires.
8944        // Materializes the `<&'static str as
8945        // From<&RestartStrategy>>::from` output in a `const`-shape
8946        // binding to make the `'static` lifetime promise a build-time
8947        // invariant.
8948        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8949        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8950        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8951        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8952        for variant in RestartStrategy::ALL {
8953            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8954            let via_method: &'static str = variant.as_str();
8955            assert_eq!(
8956                via_trait, via_method,
8957                "From<&RestartStrategy> for &'static str impl must \
8958                 round-trip &RestartStrategy::{variant:?} to the same \
8959                 lifted SUPERVISOR_ESTRATEGIA_* const \
8960                 RestartStrategy::as_str returns — divergence signals a \
8961                 silent detour off the substrate-primitive accessor"
8962            );
8963            let via_into: &'static str = variant.into();
8964            assert_eq!(
8965                via_into, via_method,
8966                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8967                 must byte-equal RestartStrategy::as_str on the same input — \
8968                 the blanket-derived Into shape must resolve to the same \
8969                 as_str dispatch as the explicit From impl"
8970            );
8971        }
8972        assert_eq!(
8973            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8974            [
8975                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8976                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8977                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8978                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8979            ],
8980            "const-context RestartStrategy::as_str must resolve to the \
8981             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8982             input From<&RestartStrategy> for &'static str impl inherits \
8983             its `'static` lifetime promise from the same accessor the \
8984             owned-input sibling routes through"
8985        );
8986    }
8987
8988    #[test]
8989    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8990        // Cross-axis partition pin: the paired trait-idiomatic
8991        // owned-input `From<RestartStrategy> for &'static str` (523157d
8992        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8993        // &'static str` (this lift) forward projections must resolve
8994        // identically on every arm, locking the two input-shape paths
8995        // together so any future detour trips at caixa-core test time.
8996        // Then a witness that a `.iter().map(Into::into)` pipe over
8997        // [`RestartStrategy::ALL`] (whose iterator yields
8998        // `&RestartStrategy`) materializes the four-arm accept-set
8999        // through the borrowed-input axis alone — the exact shape a
9000        // future wasm-operator per-supervisor sibling-restart-strategy
9001        // diagnostic line, a future substrate-wide per-arm diagnostic
9002        // column, or a
9003        // `HashMap::<&'static str, RestartStrategy>::from_iter(
9004        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
9005        // per-strategy lookup reaches through — closing the two-way
9006        // owned/borrowed input-shape symmetry on the forward-projection
9007        // trait-idiomatic axis. Peer of the sibling
9008        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9009        // (64aa742) /
9010        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9011        // (5ab993a) /
9012        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9013        // (807b0b5) partition pins on the sibling closed-set typed-enum
9014        // discriminator axes — extends the borrowed-input axis
9015        // discipline onto the first M2 OTP-shape sibling-restart
9016        // closed-set typed enum on the caixa surface. Also closes the
9017        // direct two-way `&Self → &'static str → Self` round-trip via
9018        // the paired [`TryFrom<&str>`] axis — unlike the peer
9019        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
9020        // lowercase Portuguese diagnostic bytes while the reverse
9021        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
9022        // trip through an intermediate wire-vocab hop), the
9023        // [`RestartStrategy::as_str`] emit and
9024        // [`RestartStrategy::from_wire`] parse share the same
9025        // `PascalCase` vocabulary by construction, so the borrowed-
9026        // input forward axis and the reverse axis compose directly.
9027        for &variant in RestartStrategy::ALL {
9028            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9029            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
9030            assert_eq!(
9031                owned, borrowed,
9032                "From<RestartStrategy> and From<&RestartStrategy> for \
9033                 &'static str must resolve identically on \
9034                 RestartStrategy::{variant:?} — divergence signals the \
9035                 owned-input and borrowed-input forward-projection paths \
9036                 have drifted onto different emit-sets"
9037            );
9038        }
9039        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
9040        let via_method: Vec<&'static str> =
9041            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
9042        assert_eq!(
9043            via_iter, via_method,
9044            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
9045             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
9046             borrowed-input `From<&RestartStrategy> for &'static str` \
9047             axis is what makes the `.iter().map(Into::into)` shape route \
9048             through the substrate-primitive `RestartStrategy::as_str` \
9049             accessor rather than through a per-call-site `.copied()` / \
9050             dereference detour"
9051        );
9052        for variant in RestartStrategy::ALL {
9053            let emitted: &'static str = variant.into();
9054            let re_parsed: Result<RestartStrategy, ()> =
9055                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9056            assert_eq!(
9057                re_parsed,
9058                Ok(*variant),
9059                "trait-idiomatic borrowed-input forward-projection + \
9060                 reverse-projection axis pair must round-trip \
9061                 &RestartStrategy::{variant:?} through `.into::<&'static \
9062                 str>()` (via the borrowed-input axis) and back through \
9063                 `TryFrom<&str>` — a break signals the borrowed-input \
9064                 forward-emit and reverse-parse axes have drifted onto \
9065                 different vocabularies"
9066            );
9067        }
9068    }
9069
9070    #[test]
9071    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
9072        // Fail-before-pass-after byte-parity pin on the newly lifted
9073        // `impl From<RestartStrategy> for String` — asserts the
9074        // owned-`String`-returning standard-library trait impl and the
9075        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
9076        // accessor resolve to the same four-arm emit-set across every
9077        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
9078        // Rust's standard library does not carry a blanket
9079        // `impl<T: AsRef<str>> From<T> for String` (nor an
9080        // `impl<T: fmt::Display> From<T> for String`), so the
9081        // owned-`String` forward-projection axis is a distinct
9082        // trait-idiomatic surface that a
9083        // `let key: String = strategy.into();`-shaped call site
9084        // reaches through this impl and no other — the paired sibling
9085        // `From<RestartStrategy> for &'static str` impl forces every
9086        // owned-`String` call site through an explicit
9087        // `.to_owned()` / `String::from` restatement.
9088        for &variant in RestartStrategy::ALL {
9089            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
9090            let via_method: &'static str = variant.as_str();
9091            assert_eq!(
9092                via_trait.as_str(),
9093                via_method,
9094                "From<RestartStrategy> for String impl must round-trip \
9095                 RestartStrategy::{variant:?} to the same lifted \
9096                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9097                 returns — divergence signals a silent detour off the \
9098                 substrate-primitive accessor"
9099            );
9100            let via_into: String = variant.into();
9101            assert_eq!(
9102                via_into.as_str(),
9103                via_method,
9104                "Into<String>::into on RestartStrategy::{variant:?} must \
9105                 byte-equal RestartStrategy::as_str on the same input — the \
9106                 blanket-derived Into shape must resolve to the same as_str \
9107                 dispatch as the explicit From impl"
9108            );
9109        }
9110    }
9111
9112    #[test]
9113    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9114        // Cross-axis partition pin: the paired trait-idiomatic
9115        // owned-`String` `From<RestartStrategy> for String` (this lift)
9116        // and owned-`&'static str` `From<RestartStrategy> for &'static
9117        // str` (523157d) forward projections must resolve identically
9118        // on every arm, locking the two return-type-shape paths
9119        // together so any future detour trips at caixa-core test time.
9120        // Also byte-parity witness against the sibling
9121        // [`ToString::to_string`] surface routed through
9122        // [`std::fmt::Display`] — the three owned-heap-string paths
9123        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9124        // resolve identically on every arm so a future consumer that
9125        // picks any of the three lands on the same lifted
9126        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9127        // witness through the paired trait-idiomatic reverse
9128        // [`TryFrom<&str>`] axis on the owned-`String`'s
9129        // [`String::as_str`] borrow that closes the two-way
9130        // `Self → String → Self` round-trip on the trait-idiomatic
9131        // owned-`String` forward + reverse axis pair.
9132        for &variant in RestartStrategy::ALL {
9133            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9134            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9135            assert_eq!(
9136                owned_string.as_str(),
9137                owned_static,
9138                "From<RestartStrategy> for String and From<RestartStrategy> \
9139                 for &'static str must resolve identically on \
9140                 RestartStrategy::{variant:?} — divergence signals the \
9141                 owned-`String` and owned-`&'static str` forward-projection \
9142                 return-type-shape paths have drifted onto different \
9143                 emit-sets"
9144            );
9145            let via_to_string: String = variant.to_string();
9146            assert_eq!(
9147                owned_string, via_to_string,
9148                "From<RestartStrategy> for String must byte-equal \
9149                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9150                 divergence signals the trait-idiomatic owned-`String` \
9151                 forward-projection axis and the ToString-through-Display \
9152                 axis have drifted onto different emit-sets"
9153            );
9154        }
9155        let via_iter: Vec<String> = RestartStrategy::ALL
9156            .iter()
9157            .copied()
9158            .map(String::from)
9159            .collect();
9160        let via_method: Vec<String> = RestartStrategy::ALL
9161            .iter()
9162            .map(|s| s.as_str().to_owned())
9163            .collect();
9164        assert_eq!(
9165            via_iter, via_method,
9166            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9167             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9168             every arm — the owned-`String` `From<RestartStrategy> for \
9169             String` axis is what makes the `String::from` composition \
9170             route through the substrate-primitive `RestartStrategy::as_str` \
9171             accessor rather than through a per-call-site `.to_owned()` / \
9172             `String::from(strategy.as_str())` detour"
9173        );
9174        for &variant in RestartStrategy::ALL {
9175            let emitted: String = variant.into();
9176            let re_parsed: Result<RestartStrategy, ()> =
9177                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9178            assert_eq!(
9179                re_parsed,
9180                Ok(variant),
9181                "trait-idiomatic owned-`String` forward-projection + \
9182                 reverse-projection axis pair must round-trip \
9183                 RestartStrategy::{variant:?} through `.into::<String>()` \
9184                 and back through `TryFrom<&str>` on the owned-`String`'s \
9185                 String::as_str borrow — a break signals the owned-`String` \
9186                 forward-emit and reverse-parse axes have drifted onto \
9187                 different vocabularies"
9188            );
9189        }
9190    }
9191
9192    #[test]
9193    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9194        // Fail-before-pass-after byte-parity pin on the newly lifted
9195        // `impl From<&RestartStrategy> for String` — asserts the
9196        // borrowed-input owned-`String`-returning standard-library trait
9197        // impl and the substrate-primitive [`RestartStrategy::as_str`]
9198        // `pub const fn` accessor resolve to the same four-arm emit-set
9199        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9200        // enumerates. Rust's standard library does not carry a blanket
9201        // `impl<T: AsRef<str>> From<&T> for String` (nor an
9202        // `impl<T: fmt::Display> From<&T> for String`), so the
9203        // borrowed-input owned-`String` forward-projection axis is a
9204        // distinct trait-idiomatic surface that a
9205        // `let key: String = (&strategy).into();`-shaped call site
9206        // reaches through this impl and no other — the paired sibling
9207        // `From<RestartStrategy> for String` impl forces every
9208        // borrowed-input call site through an explicit `Copy` deref
9209        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9210        // `.to_string()` detour.
9211        for &variant in RestartStrategy::ALL {
9212            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9213            let via_method: &'static str = variant.as_str();
9214            assert_eq!(
9215                via_trait.as_str(),
9216                via_method,
9217                "From<&RestartStrategy> for String impl must round-trip \
9218                 &RestartStrategy::{variant:?} to the same lifted \
9219                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9220                 returns — divergence signals a silent detour off the \
9221                 substrate-primitive accessor"
9222            );
9223            let via_into: String = (&variant).into();
9224            assert_eq!(
9225                via_into.as_str(),
9226                via_method,
9227                "Into<String>::into on &RestartStrategy::{variant:?} must \
9228                 byte-equal RestartStrategy::as_str on the same input — the \
9229                 blanket-derived Into shape must resolve to the same as_str \
9230                 dispatch as the explicit From impl"
9231            );
9232        }
9233    }
9234
9235    #[test]
9236    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9237        // Cross-axis partition pin: the newly lifted trait-idiomatic
9238        // borrowed-input owned-`String` `From<&RestartStrategy> for
9239        // String` (this lift), the paired owned-input owned-`String`
9240        // `From<RestartStrategy> for String` (7baa18a), the paired
9241        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9242        // for &'static str` (e941836), and the paired owned-input
9243        // owned-`&'static str` `From<RestartStrategy> for &'static str`
9244        // (523157d) — every corner of the `{Self, &Self} × {&'static
9245        // str, String}` 2×2 trait-idiomatic projection family — must
9246        // resolve identically on every arm, locking the four
9247        // return-shape × input-shape paths together so any future
9248        // detour trips at caixa-core test time. Also byte-parity
9249        // witness against the sibling [`ToString::to_string`] surface
9250        // routed through [`std::fmt::Display`] and a direct round-trip
9251        // witness through the paired trait-idiomatic reverse
9252        // [`TryFrom<&str>`] axis on the owned-`String`'s
9253        // [`String::as_str`] borrow that closes the two-way
9254        // `&Self → String → Self` round-trip on the trait-idiomatic
9255        // borrowed-input owned-`String` forward + reverse axis pair.
9256        for &variant in RestartStrategy::ALL {
9257            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9258            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9259            let borrowed_static: &'static str =
9260                <&'static str as From<&RestartStrategy>>::from(&variant);
9261            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9262            assert_eq!(
9263                borrowed_string, owned_string,
9264                "From<&RestartStrategy> for String and From<RestartStrategy> \
9265                 for String must resolve identically on \
9266                 RestartStrategy::{variant:?} — divergence signals the \
9267                 borrowed-input and owned-input owned-`String` \
9268                 forward-projection input-shape paths have drifted onto \
9269                 different emit-sets"
9270            );
9271            assert_eq!(
9272                borrowed_string.as_str(),
9273                borrowed_static,
9274                "From<&RestartStrategy> for String and From<&RestartStrategy> \
9275                 for &'static str must resolve identically on \
9276                 RestartStrategy::{variant:?} — divergence signals the \
9277                 borrowed-input `&'static str` and owned-`String` \
9278                 return-shape paths have drifted onto different emit-sets"
9279            );
9280            assert_eq!(
9281                borrowed_string.as_str(),
9282                owned_static,
9283                "From<&RestartStrategy> for String and From<RestartStrategy> \
9284                 for &'static str must resolve identically on \
9285                 RestartStrategy::{variant:?} — divergence signals a break \
9286                 in the diagonal corner of the {{Self, &Self}} × \
9287                 {{&'static str, String}} 2×2 trait-idiomatic \
9288                 projection family"
9289            );
9290            let via_to_string: String = variant.to_string();
9291            assert_eq!(
9292                borrowed_string, via_to_string,
9293                "From<&RestartStrategy> for String must byte-equal \
9294                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9295                 divergence signals the trait-idiomatic borrowed-input \
9296                 owned-`String` forward-projection axis and the \
9297                 ToString-through-Display axis have drifted onto different \
9298                 emit-sets"
9299            );
9300        }
9301        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9302        let via_method: Vec<String> = RestartStrategy::ALL
9303            .iter()
9304            .map(|s| s.as_str().to_owned())
9305            .collect();
9306        assert_eq!(
9307            via_iter, via_method,
9308            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9309             call site whose iteration axis holds `&RestartStrategy` by \
9310             construction — must byte-equal `.iter().map(|s| \
9311             s.as_str().to_owned())` on every arm — the borrowed-input \
9312             owned-`String` `From<&RestartStrategy> for String` axis is \
9313             what makes the `String::from` composition route through the \
9314             substrate-primitive `RestartStrategy::as_str` accessor \
9315             without a spurious `Copy` deref (which would only be \
9316             reachable through the owned-input `From<RestartStrategy> for \
9317             String` axis by first calling `.copied()` on the iterator)"
9318        );
9319        for &variant in RestartStrategy::ALL {
9320            let emitted: String = (&variant).into();
9321            let re_parsed: Result<RestartStrategy, ()> =
9322                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9323            assert_eq!(
9324                re_parsed,
9325                Ok(variant),
9326                "trait-idiomatic borrowed-input owned-`String` \
9327                 forward-projection + reverse-projection axis pair must \
9328                 round-trip &RestartStrategy::{variant:?} through \
9329                 `.into::<String>()` on the borrowed-input surface and \
9330                 back through `TryFrom<&str>` on the owned-`String`'s \
9331                 String::as_str borrow — a break signals the \
9332                 borrowed-input owned-`String` forward-emit and \
9333                 reverse-parse axes have drifted onto different \
9334                 vocabularies"
9335            );
9336        }
9337    }
9338
9339    #[test]
9340    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9341        // Fail-before-pass-after byte-parity pin on the newly lifted
9342        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9343        // asserts the standard-library trait impl and the substrate-
9344        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9345        // accessor resolve to the same four-arm emit-set across every
9346        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9347        // enumerates. Rust's standard library does not carry a blanket
9348        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9349        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9350        // the `Cow<'static, str>` forward-projection axis is a
9351        // distinct trait-idiomatic surface that a
9352        // `let key: Cow<'static, str> = strategy.into();`-shaped call
9353        // site reaches through this impl and no other — the paired
9354        // sibling `From<RestartStrategy> for &'static str` and
9355        // `From<RestartStrategy> for String` impls force every
9356        // `Cow<'static, str>`-parameterized call site through a
9357        // `Cow::Borrowed(strategy.as_str())` /
9358        // `Cow::Owned(strategy.to_string())` composition whose type
9359        // bounds have no compile-time link back to the substrate
9360        // primitive.
9361        //
9362        // Also asserts the projection lands on the zero-alloc
9363        // [`std::borrow::Cow::Borrowed`] arm (not the
9364        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9365        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9366        // return lifetime by construction makes the borrowed arm the
9367        // type-correct projection with no runtime allocation. Any
9368        // future silent detour that routes the impl through the owned
9369        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9370        // that would allocate on every call site where the
9371        // `&'static str` return of [`super::RestartStrategy::as_str`]
9372        // makes the zero-alloc borrowed projection type-correct) trips
9373        // at caixa-core test time under the
9374        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9375        // than at a downstream `Cow<'static, str>`-bound consumer's
9376        // silent allocation.
9377        //
9378        // First peer on the substrate-wide trait-idiomatic
9379        // [`std::borrow::Cow<'static, str>`] forward-projection family
9380        // to extend the axis off the top-level [`super::CaixaKind`]
9381        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9382        // first M2 OTP-shape closed-set fieldless typed enum on the
9383        // caixa surface.
9384        for &variant in RestartStrategy::ALL {
9385            let via_trait: std::borrow::Cow<'static, str> =
9386                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9387            let via_method: &'static str = variant.as_str();
9388            assert_eq!(
9389                via_trait.as_ref(),
9390                via_method,
9391                "From<RestartStrategy> for Cow<'static, str> impl must \
9392                 round-trip RestartStrategy::{variant:?} to the same \
9393                 lifted SUPERVISOR_ESTRATEGIA_* const \
9394                 RestartStrategy::as_str returns — divergence signals a \
9395                 silent detour off the substrate-primitive accessor"
9396            );
9397            assert!(
9398                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9399                "From<RestartStrategy> for Cow<'static, str> impl must \
9400                 land on the zero-alloc Cow::Borrowed arm on \
9401                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9402                 signals the projection has silently allocated where \
9403                 the substrate-primitive RestartStrategy::as_str \
9404                 `&'static str` return makes the borrowed arm the \
9405                 type-correct projection"
9406            );
9407            let via_into: std::borrow::Cow<'static, str> = variant.into();
9408            assert_eq!(
9409                via_into.as_ref(),
9410                via_method,
9411                "Into<Cow<'static, str>>::into on \
9412                 RestartStrategy::{variant:?} must byte-equal \
9413                 RestartStrategy::as_str on the same input — the \
9414                 blanket-derived Into shape must resolve to the same \
9415                 as_str dispatch as the explicit From impl"
9416            );
9417            assert!(
9418                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9419                "Into<Cow<'static, str>>::into on \
9420                 RestartStrategy::{variant:?} must land on the \
9421                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9422                 Into shape must resolve to the same Cow::Borrowed \
9423                 dispatch as the explicit From impl"
9424            );
9425        }
9426    }
9427
9428    #[test]
9429    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9430        // Cross-axis partition pin: the newly lifted trait-idiomatic
9431        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9432        // (this lift), the paired owned-input `From<RestartStrategy>
9433        // for &'static str` (523157d), and the paired owned-input
9434        // `From<RestartStrategy> for String` (7baa18a) forward
9435        // projections must resolve identically on every arm, locking
9436        // the three return-shape paths together by construction so any
9437        // future detour trips at caixa-core test time. Also byte-parity
9438        // witness against the sibling [`ToString::to_string`] surface
9439        // routed through [`std::fmt::Display`] — every owned-heap-
9440        // string path (the `Cow::Owned` promotion of this axis's
9441        // `.into_owned()`, `From<RestartStrategy> for String`, and
9442        // `.to_string()`) resolves to the same lifted
9443        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9444        //
9445        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9446        // witness over [`super::RestartStrategy::ALL`] that
9447        // materializes the four-arm accept-set through the
9448        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9449        // shape a future `axum::response::IntoResponse` per-strategy
9450        // rejection-body composer, a future M4 admission-webhook
9451        // per-strategy rejection-reason emitter whose typing rules out
9452        // the sibling [`AsRef<str>`] borrowed return, or a future
9453        // substrate-wide per-strategy diagnostic surface that binds
9454        // through a [`Cow<'static, str>`] boundary reaches through.
9455        // The pipe witness also pins the zero-alloc discipline: every
9456        // element in the collected vector satisfies the
9457        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9458        // accidental silent-allocation regression on the pipe's
9459        // iteration axis is a caixa-core-test-time failure.
9460        for &variant in RestartStrategy::ALL {
9461            let via_cow: std::borrow::Cow<'static, str> =
9462                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9463            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9464            let via_string: String = <String as From<RestartStrategy>>::from(variant);
9465            assert_eq!(
9466                via_cow.as_ref(),
9467                via_static,
9468                "From<RestartStrategy> for Cow<'static, str> and \
9469                 From<RestartStrategy> for &'static str must resolve \
9470                 identically on RestartStrategy::{variant:?} — \
9471                 divergence signals the Cow<'static, str> and \
9472                 &'static str return-shape paths have drifted onto \
9473                 different emit-sets"
9474            );
9475            assert_eq!(
9476                via_cow.as_ref(),
9477                via_string.as_str(),
9478                "From<RestartStrategy> for Cow<'static, str> and \
9479                 From<RestartStrategy> for String must resolve \
9480                 identically on RestartStrategy::{variant:?} — \
9481                 divergence signals the Cow<'static, str> and String \
9482                 return-shape paths have drifted onto different \
9483                 emit-sets"
9484            );
9485            let via_to_string: String = variant.to_string();
9486            assert_eq!(
9487                via_cow.as_ref(),
9488                via_to_string.as_str(),
9489                "From<RestartStrategy> for Cow<'static, str> must \
9490                 byte-equal RestartStrategy::to_string on \
9491                 RestartStrategy::{variant:?} — divergence signals the \
9492                 trait-idiomatic Cow<'static, str> forward-projection \
9493                 axis and the ToString-through-Display axis have \
9494                 drifted onto different emit-sets"
9495            );
9496        }
9497        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9498            .iter()
9499            .copied()
9500            .map(std::borrow::Cow::from)
9501            .collect();
9502        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9503            .iter()
9504            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9505            .collect();
9506        assert_eq!(
9507            via_iter, via_method,
9508            "`.iter().copied().map(Cow::from)` over \
9509             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9510             Cow::Borrowed(s.as_str()))` on every arm — the \
9511             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9512             str>` axis is what makes the `Cow::from` composition \
9513             route through the substrate-primitive \
9514             `RestartStrategy::as_str` accessor with the zero-alloc \
9515             Cow::Borrowed arm by construction, rather than a \
9516             per-call-site `Cow::Owned(strategy.to_string())` \
9517             allocation"
9518        );
9519        for cow in &via_iter {
9520            assert!(
9521                matches!(cow, std::borrow::Cow::Borrowed(_)),
9522                "every element of the \
9523                 .iter().copied().map(Cow::from) pipe over \
9524                 RestartStrategy::ALL must land on the zero-alloc \
9525                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9526                 signals the pipe's iteration axis has silently \
9527                 allocated where the substrate-primitive \
9528                 RestartStrategy::as_str `&'static str` return makes \
9529                 the borrowed arm the type-correct projection"
9530            );
9531        }
9532    }
9533
9534    #[test]
9535    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9536        // Fail-before-pass-after byte-parity pin on the newly lifted
9537        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9538        // asserts the borrowed-input standard-library trait impl and
9539        // the substrate-primitive [`super::RestartStrategy::as_str`]
9540        // `pub const fn` accessor resolve to the same four-arm emit-
9541        // set across every arm the exhaustive
9542        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9543        // standard library does not carry a blanket
9544        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9545        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9546        // the borrowed-input `Cow<'static, str>` forward-projection
9547        // axis is a distinct trait-idiomatic surface that a
9548        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9549        // call site or a
9550        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9551        // reaches through this impl and no other — the paired owned-
9552        // input `From<RestartStrategy> for Cow<'static, str>` impl
9553        // (7dd28b3) forces every borrowed-input call site through an
9554        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9555        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9556        // bounds have no compile-time link back to the substrate
9557        // primitive.
9558        //
9559        // Also asserts the projection lands on the zero-alloc
9560        // [`std::borrow::Cow::Borrowed`] arm (not the
9561        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9562        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9563        // return lifetime by construction makes the borrowed arm the
9564        // type-correct projection with no runtime allocation on the
9565        // borrowed-input surface just as on the paired owned-input
9566        // surface.
9567        //
9568        // Second peer on the substrate-wide trait-idiomatic
9569        // [`std::borrow::Cow<'static, str>`] forward-projection family
9570        // on this enum — closes the `{Self, &Self}` input-shape
9571        // corner of the [`Cow<'static, str>`] axis on the first M2
9572        // OTP-shape closed-set fieldless typed enum peer on the caixa
9573        // surface (`:supervisor :estrategia`), exactly as d45c409
9574        // closed it on the top-level [`super::CaixaKind`] one commit
9575        // after the owning half (99c1735) landed. Every future
9576        // closed-set fieldless typed enum peer on the substrate is a
9577        // future target of the campaign.
9578        for &variant in RestartStrategy::ALL {
9579            let via_trait: std::borrow::Cow<'static, str> =
9580                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9581            let via_method: &'static str = variant.as_str();
9582            assert_eq!(
9583                via_trait.as_ref(),
9584                via_method,
9585                "From<&RestartStrategy> for Cow<'static, str> impl must \
9586                 round-trip &RestartStrategy::{variant:?} to the same \
9587                 lifted SUPERVISOR_ESTRATEGIA_* const \
9588                 RestartStrategy::as_str returns — divergence signals a \
9589                 silent detour off the substrate-primitive accessor"
9590            );
9591            assert!(
9592                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9593                "From<&RestartStrategy> for Cow<'static, str> impl must \
9594                 land on the zero-alloc Cow::Borrowed arm on \
9595                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9596                 signals the projection has silently allocated where \
9597                 the substrate-primitive RestartStrategy::as_str \
9598                 `&'static str` return makes the borrowed arm the \
9599                 type-correct projection"
9600            );
9601            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9602            assert_eq!(
9603                via_into.as_ref(),
9604                via_method,
9605                "Into<Cow<'static, str>>::into on \
9606                 &RestartStrategy::{variant:?} must byte-equal \
9607                 RestartStrategy::as_str on the same input — the \
9608                 blanket-derived Into shape must resolve to the same \
9609                 as_str dispatch as the explicit From impl"
9610            );
9611            assert!(
9612                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9613                "Into<Cow<'static, str>>::into on \
9614                 &RestartStrategy::{variant:?} must land on the \
9615                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9616                 Into shape must resolve to the same Cow::Borrowed \
9617                 dispatch as the explicit From impl"
9618            );
9619        }
9620    }
9621
9622    #[test]
9623    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9624        // Cross-axis partition pin: the newly lifted trait-idiomatic
9625        // borrowed-input `From<&RestartStrategy> for
9626        // std::borrow::Cow<'static, str>` (this lift), the paired
9627        // owned-input `From<RestartStrategy> for
9628        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9629        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9630        // for &'static str`, and the paired borrowed-input owned-
9631        // `String` `From<&RestartStrategy> for String` must resolve
9632        // identically on every arm, locking the four
9633        // return-shape × input-shape paths together by construction so
9634        // any future detour trips at caixa-core test time. Also byte-
9635        // parity witness against the sibling [`ToString::to_string`]
9636        // surface routed through [`std::fmt::Display`] — every owned-
9637        // heap-string path (this axis's `.into_owned()` promotion, the
9638        // paired [`From<&RestartStrategy> for String`], and
9639        // `.to_string()`) resolves to the same lifted
9640        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9641        //
9642        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9643        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9644        // `&RestartStrategy` by construction, so the borrowed-input
9645        // [`Cow<'static, str>`] axis is what routes the pipe through
9646        // the substrate-primitive [`super::RestartStrategy::as_str`]
9647        // accessor without a spurious [`Copy`] deref (which would only
9648        // be reachable through the owned-input
9649        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9650        // first calling `.copied()` on the iterator). The pipe witness
9651        // also pins the zero-alloc discipline: every element in the
9652        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9653        // arm predicate, so a future accidental silent-allocation
9654        // regression on the pipe's iteration axis is a caixa-core-
9655        // test-time failure.
9656        for &strategy in RestartStrategy::ALL {
9657            let borrowed_cow: std::borrow::Cow<'static, str> =
9658                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9659            let owned_cow: std::borrow::Cow<'static, str> =
9660                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9661            let borrowed_static: &'static str =
9662                <&'static str as From<&RestartStrategy>>::from(&strategy);
9663            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9664            assert_eq!(
9665                borrowed_cow, owned_cow,
9666                "From<&RestartStrategy> for Cow<'static, str> and \
9667                 From<RestartStrategy> for Cow<'static, str> must \
9668                 resolve identically on RestartStrategy::{strategy:?} — \
9669                 divergence signals the borrowed-input and owned-input \
9670                 Cow<'static, str> forward-projection input-shape \
9671                 paths have drifted onto different emit-sets"
9672            );
9673            assert_eq!(
9674                borrowed_cow.as_ref(),
9675                borrowed_static,
9676                "From<&RestartStrategy> for Cow<'static, str> and \
9677                 From<&RestartStrategy> for &'static str must resolve \
9678                 identically on RestartStrategy::{strategy:?} — \
9679                 divergence signals the borrowed-input Cow<'static, \
9680                 str> and &'static str return-shape paths have drifted \
9681                 onto different emit-sets"
9682            );
9683            assert_eq!(
9684                borrowed_cow.as_ref(),
9685                borrowed_string.as_str(),
9686                "From<&RestartStrategy> for Cow<'static, str> and \
9687                 From<&RestartStrategy> for String must resolve \
9688                 identically on RestartStrategy::{strategy:?} — \
9689                 divergence signals the borrowed-input Cow<'static, \
9690                 str> and owned-`String` return-shape paths have \
9691                 drifted onto different emit-sets"
9692            );
9693            let via_to_string: String = strategy.to_string();
9694            assert_eq!(
9695                borrowed_cow.as_ref(),
9696                via_to_string.as_str(),
9697                "From<&RestartStrategy> for Cow<'static, str> must \
9698                 byte-equal RestartStrategy::to_string on \
9699                 RestartStrategy::{strategy:?} — divergence signals \
9700                 the trait-idiomatic borrowed-input Cow<'static, str> \
9701                 forward-projection axis and the ToString-through-\
9702                 Display axis have drifted onto different emit-sets"
9703            );
9704        }
9705        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9706            .iter()
9707            .map(std::borrow::Cow::from)
9708            .collect();
9709        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9710            .iter()
9711            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9712            .collect();
9713        assert_eq!(
9714            via_iter, via_method,
9715            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9716             call site whose iteration axis holds `&RestartStrategy` \
9717             by construction — must byte-equal `.iter().map(|s| \
9718             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9719             input Cow<'static, str> `From<&RestartStrategy> for \
9720             Cow<'static, str>` axis is what makes the `Cow::from` \
9721             composition route through the substrate-primitive \
9722             `RestartStrategy::as_str` accessor with the zero-alloc \
9723             Cow::Borrowed arm by construction and without a spurious \
9724             `Copy` deref (which would only be reachable through the \
9725             owned-input `From<RestartStrategy> for Cow<'static, str>` \
9726             axis by first calling `.copied()` on the iterator)"
9727        );
9728        for cow in &via_iter {
9729            assert!(
9730                matches!(cow, std::borrow::Cow::Borrowed(_)),
9731                "every element of the .iter().map(Cow::from) pipe \
9732                 over RestartStrategy::ALL must land on the zero-\
9733                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9734                 any arm signals the pipe's iteration axis has \
9735                 silently allocated where the substrate-primitive \
9736                 RestartStrategy::as_str `&'static str` return makes \
9737                 the borrowed arm the type-correct projection"
9738            );
9739        }
9740    }
9741
9742    #[test]
9743    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9744        // Fail-before-pass-after byte-parity pin on the newly lifted
9745        // `impl From<RestartStrategy> for Box<str>` — asserts the
9746        // owned-input standard-library trait impl and the
9747        // substrate-primitive [`super::RestartStrategy::as_str`]
9748        // `pub const fn` accessor resolve to the same four-arm emit-
9749        // set across every arm the exhaustive
9750        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9751        // substrate-wide `Box<str>` forward-projection campaign tier
9752        // on the first M2 OTP-shape closed-set fieldless typed enum
9753        // peer on the caixa surface (`:supervisor :estrategia`),
9754        // immediately after the paired `Cow<'static, str>` axis
9755        // (7dd28b3 / ee577fd) closed the
9756        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9757        // 2×3 corner on this enum. Rust's standard library carries
9758        // `impl From<&str> for Box<str>` and
9759        // `impl From<String> for Box<str>` but no blanket
9760        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9761        // a distinct trait-idiomatic surface that a
9762        // `let key: Box<str> = strategy.into();`-shaped call site
9763        // reaches through this impl and no other — a paired
9764        // `Box::from(strategy.as_str())` open-code has no compile-
9765        // time link back to the substrate primitive.
9766        for &variant in RestartStrategy::ALL {
9767            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9768            let via_method: &'static str = variant.as_str();
9769            assert_eq!(
9770                via_trait.as_ref(),
9771                via_method,
9772                "From<RestartStrategy> for Box<str> impl must round-\
9773                 trip RestartStrategy::{variant:?} to the same lifted \
9774                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9775                 returns — divergence signals a silent detour off the \
9776                 substrate-primitive accessor"
9777            );
9778            let via_into: Box<str> = variant.into();
9779            assert_eq!(
9780                via_into.as_ref(),
9781                via_method,
9782                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9783                 must byte-equal RestartStrategy::as_str on the same \
9784                 input — the blanket-derived Into shape must resolve \
9785                 to the same as_str dispatch as the explicit From impl"
9786            );
9787        }
9788    }
9789
9790    #[test]
9791    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9792        // Fail-before-pass-after byte-parity pin on the newly lifted
9793        // `impl From<&RestartStrategy> for Box<str>` — asserts the
9794        // borrowed-input standard-library trait impl and the
9795        // substrate-primitive [`super::RestartStrategy::as_str`]
9796        // `pub const fn` accessor resolve to the same four-arm emit-
9797        // set across every arm the exhaustive
9798        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9799        // standard library does not carry a blanket
9800        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9801        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9802        // so the borrowed-input `Box<str>` forward-projection axis
9803        // is a distinct trait-idiomatic surface that a
9804        // `let key: Box<str> = (&strategy).into();`-shaped call site
9805        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9806        // shaped pipe reaches through this impl and no other — the
9807        // paired owned-input `From<RestartStrategy> for Box<str>`
9808        // impl (69ef45c) forces every borrowed-input call site
9809        // through an explicit `Copy` deref
9810        // (`Box::<str>::from((*strategy).as_str())`) or a
9811        // `Box::<str>::from(strategy.as_str())` open-code whose
9812        // type bounds have no compile-time link back to the
9813        // substrate primitive.
9814        //
9815        // Second peer on the substrate-wide trait-idiomatic
9816        // [`Box<str>`] forward-projection family on this enum —
9817        // closes the `{Self, &Self}` input-shape corner of the
9818        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9819        // fieldless typed enum peer on the caixa surface
9820        // (`:supervisor :estrategia`), exactly as ee577fd closed
9821        // the paired [`Cow<'static, str>`] axis one commit after
9822        // its owning half (7dd28b3) landed. Every future closed-
9823        // set fieldless typed enum peer on the substrate is a
9824        // future target of the campaign.
9825        //
9826        // Also byte-parity witness against the paired owned-input
9827        // [`From<RestartStrategy> for Box<str>`] and the sibling
9828        // borrowed-input [`From<&RestartStrategy> for &'static str`],
9829        // [`From<&RestartStrategy> for String`], and
9830        // [`From<&RestartStrategy> for Cow<'static, str>`]
9831        // return-shape axes — locking the four
9832        // return-shape × input-shape paths together by construction
9833        // so any future detour trips at caixa-core test time. Then a
9834        // `.iter().map(Box::<str>::from)` pipe witness over
9835        // [`super::RestartStrategy::ALL`] — whose iterator yields
9836        // `&RestartStrategy` by construction, so the borrowed-input
9837        // [`Box<str>`] axis is what routes the pipe through the
9838        // substrate-primitive [`super::RestartStrategy::as_str`]
9839        // accessor without a spurious [`Copy`] deref (which would
9840        // only be reachable through the owned-input
9841        // [`From<RestartStrategy> for Box<str>`] axis by first
9842        // calling `.copied()` on the iterator).
9843        for &variant in RestartStrategy::ALL {
9844            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9845            let via_method: &'static str = variant.as_str();
9846            assert_eq!(
9847                via_trait.as_ref(),
9848                via_method,
9849                "From<&RestartStrategy> for Box<str> impl must \
9850                 round-trip &RestartStrategy::{variant:?} to the same \
9851                 lifted SUPERVISOR_ESTRATEGIA_* const \
9852                 RestartStrategy::as_str returns — divergence signals \
9853                 a silent detour off the substrate-primitive accessor"
9854            );
9855            let via_into: Box<str> = (&variant).into();
9856            assert_eq!(
9857                via_into.as_ref(),
9858                via_method,
9859                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9860                 must byte-equal RestartStrategy::as_str on the same \
9861                 input — the blanket-derived Into shape must resolve \
9862                 to the same as_str dispatch as the explicit From impl"
9863            );
9864            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9865            assert_eq!(
9866                via_trait, owned_box,
9867                "From<&RestartStrategy> for Box<str> and \
9868                 From<RestartStrategy> for Box<str> must resolve \
9869                 identically on RestartStrategy::{variant:?} — \
9870                 divergence signals the borrowed-input and owned-input \
9871                 Box<str> forward-projection input-shape paths have \
9872                 drifted onto different emit-sets"
9873            );
9874            let borrowed_static: &'static str =
9875                <&'static str as From<&RestartStrategy>>::from(&variant);
9876            assert_eq!(
9877                via_trait.as_ref(),
9878                borrowed_static,
9879                "From<&RestartStrategy> for Box<str> and \
9880                 From<&RestartStrategy> for &'static str must resolve \
9881                 identically on RestartStrategy::{variant:?} — \
9882                 divergence signals the borrowed-input Box<str> and \
9883                 &'static str return-shape paths have drifted onto \
9884                 different emit-sets"
9885            );
9886            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9887            assert_eq!(
9888                via_trait.as_ref(),
9889                borrowed_string.as_str(),
9890                "From<&RestartStrategy> for Box<str> and \
9891                 From<&RestartStrategy> for String must resolve \
9892                 identically on RestartStrategy::{variant:?} — \
9893                 divergence signals the borrowed-input Box<str> and \
9894                 owned-`String` return-shape paths have drifted onto \
9895                 different emit-sets"
9896            );
9897            let borrowed_cow: std::borrow::Cow<'static, str> =
9898                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9899            assert_eq!(
9900                via_trait.as_ref(),
9901                borrowed_cow.as_ref(),
9902                "From<&RestartStrategy> for Box<str> and \
9903                 From<&RestartStrategy> for Cow<'static, str> must \
9904                 resolve identically on RestartStrategy::{variant:?} — \
9905                 divergence signals the borrowed-input Box<str> and \
9906                 Cow<'static, str> return-shape paths have drifted \
9907                 onto different emit-sets"
9908            );
9909        }
9910        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9911        let via_method: Vec<Box<str>> = RestartStrategy::ALL
9912            .iter()
9913            .map(|s| Box::<str>::from(s.as_str()))
9914            .collect();
9915        assert_eq!(
9916            via_iter, via_method,
9917            "`.iter().map(Box::<str>::from)` over \
9918             RestartStrategy::ALL — a call site whose iteration axis \
9919             holds `&RestartStrategy` by construction — must byte-\
9920             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9921             on every arm — the borrowed-input Box<str> \
9922             `From<&RestartStrategy> for Box<str>` axis is what \
9923             makes the `Box::<str>::from` composition route through \
9924             the substrate-primitive `RestartStrategy::as_str` \
9925             accessor without a spurious `Copy` deref (which would \
9926             only be reachable through the owned-input \
9927             `From<RestartStrategy> for Box<str>` axis by first \
9928             calling `.copied()` on the iterator)"
9929        );
9930    }
9931
9932    #[test]
9933    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9934        // Fail-before-pass-after byte-parity pin on the newly lifted
9935        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9936        // the owned-input standard-library trait impl and the
9937        // substrate-primitive [`super::RestartStrategy::as_str`]
9938        // `pub const fn` accessor resolve to the same four-arm emit-
9939        // set across every arm the exhaustive
9940        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9941        // substrate-wide [`std::sync::Arc<str>`] forward-projection
9942        // campaign tier on the first M2 OTP-shape closed-set fieldless
9943        // typed enum peer on the caixa surface
9944        // (`:supervisor :estrategia`), immediately after the paired
9945        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9946        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9947        // Box<str>}` 2×4 corner on this enum. Rust's standard library
9948        // carries `impl From<&str> for std::sync::Arc<str>` and
9949        // `impl From<String> for std::sync::Arc<str>` but no blanket
9950        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9951        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9952        // so this axis is a distinct trait-idiomatic surface that a
9953        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9954        // site reaches through this impl and no other — a paired
9955        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9956        // has no compile-time link back to the substrate primitive,
9957        // and a two-step `std::sync::Arc::<str>::from(String::from(
9958        // strategy))` composition through the owned-`String` axis
9959        // allocates twice (once into the intermediate `String`, once
9960        // into the [`Arc<str>`] on the `From<String>` conversion)
9961        // where the single-step trait impl allocates once.
9962        //
9963        // Cross-axis byte-parity witness against the sibling owned-
9964        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9965        // return-shape axes — locking the five return-shape paths on
9966        // the owned-input surface together by construction so any
9967        // future detour off the substrate-primitive
9968        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9969        // core test time.
9970        for &variant in RestartStrategy::ALL {
9971            let via_trait: std::sync::Arc<str> =
9972                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9973            let via_method: &'static str = variant.as_str();
9974            assert_eq!(
9975                via_trait.as_ref(),
9976                via_method,
9977                "From<RestartStrategy> for std::sync::Arc<str> impl \
9978                 must round-trip RestartStrategy::{variant:?} to the \
9979                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9980                 RestartStrategy::as_str returns — divergence signals \
9981                 a silent detour off the substrate-primitive accessor"
9982            );
9983            let via_into: std::sync::Arc<str> = variant.into();
9984            assert_eq!(
9985                via_into.as_ref(),
9986                via_method,
9987                "Into<std::sync::Arc<str>>::into on \
9988                 RestartStrategy::{variant:?} must byte-equal \
9989                 RestartStrategy::as_str on the same input — the \
9990                 blanket-derived Into shape must resolve to the same \
9991                 as_str dispatch as the explicit From impl"
9992            );
9993            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9994            assert_eq!(
9995                via_trait.as_ref(),
9996                owned_static,
9997                "From<RestartStrategy> for std::sync::Arc<str> and \
9998                 From<RestartStrategy> for &'static str must resolve \
9999                 identically on RestartStrategy::{variant:?} — \
10000                 divergence signals the owned-input std::sync::Arc<str> \
10001                 and &'static str return-shape paths have drifted onto \
10002                 different emit-sets"
10003            );
10004            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10005            assert_eq!(
10006                via_trait.as_ref(),
10007                owned_string.as_str(),
10008                "From<RestartStrategy> for std::sync::Arc<str> and \
10009                 From<RestartStrategy> for String must resolve \
10010                 identically on RestartStrategy::{variant:?} — \
10011                 divergence signals the owned-input std::sync::Arc<str> \
10012                 and owned-`String` return-shape paths have drifted \
10013                 onto different emit-sets"
10014            );
10015            let owned_cow: std::borrow::Cow<'static, str> =
10016                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10017            assert_eq!(
10018                via_trait.as_ref(),
10019                owned_cow.as_ref(),
10020                "From<RestartStrategy> for std::sync::Arc<str> and \
10021                 From<RestartStrategy> for Cow<'static, str> must \
10022                 resolve identically on RestartStrategy::{variant:?} — \
10023                 divergence signals the owned-input std::sync::Arc<str> \
10024                 and Cow<'static, str> return-shape paths have drifted \
10025                 onto different emit-sets"
10026            );
10027            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10028            assert_eq!(
10029                via_trait.as_ref(),
10030                owned_box.as_ref(),
10031                "From<RestartStrategy> for std::sync::Arc<str> and \
10032                 From<RestartStrategy> for Box<str> must resolve \
10033                 identically on RestartStrategy::{variant:?} — \
10034                 divergence signals the owned-input std::sync::Arc<str> \
10035                 and Box<str> return-shape paths have drifted onto \
10036                 different emit-sets"
10037            );
10038        }
10039    }
10040
10041    #[test]
10042    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
10043        // Fail-before-pass-after byte-parity pin on the newly lifted
10044        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
10045        // asserts the borrowed-input standard-library trait impl and
10046        // the substrate-primitive [`super::RestartStrategy::as_str`]
10047        // `pub const fn` accessor resolve to the same four-arm emit-
10048        // set across every arm the exhaustive
10049        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10050        // standard library does not carry a blanket
10051        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
10052        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10053        // so the borrowed-input [`std::sync::Arc<str>`] forward-
10054        // projection axis is a distinct trait-idiomatic surface that a
10055        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
10056        // call site or a
10057        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
10058        // shaped pipe reaches through this impl and no other — the
10059        // paired owned-input
10060        // `From<RestartStrategy> for std::sync::Arc<str>` impl
10061        // (bca2ec8) forces every borrowed-input call site through an
10062        // explicit `Copy` deref
10063        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
10064        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10065        // whose type bounds have no compile-time link back to the
10066        // substrate primitive.
10067        //
10068        // Second peer on the substrate-wide trait-idiomatic
10069        // [`std::sync::Arc<str>`] forward-projection family on this
10070        // enum — closes the `{Self, &Self}` input-shape corner of
10071        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
10072        // closed-set fieldless typed enum peer on the caixa surface
10073        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
10074        // paired [`Box<str>`] axis one commit after its owning half
10075        // (69ef45c) landed. Every future closed-set fieldless typed
10076        // enum peer on the substrate is a future target of the
10077        // campaign.
10078        //
10079        // Also byte-parity witness against the paired owned-input
10080        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
10081        // sibling borrowed-input
10082        // [`From<&RestartStrategy> for &'static str`],
10083        // [`From<&RestartStrategy> for String`],
10084        // [`From<&RestartStrategy> for Cow<'static, str>`], and
10085        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
10086        // locking the five return-shape × input-shape paths together
10087        // by construction so any future detour trips at caixa-core
10088        // test time. Then a
10089        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
10090        // [`super::RestartStrategy::ALL`] — whose iterator yields
10091        // `&RestartStrategy` by construction, so the borrowed-input
10092        // [`std::sync::Arc<str>`] axis is what routes the pipe
10093        // through the substrate-primitive
10094        // [`super::RestartStrategy::as_str`] accessor without a
10095        // spurious [`Copy`] deref (which would only be reachable
10096        // through the owned-input
10097        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
10098        // first calling `.copied()` on the iterator).
10099        for &variant in RestartStrategy::ALL {
10100            let via_trait: std::sync::Arc<str> =
10101                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10102            let via_method: &'static str = variant.as_str();
10103            assert_eq!(
10104                via_trait.as_ref(),
10105                via_method,
10106                "From<&RestartStrategy> for std::sync::Arc<str> impl \
10107                 must round-trip &RestartStrategy::{variant:?} to the \
10108                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10109                 RestartStrategy::as_str returns — divergence signals \
10110                 a silent detour off the substrate-primitive accessor"
10111            );
10112            let via_into: std::sync::Arc<str> = (&variant).into();
10113            assert_eq!(
10114                via_into.as_ref(),
10115                via_method,
10116                "Into<std::sync::Arc<str>>::into on \
10117                 &RestartStrategy::{variant:?} must byte-equal \
10118                 RestartStrategy::as_str on the same input — the \
10119                 blanket-derived Into shape must resolve to the same \
10120                 as_str dispatch as the explicit From impl"
10121            );
10122            let owned_arc: std::sync::Arc<str> =
10123                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10124            assert_eq!(
10125                via_trait, owned_arc,
10126                "From<&RestartStrategy> for std::sync::Arc<str> and \
10127                 From<RestartStrategy> for std::sync::Arc<str> must \
10128                 resolve identically on RestartStrategy::{variant:?} — \
10129                 divergence signals the borrowed-input and owned-input \
10130                 std::sync::Arc<str> forward-projection input-shape \
10131                 paths have drifted onto different emit-sets"
10132            );
10133            let borrowed_static: &'static str =
10134                <&'static str as From<&RestartStrategy>>::from(&variant);
10135            assert_eq!(
10136                via_trait.as_ref(),
10137                borrowed_static,
10138                "From<&RestartStrategy> for std::sync::Arc<str> and \
10139                 From<&RestartStrategy> for &'static str must resolve \
10140                 identically on RestartStrategy::{variant:?} — \
10141                 divergence signals the borrowed-input \
10142                 std::sync::Arc<str> and &'static str return-shape \
10143                 paths have drifted onto different emit-sets"
10144            );
10145            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10146            assert_eq!(
10147                via_trait.as_ref(),
10148                borrowed_string.as_str(),
10149                "From<&RestartStrategy> for std::sync::Arc<str> and \
10150                 From<&RestartStrategy> for String must resolve \
10151                 identically on RestartStrategy::{variant:?} — \
10152                 divergence signals the borrowed-input \
10153                 std::sync::Arc<str> and owned-`String` return-shape \
10154                 paths have drifted onto different emit-sets"
10155            );
10156            let borrowed_cow: std::borrow::Cow<'static, str> =
10157                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10158            assert_eq!(
10159                via_trait.as_ref(),
10160                borrowed_cow.as_ref(),
10161                "From<&RestartStrategy> for std::sync::Arc<str> and \
10162                 From<&RestartStrategy> for Cow<'static, str> must \
10163                 resolve identically on RestartStrategy::{variant:?} — \
10164                 divergence signals the borrowed-input \
10165                 std::sync::Arc<str> and Cow<'static, str> return-shape \
10166                 paths have drifted onto different emit-sets"
10167            );
10168            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10169            assert_eq!(
10170                via_trait.as_ref(),
10171                borrowed_box.as_ref(),
10172                "From<&RestartStrategy> for std::sync::Arc<str> and \
10173                 From<&RestartStrategy> for Box<str> must resolve \
10174                 identically on RestartStrategy::{variant:?} — \
10175                 divergence signals the borrowed-input \
10176                 std::sync::Arc<str> and Box<str> return-shape paths \
10177                 have drifted onto different emit-sets"
10178            );
10179        }
10180        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10181            .iter()
10182            .map(std::sync::Arc::<str>::from)
10183            .collect();
10184        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10185            .iter()
10186            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10187            .collect();
10188        assert_eq!(
10189            via_iter, via_method,
10190            "`.iter().map(std::sync::Arc::<str>::from)` over \
10191             RestartStrategy::ALL — a call site whose iteration axis \
10192             holds `&RestartStrategy` by construction — must byte-\
10193             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10194             on every arm — the borrowed-input std::sync::Arc<str> \
10195             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10196             what makes the `std::sync::Arc::<str>::from` composition \
10197             route through the substrate-primitive \
10198             `RestartStrategy::as_str` accessor without a spurious \
10199             `Copy` deref (which would only be reachable through the \
10200             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10201             axis by first calling `.copied()` on the iterator)"
10202        );
10203    }
10204
10205    #[test]
10206    #[allow(
10207        clippy::too_many_lines,
10208        reason = "cross-axis partition pin folds the substrate-primitive \
10209                  as_str accessor's `.as_bytes()` byte-tail plus the \
10210                  paired str-view (AsRef<str>, Display, as_str) and \
10211                  reverse-projection ({&'static str, String, Cow<'static, \
10212                  str>, Box<str>, std::sync::Arc<str>}) return-shape \
10213                  axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
10214                  -bound-consumer witness plus a blake3::Hasher::update-\
10215                  shape byte-input surface witness into one exhaustive \
10216                  round-trip over RestartStrategy::ALL — the accepted \
10217                  line-count cost of opening the byte-view axis keyed \
10218                  to the substrate-primitive as_str accessor at the \
10219                  same test-site"
10220    )]
10221    #[allow(
10222        clippy::needless_borrows_for_generic_args,
10223        reason = "the borrowed-input surface (&variant) is exercised \
10224                  deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
10225                  and the `blake3::Hasher::update`-shape byte-input \
10226                  surface both accept either owned or borrowed input \
10227                  through the standard-library blanket \
10228                  `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
10229                  and this pin round-trips both input shapes to lock \
10230                  the borrowed-input path load-bearing against a \
10231                  future silent regression"
10232    )]
10233    fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
10234        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
10235        // function that binds its argument through the standard-library
10236        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
10237        // directly, without the caller open-coding the two-hop
10238        // `estrategia.as_str().as_bytes()` composition. Lifted to the top
10239        // of the function per `clippy::items_after_statements`.
10240        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
10241            t.as_ref().to_vec()
10242        }
10243        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
10244        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10245        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
10246        // signature so a per-supervisor BLAKE3 content-address closure
10247        // that composes `hasher.update(estrategia)` on the
10248        // [`crate::Lacre`] closure builder reaches the substrate-primitive
10249        // `as_str` accessor through the [`super::RestartStrategy`]
10250        // `AsRef<[u8]>` axis and no other. Lifted to the top of the
10251        // function per `clippy::items_after_statements`.
10252        struct MockHasher(Vec<u8>);
10253        impl MockHasher {
10254            fn new() -> Self {
10255                Self(Vec::new())
10256            }
10257            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
10258                self.0.extend_from_slice(bytes.as_ref());
10259                self
10260            }
10261            fn finalize(self) -> Vec<u8> {
10262                self.0
10263            }
10264        }
10265
10266        // Fail-before-pass-after byte-parity pin on the newly lifted
10267        // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
10268        // idiomatic byte-view standard-library impl and the substrate-
10269        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10270        // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
10271        // `PascalCase` wire byte-string emit-set across every arm the
10272        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10273        // Opens the trait-idiomatic byte-view axis onto the first M2
10274        // OTP-shape closed-set fieldless typed enum peer on the caixa
10275        // surface (`:supervisor :estrategia`), extending the substrate-
10276        // wide byte-view campaign the sibling
10277        // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
10278        //
10279        // Rust's standard library carries `impl AsRef<[u8]> for str` and
10280        // `impl AsRef<[u8]> for String`, so a two-hop composition
10281        // `estrategia.as_str().as_bytes()` (or the equally two-hop
10282        // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
10283        // through the pre-existing str-view axis alone. But that two-hop
10284        // shape has no compile-time link back to the byte-projection
10285        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
10286        // consumer to open-code the two-hop composition at every call
10287        // site, and admits a silent split whenever a future call site
10288        // takes a sibling reverse-projection axis whose `.as_bytes()`
10289        // byte-tail carries no compile-time byte-view surface. This
10290        // impl closes the byte-view axis at the substrate-primitive
10291        // [`super::RestartStrategy::as_str`] accessor so every future
10292        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
10293        // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
10294        // the paired str-view axes already return through — through one
10295        // trait dispatch.
10296        for &variant in RestartStrategy::ALL {
10297            let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10298            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
10299            assert_eq!(
10300                via_trait, via_method_bytes,
10301                "AsRef<[u8]> for RestartStrategy impl must byte-equal \
10302                 RestartStrategy::as_str().as_bytes() on \
10303                 RestartStrategy::{variant:?} — divergence signals a \
10304                 silent detour off the substrate-primitive accessor"
10305            );
10306            // Cross-axis witness against the paired str-view axes'
10307            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
10308            // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
10309            // all resolve to the same lifted
10310            // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
10311            // roster, and the byte-view axis must byte-equal each of
10312            // their `.as_bytes()` byte-tails by construction — locking
10313            // the str-view and byte-view axes together at the
10314            // substrate-primitive accessor.
10315            let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
10316            assert_eq!(
10317                via_trait,
10318                str_view_ref.as_bytes(),
10319                "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
10320                 RestartStrategy must resolve to byte-equal byte-tails \
10321                 on RestartStrategy::{variant:?} — divergence signals \
10322                 the byte-view and str-view axes have drifted off the \
10323                 same substrate-primitive as_str accessor"
10324            );
10325            let display_bytes = variant.to_string();
10326            assert_eq!(
10327                via_trait,
10328                display_bytes.as_bytes(),
10329                "AsRef<[u8]> for RestartStrategy and \
10330                 <RestartStrategy as std::fmt::Display>::to_string must \
10331                 resolve to byte-equal byte-tails on \
10332                 RestartStrategy::{variant:?} — divergence signals the \
10333                 byte-view axis and the Display formatter axis have \
10334                 drifted off the same substrate-primitive as_str \
10335                 accessor"
10336            );
10337            // Cross-axis witness against the paired reverse-projection
10338            // axes' `.as_bytes()` byte-tails: every one of `{&'static
10339            // str, String, Cow<'static, str>, Box<str>,
10340            // std::sync::Arc<str>}` allocates (or borrows) the same
10341            // `PascalCase` wire byte-string the substrate-primitive
10342            // accessor emits, so the byte-view axis must byte-equal
10343            // each of their `.as_bytes()` byte-tails by construction.
10344            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10345            assert_eq!(
10346                via_trait,
10347                owned_static.as_bytes(),
10348                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10349                 for &'static str must resolve to byte-equal byte-tails \
10350                 on RestartStrategy::{variant:?}"
10351            );
10352            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10353            assert_eq!(
10354                via_trait,
10355                owned_string.as_bytes(),
10356                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10357                 for String must resolve to byte-equal byte-tails on \
10358                 RestartStrategy::{variant:?}"
10359            );
10360            let owned_cow: std::borrow::Cow<'static, str> =
10361                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10362            assert_eq!(
10363                via_trait,
10364                owned_cow.as_bytes(),
10365                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10366                 for Cow<'static, str> must resolve to byte-equal byte-\
10367                 tails on RestartStrategy::{variant:?}"
10368            );
10369            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10370            assert_eq!(
10371                via_trait,
10372                owned_box.as_bytes(),
10373                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10374                 for Box<str> must resolve to byte-equal byte-tails on \
10375                 RestartStrategy::{variant:?}"
10376            );
10377            let owned_arc: std::sync::Arc<str> =
10378                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10379            assert_eq!(
10380                via_trait,
10381                owned_arc.as_bytes(),
10382                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10383                 for std::sync::Arc<str> must resolve to byte-equal byte-\
10384                 tails on RestartStrategy::{variant:?}"
10385            );
10386        }
10387        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
10388        // input function `generic_bytes_sink` (lifted above per
10389        // `clippy::items_after_statements`) accepts a
10390        // [`super::RestartStrategy`] directly through the trait bound,
10391        // without the caller open-coding the two-hop
10392        // `estrategia.as_str().as_bytes()` composition. This is the
10393        // shape that reaches the caixa-lacre BLAKE3 content-address
10394        // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
10395        // input surface through this impl and no other.
10396        for &variant in RestartStrategy::ALL {
10397            let via_generic = generic_bytes_sink(variant);
10398            let via_borrowed_generic = generic_bytes_sink(&variant);
10399            let via_method_bytes = variant.as_str().as_bytes().to_vec();
10400            assert_eq!(
10401                via_generic, via_method_bytes,
10402                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10403                 RestartStrategy::{variant:?} must yield the same byte-\
10404                 tail RestartStrategy::as_str().as_bytes() returns — \
10405                 divergence signals the byte-view axis fails to bridge \
10406                 a generic byte-input trait bound to the substrate-\
10407                 primitive accessor"
10408            );
10409            assert_eq!(
10410                via_borrowed_generic, via_method_bytes,
10411                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10412                 &RestartStrategy::{variant:?} must yield the same byte-\
10413                 tail RestartStrategy::as_str().as_bytes() returns — \
10414                 the borrowed-input surface must resolve to the same \
10415                 as_str dispatch"
10416            );
10417        }
10418        // `blake3::Hasher::update`-shape byte-input surface witness on
10419        // the caixa-lacre compounding target: the `MockHasher` (lifted
10420        // above per `clippy::items_after_statements`) mirrors
10421        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10422        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
10423        // signature and accepts a [`super::RestartStrategy`] directly,
10424        // routing its byte-tail through the substrate-primitive
10425        // `as_str` accessor — the shape a future per-supervisor BLAKE3
10426        // content-address closure composes to fold an `:estrategia`
10427        // discriminator byte-tag into the [`crate::Lacre`] closure
10428        // body.
10429        for &variant in RestartStrategy::ALL {
10430            let mut owned_hasher = MockHasher::new();
10431            owned_hasher.update(variant);
10432            let owned_folded = owned_hasher.finalize();
10433            assert_eq!(
10434                owned_folded,
10435                variant.as_str().as_bytes(),
10436                "`hasher.update(estrategia)`-shape composition on \
10437                 RestartStrategy::{variant:?} must fold the same byte-\
10438                 tail RestartStrategy::as_str().as_bytes() returns — \
10439                 the shape a future per-supervisor BLAKE3 content-\
10440                 address closure composes to fold an `:estrategia` \
10441                 discriminator byte-tag into the Lacre closure body"
10442            );
10443            let mut borrowed_hasher = MockHasher::new();
10444            borrowed_hasher.update(&variant);
10445            let borrowed_folded = borrowed_hasher.finalize();
10446            assert_eq!(
10447                borrowed_folded,
10448                variant.as_str().as_bytes(),
10449                "`hasher.update(&estrategia)`-shape composition on \
10450                 &RestartStrategy::{variant:?} must fold the same byte-\
10451                 tail RestartStrategy::as_str().as_bytes() returns — \
10452                 the borrowed-input surface must resolve to the same \
10453                 as_str dispatch"
10454            );
10455        }
10456    }
10457
10458    #[test]
10459    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
10460        // Fail-before-pass-after byte-parity pin on the newly lifted
10461        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
10462        // library trait impl and the substrate-primitive
10463        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
10464        // the same three-arm accept-set across every arm the exhaustive
10465        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10466        // detour that routes the trait impl through a divergent
10467        // projection (a per-arm inline `match s { "Permanent" =>
10468        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
10469        // link to the un-lifted arm-literal, a hypothetical
10470        // `#[serde(rename_all = "…")]` attribute drift that silently
10471        // splits the wire byte-string from every consumer that reaches
10472        // for this typed dispatch, an accidental swap onto the kebab-case
10473        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
10474        // impl parses through and which would collide the two-axis
10475        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
10476        // doc block makes load-bearing) trips at caixa-core test time
10477        // under `assert_eq!` rather than at a downstream
10478        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
10479        // every one of the three arms [`RestartPolicy::ALL`] carries so
10480        // no arm's projection is covered only by the sibling method-
10481        // named `from_wire` path. Peer of the sibling
10482        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
10483        // (5b828ed) — extends the trait-idiomatic reverse-projection
10484        // axis onto the third and final M2-OTP-shape closed-set typed
10485        // enum on the caixa surface (the paired per-child restart-
10486        // decision-policy sibling on the same M2 `:supervisor` slot).
10487        for &variant in RestartPolicy::ALL {
10488            let wire = variant.as_str();
10489            assert_eq!(
10490                <RestartPolicy as TryFrom<&str>>::try_from(wire),
10491                Ok(variant),
10492                "TryFrom<&str> impl on RestartPolicy must round-trip \
10493                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
10494                 Ok(RestartPolicy::{variant:?}) — divergence from \
10495                 RestartPolicy::from_wire signals a silent detour off \
10496                 the substrate-primitive accessor"
10497            );
10498            assert_eq!(
10499                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
10500                RestartPolicy::from_wire(wire),
10501                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
10502                 equal RestartPolicy::from_wire on the same input"
10503            );
10504        }
10505    }
10506
10507    #[test]
10508    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
10509        // Rejection witness on the `impl TryFrom<&str> for
10510        // RestartPolicy` — sweeps a candidate set of byte-strings
10511        // outside the three-arm PascalCase wire accept-set the sibling
10512        // [`RestartPolicy::as_str`] emits and asserts every one lands on
10513        // `Err(())`, so a future accidental widening of the trait impl's
10514        // accept-set (a stray additional
10515        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
10516        // path, a silent inclusion of the kebab-case dispatcher-catalog
10517        // byte-string the pre-existing [`std::str::FromStr`] impl the
10518        // [`gen_platform::FromStrKind`] derive installs parses onto the
10519        // wire axis — which would collide the two-axis
10520        // wire/dispatcher-catalog split the sibling
10521        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
10522        // an English-rebrand or plural-arm silent alias that would widen
10523        // the wire accept-set past the OTP-canonical three) trips at
10524        // caixa-core test time. The candidate set includes the empty
10525        // string, whitespace-only padding, the kebab-case dispatcher-
10526        // catalog byte-strings on the sibling axis (a caller who
10527        // confuses the two axes trips here rather than at a downstream
10528        // consumer's silent reject), a lowercase / uppercase / mixed-case
10529        // fold of each PascalCase arm (a caller who assumes case-fold
10530        // acceptance trips here), leading/trailing whitespace padding,
10531        // the trailing-newline shape, quote-wrapped candidates, and a
10532        // residual set of plausible-but-wrong English rebrand
10533        // candidates. Peer of the sibling
10534        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
10535        // (5b828ed) rejection witness.
10536        let rejected: &[&str] = &[
10537            "",
10538            " ",
10539            "\n",
10540            "\t",
10541            "permanent",
10542            "temporary",
10543            "transient",
10544            "PERMANENT",
10545            "TEMPORARY",
10546            "TRANSIENT",
10547            "Permanents",
10548            "Permanent ",
10549            " Permanent",
10550            " Temporary ",
10551            "Permanent\n",
10552            "Transient\t",
10553            "\"Permanent\"",
10554            "Ephemeral",
10555            "Always",
10556            "Never",
10557            "OnAbnormalExit",
10558            "intrinsic",
10559            "?",
10560        ];
10561        for &input in rejected {
10562            assert_eq!(
10563                <RestartPolicy as TryFrom<&str>>::try_from(input),
10564                Err(()),
10565                "TryFrom<&str> impl on RestartPolicy must reject the \
10566                 non-wire byte-string {input:?} — silent acceptance \
10567                 signals an accept-set widening off the paired \
10568                 RestartPolicy::from_wire resolver"
10569            );
10570        }
10571    }
10572
10573    #[test]
10574    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
10575        // Cross-axis partition pin: the paired `TryFrom<&str>` and
10576        // `from_wire` reverse projections must resolve identically on
10577        // *every* input, not just the ones [`RestartPolicy::ALL`]
10578        // enumerates. Sweeps a mixed candidate set spanning accepted
10579        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
10580        // case dispatcher-catalog byte-strings, empty, whitespace-
10581        // padded, quoted, English-rebrand candidates) inputs and asserts
10582        // the trait's `Result::ok()` projection byte-equals the method-
10583        // named resolver's `Option<Self>` return-shape on each, locking
10584        // the two paths together by construction so any future detour
10585        // (a stray `try_from` special-case that widens or narrows the
10586        // accept-set outside the paired `from_wire` resolver, an
10587        // accidental swap onto the kebab-case [`std::str::FromStr`]
10588        // impl the [`gen_platform::FromStrKind`] derive installs on the
10589        // sibling dispatcher-catalog axis) trips at caixa-core test
10590        // time. Peer of the sibling
10591        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
10592        // pin — extends the round-trip discipline onto the M2-OTP-shape
10593        // per-child restart-policy axis.
10594        let candidates: &[&str] = &[
10595            "Permanent",
10596            "Temporary",
10597            "Transient",
10598            "",
10599            "permanent",
10600            "temporary",
10601            "transient",
10602            "PERMANENT",
10603            "unknown",
10604            "Permanent ",
10605            " Permanent",
10606            "\"Permanent\"",
10607            "Ephemeral",
10608            "OnAbnormalExit",
10609            "?",
10610        ];
10611        for &input in candidates {
10612            let via_trait: Option<RestartPolicy> =
10613                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
10614            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
10615            assert_eq!(
10616                via_trait, via_method,
10617                "TryFrom<&str> and from_wire must resolve identically on \
10618                 input {input:?} — divergence signals the two reverse-\
10619                 projection paths have drifted onto different accept-sets"
10620            );
10621        }
10622    }
10623
10624    #[test]
10625    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
10626        // Fail-before-pass-after byte-parity pin on the newly lifted
10627        // `impl From<RestartPolicy> for &'static str` — asserts the
10628        // standard-library trait impl and the substrate-primitive
10629        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10630        // the same three-arm emit-set across every arm the exhaustive
10631        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10632        // detour that routes the trait impl through a divergent
10633        // projection (a per-arm inline `match policy { Permanent =>
10634        // "Permanent", … }` re-inlining that opens a compile-time link
10635        // to the un-lifted arm-literal, an accidental swap onto the
10636        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
10637        // axis that would collide the two-axis wire/catalog split the
10638        // sibling [`RestartPolicy::from_wire`] doc block makes
10639        // load-bearing) trips at caixa-core test time under
10640        // `assert_eq!` rather than at a downstream
10641        // `impl Into<&'static str>`-bound consumer's silent split.
10642        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
10643        // carries so no arm's projection is covered only by the sibling
10644        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
10645        // paths. Materializes the `<&'static str as
10646        // From<RestartPolicy>>::from` output in a `const`-shape binding
10647        // to make the `'static` lifetime promise a build-time invariant
10648        // — a future accidental downgrade of any of the three arms'
10649        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
10650        // non-`&'static str` (a `String::leak()`-produced return, a
10651        // `Box::leak`-cast) trips at caixa-core build time rather than
10652        // at a downstream `'static`-bound consumer. Peer of the sibling
10653        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
10654        // (523157d) — extends the trait-idiomatic forward-projection
10655        // axis onto the second (and second-of-two-in-M2) closed-set
10656        // typed enum on the caixa surface (the paired per-child
10657        // restart-decision-policy sibling on the same M2 `:supervisor`
10658        // slot).
10659        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10660        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10661        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10662        for &variant in RestartPolicy::ALL {
10663            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10664            let via_method: &'static str = variant.as_str();
10665            assert_eq!(
10666                via_trait, via_method,
10667                "From<RestartPolicy> for &'static str impl must round-trip \
10668                 RestartPolicy::{variant:?} to the same lifted \
10669                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
10670                 divergence signals a silent detour off the substrate-primitive \
10671                 accessor"
10672            );
10673            let via_into: &'static str = variant.into();
10674            assert_eq!(
10675                via_into, via_method,
10676                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
10677                 byte-equal RestartPolicy::as_str on the same input — the \
10678                 blanket-derived Into shape must resolve to the same as_str \
10679                 dispatch as the explicit From impl"
10680            );
10681        }
10682        assert_eq!(
10683            [PERMANENT, TEMPORARY, TRANSIENT],
10684            [
10685                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10686                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10687                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10688            ],
10689            "const-context RestartPolicy::as_str must resolve to the three \
10690             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
10691             downgrade of any arm to a non-const or non-static byte-string \
10692             breaks the `&'static str`-lifetime promise the paired \
10693             From<RestartPolicy> for &'static str impl carries by \
10694             construction"
10695        );
10696    }
10697
10698    #[test]
10699    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10700        // Cross-axis partition pin: the paired trait-idiomatic
10701        // `From<RestartPolicy> for &'static str` forward projection and
10702        // the method-named [`RestartPolicy::as_str`] forward projection
10703        // must resolve identically on *every* arm, not just the ones
10704        // named in the primary byte-parity pin above. Sweeps every
10705        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10706        // output byte-equals the method-named accessor's return-value on
10707        // each, locking the two forward-projection paths together by
10708        // construction so any future detour (a stray `From` special-case
10709        // that lands on a divergent per-arm literal outside the paired
10710        // `as_str` dispatch, a hypothetical rebrand touching one axis
10711        // without the other) trips at caixa-core test time. Peer of the
10712        // sibling forward-projection partition pin
10713        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10714        // (523157d) — extends the round-trip discipline onto the
10715        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10716        // surface, closing the two-way `Self ↔ &'static str` round-trip
10717        // on the trait-idiomatic pair (`From<Self> for &'static str` +
10718        // `TryFrom<&str> for Self`) as well as the pre-existing method-
10719        // named pair (`as_str` + `from_wire`).
10720        for &variant in RestartPolicy::ALL {
10721            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10722            let via_method: &'static str = variant.as_str();
10723            assert_eq!(
10724                via_trait, via_method,
10725                "From<RestartPolicy> for &'static str and \
10726                 RestartPolicy::as_str must resolve identically on \
10727                 RestartPolicy::{variant:?} — divergence signals the \
10728                 two forward-projection paths have drifted onto different \
10729                 emit-sets"
10730            );
10731        }
10732        // Round-trip witness: every arm's forward `From` output re-parses
10733        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10734        // to the original variant. Closes the two-way `RestartPolicy ↔
10735        // &'static str` round-trip on the trait-idiomatic axis pair,
10736        // mirroring the pre-existing method-named `as_str` + `from_wire`
10737        // round-trip on the substrate-primitive axis pair.
10738        for &variant in RestartPolicy::ALL {
10739            let emitted: &'static str = variant.into();
10740            let re_parsed: Result<RestartPolicy, ()> =
10741                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10742            assert_eq!(
10743                re_parsed,
10744                Ok(variant),
10745                "trait-idiomatic axis pair must round-trip \
10746                 RestartPolicy::{variant:?} through `.into::<&'static \
10747                 str>()` and back through `TryFrom<&str>` — a break signals \
10748                 the forward-emit and reverse-parse axes have drifted onto \
10749                 different vocabularies"
10750            );
10751        }
10752    }
10753
10754    #[test]
10755    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10756        // Fail-before-pass-after byte-parity pin on the newly lifted
10757        // `impl From<&RestartPolicy> for &'static str` — asserts the
10758        // borrowed-input standard-library trait impl and the substrate-
10759        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10760        // resolve to the same three-arm emit-set across every arm the
10761        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10762        // `From` trait does not auto-derive the borrowed-input sibling
10763        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10764        // where T: Copy, U: From<T>` blanket in `core`), so the
10765        // borrowed-input axis is a distinct trait-idiomatic surface
10766        // that a `.iter().map(Into::into)` shape over
10767        // [`RestartPolicy::ALL`] (whose iterator yields
10768        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10769        // impl and no other — the paired owned-input
10770        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10771        // / dereference before the trait fires. Materializes the
10772        // `<&'static str as From<&RestartPolicy>>::from` output in a
10773        // `const`-shape binding to make the `'static` lifetime promise
10774        // a build-time invariant.
10775        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10776        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10777        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10778        for variant in RestartPolicy::ALL {
10779            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10780            let via_method: &'static str = variant.as_str();
10781            assert_eq!(
10782                via_trait, via_method,
10783                "From<&RestartPolicy> for &'static str impl must round-trip \
10784                 &RestartPolicy::{variant:?} to the same lifted \
10785                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10786                 returns — divergence signals a silent detour off the \
10787                 substrate-primitive accessor"
10788            );
10789            let via_into: &'static str = variant.into();
10790            assert_eq!(
10791                via_into, via_method,
10792                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10793                 must byte-equal RestartPolicy::as_str on the same input — \
10794                 the blanket-derived Into shape must resolve to the same \
10795                 as_str dispatch as the explicit From impl"
10796            );
10797        }
10798        assert_eq!(
10799            [PERMANENT, TEMPORARY, TRANSIENT],
10800            [
10801                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10802                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10803                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10804            ],
10805            "const-context RestartPolicy::as_str must resolve to the three \
10806             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10807             From<&RestartPolicy> for &'static str impl inherits its \
10808             `'static` lifetime promise from the same accessor the \
10809             owned-input sibling routes through"
10810        );
10811    }
10812
10813    #[test]
10814    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10815        // Cross-axis partition pin: the paired trait-idiomatic
10816        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10817        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10818        // &'static str` (this lift) forward projections must resolve
10819        // identically on every arm, locking the two input-shape paths
10820        // together so any future detour trips at caixa-core test time.
10821        // Then a witness that a `.iter().map(Into::into)` pipe over
10822        // [`RestartPolicy::ALL`] (whose iterator yields
10823        // `&RestartPolicy`) materializes the three-arm accept-set
10824        // through the borrowed-input axis alone — the exact shape a
10825        // future wasm-operator per-child post-exit restart-decision
10826        // diagnostic line, a future substrate-wide per-arm diagnostic
10827        // column, or a
10828        // `HashMap::<&'static str, RestartPolicy>::from_iter(
10829        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10830        // per-policy lookup reaches through — closing the two-way
10831        // owned/borrowed input-shape symmetry on the forward-projection
10832        // trait-idiomatic axis. Peer of the sibling
10833        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10834        // (64aa742) /
10835        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10836        // (5ab993a) /
10837        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10838        // (807b0b5) /
10839        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10840        // (e941836) partition pins on the sibling closed-set typed-enum
10841        // discriminator axes — extends the borrowed-input axis
10842        // discipline onto the second-of-two M2 OTP-shape closed-set
10843        // typed enum on the caixa surface (per-child restart-decision
10844        // policy). Also closes the direct two-way `&Self → &'static
10845        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10846        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10847        // forward `From` emits lowercase Portuguese diagnostic bytes
10848        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10849        // forcing the round-trip through an intermediate wire-vocab
10850        // hop), the [`RestartPolicy::as_str`] emit and
10851        // [`RestartPolicy::from_wire`] parse share the same
10852        // `PascalCase` vocabulary by construction, so the borrowed-
10853        // input forward axis and the reverse axis compose directly.
10854        for &variant in RestartPolicy::ALL {
10855            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10856            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10857            assert_eq!(
10858                owned, borrowed,
10859                "From<RestartPolicy> and From<&RestartPolicy> for \
10860                 &'static str must resolve identically on \
10861                 RestartPolicy::{variant:?} — divergence signals the \
10862                 owned-input and borrowed-input forward-projection paths \
10863                 have drifted onto different emit-sets"
10864            );
10865        }
10866        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10867        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10868        assert_eq!(
10869            via_iter, via_method,
10870            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10871             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10872             borrowed-input `From<&RestartPolicy> for &'static str` axis \
10873             is what makes the `.iter().map(Into::into)` shape route \
10874             through the substrate-primitive `RestartPolicy::as_str` \
10875             accessor rather than through a per-call-site `.copied()` / \
10876             dereference detour"
10877        );
10878        for variant in RestartPolicy::ALL {
10879            let emitted: &'static str = variant.into();
10880            let re_parsed: Result<RestartPolicy, ()> =
10881                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10882            assert_eq!(
10883                re_parsed,
10884                Ok(*variant),
10885                "trait-idiomatic borrowed-input forward-projection + \
10886                 reverse-projection axis pair must round-trip \
10887                 &RestartPolicy::{variant:?} through `.into::<&'static \
10888                 str>()` (via the borrowed-input axis) and back through \
10889                 `TryFrom<&str>` — a break signals the borrowed-input \
10890                 forward-emit and reverse-parse axes have drifted onto \
10891                 different vocabularies"
10892            );
10893        }
10894    }
10895
10896    #[test]
10897    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10898        // Fail-before-pass-after byte-parity pin on the newly lifted
10899        // `impl From<RestartPolicy> for String` — asserts the
10900        // owned-`String`-returning standard-library trait impl and the
10901        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10902        // accessor resolve to the same three-arm emit-set across every
10903        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10904        // Rust's standard library does not carry a blanket
10905        // `impl<T: AsRef<str>> From<T> for String` (nor an
10906        // `impl<T: fmt::Display> From<T> for String`), so the
10907        // owned-`String` forward-projection axis is a distinct
10908        // trait-idiomatic surface that a `let key: String =
10909        // policy.into();`-shaped call site reaches through this impl
10910        // and no other — the paired sibling `From<RestartPolicy> for
10911        // &'static str` impl forces every owned-`String` call site
10912        // through an explicit `.to_owned()` / `String::from`
10913        // restatement. Peer of the first-mover
10914        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10915        // (7baa18a) — extends the trait-idiomatic owned-`String`
10916        // forward-projection axis onto the second-of-two M2 OTP-shape
10917        // closed-set typed enums on the caixa surface (per-child
10918        // restart-decision-policy sibling on the same M2 `:supervisor`
10919        // slot).
10920        for &variant in RestartPolicy::ALL {
10921            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10922            let via_method: &'static str = variant.as_str();
10923            assert_eq!(
10924                via_trait.as_str(),
10925                via_method,
10926                "From<RestartPolicy> for String impl must round-trip \
10927                 RestartPolicy::{variant:?} to the same lifted \
10928                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10929                 returns — divergence signals a silent detour off the \
10930                 substrate-primitive accessor"
10931            );
10932            let via_into: String = variant.into();
10933            assert_eq!(
10934                via_into.as_str(),
10935                via_method,
10936                "Into<String>::into on RestartPolicy::{variant:?} must \
10937                 byte-equal RestartPolicy::as_str on the same input — the \
10938                 blanket-derived Into shape must resolve to the same as_str \
10939                 dispatch as the explicit From impl"
10940            );
10941        }
10942    }
10943
10944    #[test]
10945    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10946        // Cross-axis partition pin: the paired trait-idiomatic
10947        // owned-`String` `From<RestartPolicy> for String` (this lift)
10948        // and owned-`&'static str` `From<RestartPolicy> for &'static
10949        // str` (9fb37d0) forward projections must resolve identically
10950        // on every arm, locking the two return-type-shape paths
10951        // together so any future detour trips at caixa-core test time.
10952        // Also byte-parity witness against the sibling
10953        // [`ToString::to_string`] surface routed through
10954        // [`std::fmt::Display`] — the three owned-heap-string paths
10955        // (`.into::<String>()`, `String::from`, `.to_string()`) must
10956        // resolve identically on every arm so a future consumer that
10957        // picks any of the three lands on the same lifted
10958        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10959        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10960        // that materializes the three-arm accept-set through the
10961        // owned-`String` axis alone — the exact shape a future
10962        // wasm-operator per-child post-exit restart-decision
10963        // diagnostic line composer or a
10964        // `HashMap::<String, RestartPolicy>::from_iter(
10965        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10966        // owned-key per-policy lookup reaches through — closing the
10967        // owned-`String` forward-projection axis's iterator-pipe
10968        // shape. Then a direct round-trip witness through the paired
10969        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10970        // owned-`String`'s [`String::as_str`] borrow that closes the
10971        // two-way `Self → String → Self` round-trip on the trait-
10972        // idiomatic owned-`String` forward + reverse axis pair —
10973        // unlike the peer [`crate::CaixaKind`] axis pair (whose
10974        // forward `From` emits lowercase Portuguese diagnostic bytes
10975        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10976        // forcing the round-trip through an intermediate wire-vocab
10977        // hop), the [`RestartPolicy::as_str`] emit and
10978        // [`RestartPolicy::from_wire`] parse share the same
10979        // `PascalCase` vocabulary by construction, so the owned-
10980        // `String` forward axis and the reverse axis compose directly.
10981        for &variant in RestartPolicy::ALL {
10982            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10983            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10984            assert_eq!(
10985                owned_string.as_str(),
10986                owned_static,
10987                "From<RestartPolicy> for String and From<RestartPolicy> \
10988                 for &'static str must resolve identically on \
10989                 RestartPolicy::{variant:?} — divergence signals the \
10990                 owned-`String` and owned-`&'static str` forward-projection \
10991                 return-type-shape paths have drifted onto different \
10992                 emit-sets"
10993            );
10994            let via_to_string: String = variant.to_string();
10995            assert_eq!(
10996                owned_string, via_to_string,
10997                "From<RestartPolicy> for String must byte-equal \
10998                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10999                 divergence signals the trait-idiomatic owned-`String` \
11000                 forward-projection axis and the ToString-through-Display \
11001                 axis have drifted onto different emit-sets"
11002            );
11003        }
11004        let via_iter: Vec<String> = RestartPolicy::ALL
11005            .iter()
11006            .copied()
11007            .map(String::from)
11008            .collect();
11009        let via_method: Vec<String> = RestartPolicy::ALL
11010            .iter()
11011            .map(|p| p.as_str().to_owned())
11012            .collect();
11013        assert_eq!(
11014            via_iter, via_method,
11015            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
11016             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
11017             every arm — the owned-`String` `From<RestartPolicy> for \
11018             String` axis is what makes the `String::from` composition \
11019             route through the substrate-primitive `RestartPolicy::as_str` \
11020             accessor rather than through a per-call-site `.to_owned()` / \
11021             `String::from(policy.as_str())` detour"
11022        );
11023        for &variant in RestartPolicy::ALL {
11024            let emitted: String = variant.into();
11025            let re_parsed: Result<RestartPolicy, ()> =
11026                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11027            assert_eq!(
11028                re_parsed,
11029                Ok(variant),
11030                "trait-idiomatic owned-`String` forward-projection + \
11031                 reverse-projection axis pair must round-trip \
11032                 RestartPolicy::{variant:?} through `.into::<String>()` \
11033                 and back through `TryFrom<&str>` on the owned-`String`'s \
11034                 String::as_str borrow — a break signals the owned-`String` \
11035                 forward-emit and reverse-parse axes have drifted onto \
11036                 different vocabularies"
11037            );
11038        }
11039    }
11040
11041    #[test]
11042    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
11043        // Fail-before-pass-after byte-parity pin on the newly lifted
11044        // `impl From<&RestartPolicy> for String` — asserts the
11045        // borrowed-input owned-`String`-returning standard-library
11046        // trait impl and the substrate-primitive
11047        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11048        // the same three-arm emit-set across every arm the exhaustive
11049        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
11050        // library does not carry a blanket `impl<T: AsRef<str>>
11051        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
11052        // for String`), so the borrowed-input owned-`String` forward-
11053        // projection axis is a distinct trait-idiomatic surface that a
11054        // `let key: String = (&policy).into();`-shaped call site
11055        // reaches through this impl and no other — the paired sibling
11056        // `From<RestartPolicy> for String` impl forces every borrowed-
11057        // input call site through an explicit `Copy` deref
11058        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
11059        // `.to_string()` detour. Peer of the first-mover
11060        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
11061        // (579385f) — extends the trait-idiomatic borrowed-input
11062        // owned-`String` forward-projection axis onto the second-of-
11063        // two M2 OTP-shape closed-set typed enums on the caixa surface
11064        // (per-child restart-decision-policy sibling on the same M2
11065        // `:supervisor` slot).
11066        for &variant in RestartPolicy::ALL {
11067            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
11068            let via_method: &'static str = variant.as_str();
11069            assert_eq!(
11070                via_trait.as_str(),
11071                via_method,
11072                "From<&RestartPolicy> for String impl must round-trip \
11073                 &RestartPolicy::{variant:?} to the same lifted \
11074                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11075                 returns — divergence signals a silent detour off the \
11076                 substrate-primitive accessor"
11077            );
11078            let via_into: String = (&variant).into();
11079            assert_eq!(
11080                via_into.as_str(),
11081                via_method,
11082                "Into<String>::into on &RestartPolicy::{variant:?} must \
11083                 byte-equal RestartPolicy::as_str on the same input — \
11084                 the blanket-derived Into shape must resolve to the \
11085                 same as_str dispatch as the explicit From impl"
11086            );
11087        }
11088    }
11089
11090    #[test]
11091    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
11092        // Cross-axis partition pin: the newly lifted trait-idiomatic
11093        // borrowed-input owned-`String` `From<&RestartPolicy> for
11094        // String` (this lift), the paired owned-input owned-`String`
11095        // `From<RestartPolicy> for String` (7851725), the paired
11096        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11097        // for &'static str` (842c7f3), and the paired owned-input
11098        // owned-`&'static str` `From<RestartPolicy> for &'static str`
11099        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
11100        // str, String}` 2×2 trait-idiomatic projection family — must
11101        // resolve identically on every arm, locking the four
11102        // return-shape × input-shape paths together so any future
11103        // detour trips at caixa-core test time. Also byte-parity
11104        // witness against the sibling [`ToString::to_string`] surface
11105        // routed through [`std::fmt::Display`] and a direct round-trip
11106        // witness through the paired trait-idiomatic reverse
11107        // [`TryFrom<&str>`] axis on the owned-`String`'s
11108        // [`String::as_str`] borrow that closes the two-way
11109        // `&Self → String → Self` round-trip on the trait-idiomatic
11110        // borrowed-input owned-`String` forward + reverse axis pair.
11111        // Peer of the first-mover
11112        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
11113        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
11114        // String}` 2×2 projection corner on both M2 OTP-shape sibling
11115        // peers.
11116        for &variant in RestartPolicy::ALL {
11117            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11118            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11119            let borrowed_static: &'static str =
11120                <&'static str as From<&RestartPolicy>>::from(&variant);
11121            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11122            assert_eq!(
11123                borrowed_string, owned_string,
11124                "From<&RestartPolicy> for String and From<RestartPolicy> \
11125                 for String must resolve identically on \
11126                 RestartPolicy::{variant:?} — divergence signals the \
11127                 borrowed-input and owned-input owned-`String` \
11128                 forward-projection input-shape paths have drifted onto \
11129                 different emit-sets"
11130            );
11131            assert_eq!(
11132                borrowed_string.as_str(),
11133                borrowed_static,
11134                "From<&RestartPolicy> for String and From<&RestartPolicy> \
11135                 for &'static str must resolve identically on \
11136                 RestartPolicy::{variant:?} — divergence signals the \
11137                 borrowed-input `&'static str` and owned-`String` \
11138                 return-shape paths have drifted onto different \
11139                 emit-sets"
11140            );
11141            assert_eq!(
11142                borrowed_string.as_str(),
11143                owned_static,
11144                "From<&RestartPolicy> for String and From<RestartPolicy> \
11145                 for &'static str must resolve identically on \
11146                 RestartPolicy::{variant:?} — divergence signals a \
11147                 break in the diagonal corner of the {{Self, &Self}} × \
11148                 {{&'static str, String}} 2×2 trait-idiomatic \
11149                 projection family"
11150            );
11151            let via_to_string: String = variant.to_string();
11152            assert_eq!(
11153                borrowed_string, via_to_string,
11154                "From<&RestartPolicy> for String must byte-equal \
11155                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
11156                 — divergence signals the trait-idiomatic borrowed-input \
11157                 owned-`String` forward-projection axis and the \
11158                 ToString-through-Display axis have drifted onto \
11159                 different emit-sets"
11160            );
11161        }
11162        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
11163        let via_method: Vec<String> = RestartPolicy::ALL
11164            .iter()
11165            .map(|p| p.as_str().to_owned())
11166            .collect();
11167        assert_eq!(
11168            via_iter, via_method,
11169            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
11170             call site whose iteration axis holds `&RestartPolicy` by \
11171             construction — must byte-equal `.iter().map(|p| \
11172             p.as_str().to_owned())` on every arm — the borrowed-input \
11173             owned-`String` `From<&RestartPolicy> for String` axis is \
11174             what makes the `String::from` composition route through \
11175             the substrate-primitive `RestartPolicy::as_str` accessor \
11176             without a spurious `Copy` deref (which would only be \
11177             reachable through the owned-input `From<RestartPolicy> \
11178             for String` axis by first calling `.copied()` on the \
11179             iterator)"
11180        );
11181        for &variant in RestartPolicy::ALL {
11182            let emitted: String = (&variant).into();
11183            let re_parsed: Result<RestartPolicy, ()> =
11184                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11185            assert_eq!(
11186                re_parsed,
11187                Ok(variant),
11188                "trait-idiomatic borrowed-input owned-`String` \
11189                 forward-projection + reverse-projection axis pair must \
11190                 round-trip &RestartPolicy::{variant:?} through \
11191                 `.into::<String>()` on the borrowed-input surface and \
11192                 back through `TryFrom<&str>` on the owned-`String`'s \
11193                 String::as_str borrow — a break signals the \
11194                 borrowed-input owned-`String` forward-emit and \
11195                 reverse-parse axes have drifted onto different \
11196                 vocabularies"
11197            );
11198        }
11199    }
11200
11201    #[test]
11202    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
11203        // Fail-before-pass-after byte-parity pin on the newly lifted
11204        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
11205        // asserts the standard-library trait impl and the substrate-
11206        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
11207        // accessor resolve to the same three-arm emit-set across every
11208        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
11209        // enumerates. Rust's standard library does not carry a blanket
11210        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
11211        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
11212        // the `Cow<'static, str>` forward-projection axis is a
11213        // distinct trait-idiomatic surface that a
11214        // `let key: Cow<'static, str> = policy.into();`-shaped call
11215        // site reaches through this impl and no other — the paired
11216        // sibling `From<RestartPolicy> for &'static str` and
11217        // `From<RestartPolicy> for String` impls force every
11218        // `Cow<'static, str>`-parameterized call site through a
11219        // `Cow::Borrowed(policy.as_str())` /
11220        // `Cow::Owned(policy.to_string())` composition whose type
11221        // bounds have no compile-time link back to the substrate
11222        // primitive.
11223        //
11224        // Also asserts the projection lands on the zero-alloc
11225        // [`std::borrow::Cow::Borrowed`] arm (not the
11226        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11227        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11228        // return lifetime by construction makes the borrowed arm the
11229        // type-correct projection with no runtime allocation. Any
11230        // future silent detour that routes the impl through the owned
11231        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
11232        // that would allocate on every call site where the
11233        // `&'static str` return of [`super::RestartPolicy::as_str`]
11234        // makes the zero-alloc borrowed projection type-correct) trips
11235        // at caixa-core test time under the
11236        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
11237        // than at a downstream `Cow<'static, str>`-bound consumer's
11238        // silent allocation.
11239        //
11240        // Second peer on the substrate-wide trait-idiomatic
11241        // [`std::borrow::Cow<'static, str>`] forward-projection family
11242        // to extend the axis off the top-level [`super::CaixaKind`]
11243        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
11244        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
11245        // fieldless typed enum peer on the caixa surface — closes the
11246        // M2 OTP-shape tier of the campaign on the owned-input axis
11247        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
11248        // now carry the owned-input Cow<'static, str> forward
11249        // projection).
11250        for &variant in RestartPolicy::ALL {
11251            let via_trait: std::borrow::Cow<'static, str> =
11252                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11253            let via_method: &'static str = variant.as_str();
11254            assert_eq!(
11255                via_trait.as_ref(),
11256                via_method,
11257                "From<RestartPolicy> for Cow<'static, str> impl must \
11258                 round-trip RestartPolicy::{variant:?} to the same \
11259                 lifted SUPERVISOR_CHILD_RESTART_* const \
11260                 RestartPolicy::as_str returns — divergence signals a \
11261                 silent detour off the substrate-primitive accessor"
11262            );
11263            assert!(
11264                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11265                "From<RestartPolicy> for Cow<'static, str> impl must \
11266                 land on the zero-alloc Cow::Borrowed arm on \
11267                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
11268                 signals the projection has silently allocated where \
11269                 the substrate-primitive RestartPolicy::as_str \
11270                 `&'static str` return makes the borrowed arm the \
11271                 type-correct projection"
11272            );
11273            let via_into: std::borrow::Cow<'static, str> = variant.into();
11274            assert_eq!(
11275                via_into.as_ref(),
11276                via_method,
11277                "Into<Cow<'static, str>>::into on \
11278                 RestartPolicy::{variant:?} must byte-equal \
11279                 RestartPolicy::as_str on the same input — the \
11280                 blanket-derived Into shape must resolve to the same \
11281                 as_str dispatch as the explicit From impl"
11282            );
11283            assert!(
11284                matches!(via_into, std::borrow::Cow::Borrowed(_)),
11285                "Into<Cow<'static, str>>::into on \
11286                 RestartPolicy::{variant:?} must land on the \
11287                 zero-alloc Cow::Borrowed arm — the blanket-derived \
11288                 Into shape must resolve to the same Cow::Borrowed \
11289                 dispatch as the explicit From impl"
11290            );
11291        }
11292    }
11293
11294    #[test]
11295    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11296        // Cross-axis partition pin: the newly lifted trait-idiomatic
11297        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
11298        // (this lift), the paired owned-input `From<RestartPolicy>
11299        // for &'static str` (9fb37d0), and the paired owned-input
11300        // `From<RestartPolicy> for String` (7851725) forward
11301        // projections must resolve identically on every arm, locking
11302        // the three return-shape paths together by construction so any
11303        // future detour trips at caixa-core test time. Also byte-parity
11304        // witness against the sibling [`ToString::to_string`] surface
11305        // routed through [`std::fmt::Display`] — every owned-heap-
11306        // string path (the `Cow::Owned` promotion of this axis's
11307        // `.into_owned()`, `From<RestartPolicy> for String`, and
11308        // `.to_string()`) resolves to the same lifted
11309        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11310        //
11311        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
11312        // witness over [`super::RestartPolicy::ALL`] that
11313        // materializes the three-arm accept-set through the
11314        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
11315        // shape a future `axum::response::IntoResponse` per-policy
11316        // rejection-body composer, a future M4 admission-webhook
11317        // per-policy rejection-reason emitter whose typing rules out
11318        // the sibling [`AsRef<str>`] borrowed return, or a future
11319        // substrate-wide per-policy diagnostic surface that binds
11320        // through a [`Cow<'static, str>`] boundary reaches through.
11321        // The pipe witness also pins the zero-alloc discipline: every
11322        // element in the collected vector satisfies the
11323        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
11324        // accidental silent-allocation regression on the pipe's
11325        // iteration axis is a caixa-core-test-time failure. Peer of
11326        // the first-mover
11327        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11328        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
11329        // — closes the whole owned-input `Cow<'static, str>` +
11330        // paired `{&'static str, String}` cross-axis-parity corner on
11331        // both M2 OTP-shape sibling peers.
11332        for &variant in RestartPolicy::ALL {
11333            let via_cow: std::borrow::Cow<'static, str> =
11334                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11335            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11336            let via_string: String = <String as From<RestartPolicy>>::from(variant);
11337            assert_eq!(
11338                via_cow.as_ref(),
11339                via_static,
11340                "From<RestartPolicy> for Cow<'static, str> and \
11341                 From<RestartPolicy> for &'static str must resolve \
11342                 identically on RestartPolicy::{variant:?} — \
11343                 divergence signals the Cow<'static, str> and \
11344                 &'static str return-shape paths have drifted onto \
11345                 different emit-sets"
11346            );
11347            assert_eq!(
11348                via_cow.as_ref(),
11349                via_string.as_str(),
11350                "From<RestartPolicy> for Cow<'static, str> and \
11351                 From<RestartPolicy> for String must resolve \
11352                 identically on RestartPolicy::{variant:?} — \
11353                 divergence signals the Cow<'static, str> and String \
11354                 return-shape paths have drifted onto different \
11355                 emit-sets"
11356            );
11357            let via_to_string: String = variant.to_string();
11358            assert_eq!(
11359                via_cow.as_ref(),
11360                via_to_string.as_str(),
11361                "From<RestartPolicy> for Cow<'static, str> must \
11362                 byte-equal RestartPolicy::to_string on \
11363                 RestartPolicy::{variant:?} — divergence signals the \
11364                 trait-idiomatic Cow<'static, str> forward-projection \
11365                 axis and the ToString-through-Display axis have \
11366                 drifted onto different emit-sets"
11367            );
11368        }
11369        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11370            .iter()
11371            .copied()
11372            .map(std::borrow::Cow::from)
11373            .collect();
11374        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11375            .iter()
11376            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11377            .collect();
11378        assert_eq!(
11379            via_iter, via_method,
11380            "`.iter().copied().map(Cow::from)` over \
11381             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
11382             Cow::Borrowed(p.as_str()))` on every arm — the \
11383             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
11384             str>` axis is what makes the `Cow::from` composition \
11385             route through the substrate-primitive \
11386             `RestartPolicy::as_str` accessor with the zero-alloc \
11387             Cow::Borrowed arm by construction, rather than a \
11388             per-call-site `Cow::Owned(policy.to_string())` \
11389             allocation"
11390        );
11391        for cow in &via_iter {
11392            assert!(
11393                matches!(cow, std::borrow::Cow::Borrowed(_)),
11394                "every element of the \
11395                 .iter().copied().map(Cow::from) pipe over \
11396                 RestartPolicy::ALL must land on the zero-alloc \
11397                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11398                 signals the pipe's iteration axis has silently \
11399                 allocated where the substrate-primitive \
11400                 RestartPolicy::as_str `&'static str` return makes \
11401                 the borrowed arm the type-correct projection"
11402            );
11403        }
11404    }
11405
11406    #[test]
11407    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11408        // Fail-before-pass-after byte-parity pin on the newly lifted
11409        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
11410        // asserts the borrowed-input standard-library trait impl and
11411        // the substrate-primitive [`super::RestartPolicy::as_str`]
11412        // `pub const fn` accessor resolve to the same three-arm emit-
11413        // set across every arm the exhaustive
11414        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11415        // standard library does not carry a blanket
11416        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11417        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11418        // the borrowed-input `Cow<'static, str>` forward-projection
11419        // axis is a distinct trait-idiomatic surface that a
11420        // `let key: Cow<'static, str> = (&policy).into();`-shaped
11421        // call site or a
11422        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
11423        // reaches through this impl and no other — the paired owned-
11424        // input `From<RestartPolicy> for Cow<'static, str>` impl
11425        // (0612398) forces every borrowed-input call site through an
11426        // explicit `Copy` deref (`Cow::from(*policy)`) or a
11427        // `Cow::Borrowed(policy.as_str())` open-code whose type
11428        // bounds have no compile-time link back to the substrate
11429        // primitive.
11430        //
11431        // Also asserts the projection lands on the zero-alloc
11432        // [`std::borrow::Cow::Borrowed`] arm (not the
11433        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11434        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11435        // return lifetime by construction makes the borrowed arm the
11436        // type-correct projection with no runtime allocation on the
11437        // borrowed-input surface just as on the paired owned-input
11438        // surface.
11439        //
11440        // Closes the `{Self, &Self}` input-shape corner on the M2
11441        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
11442        // the second-of-two-in-M2 closed-set fieldless typed enum peer
11443        // on the caixa surface (`:supervisor :children :restart`),
11444        // exactly as d45c409 closed it on the top-level
11445        // [`super::CaixaKind`] one commit after the owning half
11446        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
11447        // M2 OTP-shape [`super::RestartStrategy`] one commit after
11448        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
11449        // tier of the substrate-wide Cow<'static, str> forward-
11450        // projection campaign on both input-shape corners
11451        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
11452        for &variant in RestartPolicy::ALL {
11453            let via_trait: std::borrow::Cow<'static, str> =
11454                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11455            let via_method: &'static str = variant.as_str();
11456            assert_eq!(
11457                via_trait.as_ref(),
11458                via_method,
11459                "From<&RestartPolicy> for Cow<'static, str> impl must \
11460                 round-trip &RestartPolicy::{variant:?} to the same \
11461                 lifted SUPERVISOR_CHILD_RESTART_* const \
11462                 RestartPolicy::as_str returns — divergence signals a \
11463                 silent detour off the substrate-primitive accessor"
11464            );
11465            assert!(
11466                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11467                "From<&RestartPolicy> for Cow<'static, str> impl must \
11468                 land on the zero-alloc Cow::Borrowed arm on \
11469                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
11470                 signals the projection has silently allocated where \
11471                 the substrate-primitive RestartPolicy::as_str \
11472                 `&'static str` return makes the borrowed arm the \
11473                 type-correct projection"
11474            );
11475            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
11476            assert_eq!(
11477                via_into.as_ref(),
11478                via_method,
11479                "Into<Cow<'static, str>>::into on \
11480                 &RestartPolicy::{variant:?} must byte-equal \
11481                 RestartPolicy::as_str on the same input — the \
11482                 blanket-derived Into shape must resolve to the same \
11483                 as_str dispatch as the explicit From impl"
11484            );
11485            assert!(
11486                matches!(via_into, std::borrow::Cow::Borrowed(_)),
11487                "Into<Cow<'static, str>>::into on \
11488                 &RestartPolicy::{variant:?} must land on the \
11489                 zero-alloc Cow::Borrowed arm — the blanket-derived \
11490                 Into shape must resolve to the same Cow::Borrowed \
11491                 dispatch as the explicit From impl"
11492            );
11493        }
11494    }
11495
11496    #[test]
11497    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11498        // Cross-axis partition pin: the newly lifted trait-idiomatic
11499        // borrowed-input `From<&RestartPolicy> for
11500        // std::borrow::Cow<'static, str>` (this lift), the paired
11501        // owned-input `From<RestartPolicy> for
11502        // std::borrow::Cow<'static, str>` (0612398), the paired
11503        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11504        // for &'static str`, and the paired borrowed-input owned-
11505        // `String` `From<&RestartPolicy> for String` must resolve
11506        // identically on every arm, locking the four
11507        // return-shape × input-shape paths together by construction so
11508        // any future detour trips at caixa-core test time. Also byte-
11509        // parity witness against the sibling [`ToString::to_string`]
11510        // surface routed through [`std::fmt::Display`] — every owned-
11511        // heap-string path (this axis's `.into_owned()` promotion, the
11512        // paired [`From<&RestartPolicy> for String`], and
11513        // `.to_string()`) resolves to the same lifted
11514        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11515        //
11516        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
11517        // over [`super::RestartPolicy::ALL`] — whose iterator yields
11518        // `&RestartPolicy` by construction, so the borrowed-input
11519        // [`Cow<'static, str>`] axis is what routes the pipe through
11520        // the substrate-primitive [`super::RestartPolicy::as_str`]
11521        // accessor without a spurious [`Copy`] deref (which would only
11522        // be reachable through the owned-input
11523        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
11524        // calling `.copied()` on the iterator). The pipe witness also
11525        // pins the zero-alloc discipline: every element in the
11526        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
11527        // arm predicate, so a future accidental silent-allocation
11528        // regression on the pipe's iteration axis is a caixa-core-
11529        // test-time failure. Peer of the sibling
11530        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11531        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
11532        // the whole borrowed-input `Cow<'static, str>` +
11533        // paired `{&'static str, String}` cross-axis-parity corner on
11534        // both M2 OTP-shape sibling peers.
11535        for &policy in RestartPolicy::ALL {
11536            let borrowed_cow: std::borrow::Cow<'static, str> =
11537                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
11538            let owned_cow: std::borrow::Cow<'static, str> =
11539                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
11540            let borrowed_static: &'static str =
11541                <&'static str as From<&RestartPolicy>>::from(&policy);
11542            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
11543            assert_eq!(
11544                borrowed_cow, owned_cow,
11545                "From<&RestartPolicy> for Cow<'static, str> and \
11546                 From<RestartPolicy> for Cow<'static, str> must \
11547                 resolve identically on RestartPolicy::{policy:?} — \
11548                 divergence signals the borrowed-input and owned-input \
11549                 Cow<'static, str> forward-projection input-shape \
11550                 paths have drifted onto different emit-sets"
11551            );
11552            assert_eq!(
11553                borrowed_cow.as_ref(),
11554                borrowed_static,
11555                "From<&RestartPolicy> for Cow<'static, str> and \
11556                 From<&RestartPolicy> for &'static str must resolve \
11557                 identically on RestartPolicy::{policy:?} — \
11558                 divergence signals the borrowed-input Cow<'static, \
11559                 str> and &'static str return-shape paths have drifted \
11560                 onto different emit-sets"
11561            );
11562            assert_eq!(
11563                borrowed_cow.as_ref(),
11564                borrowed_string.as_str(),
11565                "From<&RestartPolicy> for Cow<'static, str> and \
11566                 From<&RestartPolicy> for String must resolve \
11567                 identically on RestartPolicy::{policy:?} — \
11568                 divergence signals the borrowed-input Cow<'static, \
11569                 str> and owned-`String` return-shape paths have \
11570                 drifted onto different emit-sets"
11571            );
11572            let via_to_string: String = policy.to_string();
11573            assert_eq!(
11574                borrowed_cow.as_ref(),
11575                via_to_string.as_str(),
11576                "From<&RestartPolicy> for Cow<'static, str> must \
11577                 byte-equal RestartPolicy::to_string on \
11578                 RestartPolicy::{policy:?} — divergence signals \
11579                 the trait-idiomatic borrowed-input Cow<'static, str> \
11580                 forward-projection axis and the ToString-through-\
11581                 Display axis have drifted onto different emit-sets"
11582            );
11583        }
11584        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11585            .iter()
11586            .map(std::borrow::Cow::from)
11587            .collect();
11588        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11589            .iter()
11590            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11591            .collect();
11592        assert_eq!(
11593            via_iter, via_method,
11594            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
11595             call site whose iteration axis holds `&RestartPolicy` \
11596             by construction — must byte-equal `.iter().map(|p| \
11597             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
11598             input Cow<'static, str> `From<&RestartPolicy> for \
11599             Cow<'static, str>` axis is what makes the `Cow::from` \
11600             composition route through the substrate-primitive \
11601             `RestartPolicy::as_str` accessor with the zero-alloc \
11602             Cow::Borrowed arm by construction and without a spurious \
11603             `Copy` deref (which would only be reachable through the \
11604             owned-input `From<RestartPolicy> for Cow<'static, str>` \
11605             axis by first calling `.copied()` on the iterator)"
11606        );
11607        for cow in &via_iter {
11608            assert!(
11609                matches!(cow, std::borrow::Cow::Borrowed(_)),
11610                "every element of the .iter().map(Cow::from) pipe \
11611                 over RestartPolicy::ALL must land on the zero-\
11612                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
11613                 any arm signals the pipe's iteration axis has \
11614                 silently allocated where the substrate-primitive \
11615                 RestartPolicy::as_str `&'static str` return makes \
11616                 the borrowed arm the type-correct projection"
11617            );
11618        }
11619    }
11620
11621    #[test]
11622    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
11623        // Fail-before-pass-after byte-parity pin on the newly lifted
11624        // `impl From<RestartPolicy> for Box<str>` — asserts the
11625        // owned-input standard-library trait impl and the
11626        // substrate-primitive [`super::RestartPolicy::as_str`]
11627        // `pub const fn` accessor resolve to the same three-arm emit-
11628        // set across every arm the exhaustive
11629        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11630        // substrate-wide `Box<str>` forward-projection campaign tier
11631        // opened one commit prior (69ef45c) on the paired sibling-
11632        // restart [`RestartStrategy`] onto the second (and third-and-
11633        // final) M2 OTP-shape closed-set fieldless typed enum peer on
11634        // the caixa surface (`:children :restart`), immediately after
11635        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
11636        // closed the
11637        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11638        // 2×3 corner on this enum. Rust's standard library carries
11639        // `impl From<&str> for Box<str>` and
11640        // `impl From<String> for Box<str>` but no blanket
11641        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11642        // a distinct trait-idiomatic surface that a
11643        // `let key: Box<str> = policy.into();`-shaped call site
11644        // reaches through this impl and no other — a paired
11645        // `Box::from(policy.as_str())` open-code has no compile-time
11646        // link back to the substrate primitive. Peer of the sibling
11647        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
11648        // (69ef45c) — extends the trait-idiomatic owned-input
11649        // [`Box<str>`] forward-projection axis onto the third and
11650        // final M2-OTP-shape closed-set typed enum on the caixa
11651        // surface.
11652        for &variant in RestartPolicy::ALL {
11653            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11654            let via_method: &'static str = variant.as_str();
11655            assert_eq!(
11656                via_trait.as_ref(),
11657                via_method,
11658                "From<RestartPolicy> for Box<str> impl must round-\
11659                 trip RestartPolicy::{variant:?} to the same lifted \
11660                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11661                 returns — divergence signals a silent detour off the \
11662                 substrate-primitive accessor"
11663            );
11664            let via_into: Box<str> = variant.into();
11665            assert_eq!(
11666                via_into.as_ref(),
11667                via_method,
11668                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
11669                 must byte-equal RestartPolicy::as_str on the same \
11670                 input — the blanket-derived Into shape must resolve \
11671                 to the same as_str dispatch as the explicit From impl"
11672            );
11673        }
11674    }
11675
11676    #[test]
11677    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11678        // Fail-before-pass-after byte-parity pin on the newly lifted
11679        // `impl From<&RestartPolicy> for Box<str>` — asserts the
11680        // borrowed-input standard-library trait impl and the
11681        // substrate-primitive [`super::RestartPolicy::as_str`]
11682        // `pub const fn` accessor resolve to the same three-arm emit-
11683        // set across every arm the exhaustive
11684        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11685        // standard library does not carry a blanket
11686        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11687        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11688        // so the borrowed-input `Box<str>` forward-projection axis
11689        // is a distinct trait-idiomatic surface that a
11690        // `let key: Box<str> = (&policy).into();`-shaped call site
11691        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
11692        // shaped pipe reaches through this impl and no other — the
11693        // paired owned-input `From<RestartPolicy> for Box<str>`
11694        // impl (0a1b313) forces every borrowed-input call site
11695        // through an explicit `Copy` deref
11696        // (`Box::<str>::from((*policy).as_str())`) or a
11697        // `Box::<str>::from(policy.as_str())` open-code whose
11698        // type bounds have no compile-time link back to the
11699        // substrate primitive.
11700        //
11701        // Fourth (and closing) peer on the substrate-wide trait-
11702        // idiomatic [`Box<str>`] forward-projection family on the
11703        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11704        // shape corner of the [`Box<str>`] axis on the second (and
11705        // third-and-final) M2 OTP-shape closed-set fieldless typed
11706        // enum peer on the caixa surface (`:children :restart`),
11707        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11708        // axis one commit after its owning half (0612398) landed
11709        // on this enum. Every remaining closed-set fieldless typed
11710        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11711        // render-side / outside-caixa-core tiers is a future
11712        // target of the campaign.
11713        //
11714        // Also byte-parity witness against the paired owned-input
11715        // [`From<RestartPolicy> for Box<str>`] and the sibling
11716        // borrowed-input [`From<&RestartPolicy> for &'static str`],
11717        // [`From<&RestartPolicy> for String`], and
11718        // [`From<&RestartPolicy> for Cow<'static, str>`]
11719        // return-shape axes — locking the four
11720        // return-shape × input-shape paths together by construction
11721        // so any future detour trips at caixa-core test time. Then a
11722        // `.iter().map(Box::<str>::from)` pipe witness over
11723        // [`super::RestartPolicy::ALL`] — whose iterator yields
11724        // `&RestartPolicy` by construction, so the borrowed-input
11725        // [`Box<str>`] axis is what routes the pipe through the
11726        // substrate-primitive [`super::RestartPolicy::as_str`]
11727        // accessor without a spurious [`Copy`] deref (which would
11728        // only be reachable through the owned-input
11729        // [`From<RestartPolicy> for Box<str>`] axis by first
11730        // calling `.copied()` on the iterator).
11731        for &variant in RestartPolicy::ALL {
11732            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11733            let via_method: &'static str = variant.as_str();
11734            assert_eq!(
11735                via_trait.as_ref(),
11736                via_method,
11737                "From<&RestartPolicy> for Box<str> impl must round-\
11738                 trip &RestartPolicy::{variant:?} to the same lifted \
11739                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11740                 returns — divergence signals a silent detour off the \
11741                 substrate-primitive accessor"
11742            );
11743            let via_into: Box<str> = (&variant).into();
11744            assert_eq!(
11745                via_into.as_ref(),
11746                via_method,
11747                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11748                 must byte-equal RestartPolicy::as_str on the same \
11749                 input — the blanket-derived Into shape must resolve \
11750                 to the same as_str dispatch as the explicit From impl"
11751            );
11752            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11753            assert_eq!(
11754                via_trait, owned_box,
11755                "From<&RestartPolicy> for Box<str> and \
11756                 From<RestartPolicy> for Box<str> must resolve \
11757                 identically on RestartPolicy::{variant:?} — \
11758                 divergence signals the borrowed-input and owned-input \
11759                 Box<str> forward-projection input-shape paths have \
11760                 drifted onto different emit-sets"
11761            );
11762            let borrowed_static: &'static str =
11763                <&'static str as From<&RestartPolicy>>::from(&variant);
11764            assert_eq!(
11765                via_trait.as_ref(),
11766                borrowed_static,
11767                "From<&RestartPolicy> for Box<str> and \
11768                 From<&RestartPolicy> for &'static str must resolve \
11769                 identically on RestartPolicy::{variant:?} — \
11770                 divergence signals the borrowed-input Box<str> and \
11771                 &'static str return-shape paths have drifted onto \
11772                 different emit-sets"
11773            );
11774            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11775            assert_eq!(
11776                via_trait.as_ref(),
11777                borrowed_string.as_str(),
11778                "From<&RestartPolicy> for Box<str> and \
11779                 From<&RestartPolicy> for String must resolve \
11780                 identically on RestartPolicy::{variant:?} — \
11781                 divergence signals the borrowed-input Box<str> and \
11782                 owned-`String` return-shape paths have drifted onto \
11783                 different emit-sets"
11784            );
11785            let borrowed_cow: std::borrow::Cow<'static, str> =
11786                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11787            assert_eq!(
11788                via_trait.as_ref(),
11789                borrowed_cow.as_ref(),
11790                "From<&RestartPolicy> for Box<str> and \
11791                 From<&RestartPolicy> for Cow<'static, str> must \
11792                 resolve identically on RestartPolicy::{variant:?} — \
11793                 divergence signals the borrowed-input Box<str> and \
11794                 Cow<'static, str> return-shape paths have drifted \
11795                 onto different emit-sets"
11796            );
11797        }
11798        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11799        let via_method: Vec<Box<str>> = RestartPolicy::ALL
11800            .iter()
11801            .map(|p| Box::<str>::from(p.as_str()))
11802            .collect();
11803        assert_eq!(
11804            via_iter, via_method,
11805            "`.iter().map(Box::<str>::from)` over \
11806             RestartPolicy::ALL — a call site whose iteration axis \
11807             holds `&RestartPolicy` by construction — must byte-\
11808             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11809             on every arm — the borrowed-input Box<str> \
11810             `From<&RestartPolicy> for Box<str>` axis is what \
11811             makes the `Box::<str>::from` composition route through \
11812             the substrate-primitive `RestartPolicy::as_str` \
11813             accessor without a spurious `Copy` deref (which would \
11814             only be reachable through the owned-input \
11815             `From<RestartPolicy> for Box<str>` axis by first \
11816             calling `.copied()` on the iterator)"
11817        );
11818    }
11819
11820    #[test]
11821    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11822        // Fail-before-pass-after byte-parity pin on the newly lifted
11823        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11824        // the owned-input standard-library trait impl and the
11825        // substrate-primitive [`super::RestartPolicy::as_str`]
11826        // `pub const fn` accessor resolve to the same three-arm emit-
11827        // set across every arm the exhaustive
11828        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11829        // substrate-wide [`std::sync::Arc<str>`] forward-projection
11830        // campaign tier opened one projection tier prior (bca2ec8) on
11831        // the paired sibling-restart [`RestartStrategy`] owned-input
11832        // first-mover onto the second (and third-and-final) M2 OTP-
11833        // shape closed-set fieldless typed enum peer on the caixa
11834        // surface (`:children :restart`), immediately after the paired
11835        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11836        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11837        // Box<str>}` 2×4 corner on this enum. Rust's standard library
11838        // carries `impl From<&str> for std::sync::Arc<str>` and
11839        // `impl From<String> for std::sync::Arc<str>` but no blanket
11840        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11841        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11842        // so this axis is a distinct trait-idiomatic surface that a
11843        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11844        // site reaches through this impl and no other — a paired
11845        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11846        // has no compile-time link back to the substrate primitive,
11847        // and a two-step `std::sync::Arc::<str>::from(String::from(
11848        // policy))` composition through the owned-`String` axis
11849        // allocates twice (once into the intermediate `String`, once
11850        // into the [`Arc<str>`] on the `From<String>` conversion)
11851        // where the single-step trait impl allocates once.
11852        //
11853        // Cross-axis byte-parity witness against the sibling owned-
11854        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11855        // return-shape axes — locking the five return-shape paths on
11856        // the owned-input surface together by construction so any
11857        // future detour off the substrate-primitive
11858        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11859        // core test time.
11860        for &variant in RestartPolicy::ALL {
11861            let via_trait: std::sync::Arc<str> =
11862                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11863            let via_method: &'static str = variant.as_str();
11864            assert_eq!(
11865                via_trait.as_ref(),
11866                via_method,
11867                "From<RestartPolicy> for std::sync::Arc<str> impl \
11868                 must round-trip RestartPolicy::{variant:?} to the \
11869                 same lifted SUPERVISOR_CHILD_RESTART_* const \
11870                 RestartPolicy::as_str returns — divergence signals \
11871                 a silent detour off the substrate-primitive accessor"
11872            );
11873            let via_into: std::sync::Arc<str> = variant.into();
11874            assert_eq!(
11875                via_into.as_ref(),
11876                via_method,
11877                "Into<std::sync::Arc<str>>::into on \
11878                 RestartPolicy::{variant:?} must byte-equal \
11879                 RestartPolicy::as_str on the same input — the \
11880                 blanket-derived Into shape must resolve to the same \
11881                 as_str dispatch as the explicit From impl"
11882            );
11883            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11884            assert_eq!(
11885                via_trait.as_ref(),
11886                owned_static,
11887                "From<RestartPolicy> for std::sync::Arc<str> and \
11888                 From<RestartPolicy> for &'static str must resolve \
11889                 identically on RestartPolicy::{variant:?} — \
11890                 divergence signals the owned-input std::sync::Arc<str> \
11891                 and &'static str return-shape paths have drifted onto \
11892                 different emit-sets"
11893            );
11894            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11895            assert_eq!(
11896                via_trait.as_ref(),
11897                owned_string.as_str(),
11898                "From<RestartPolicy> for std::sync::Arc<str> and \
11899                 From<RestartPolicy> for String must resolve \
11900                 identically on RestartPolicy::{variant:?} — \
11901                 divergence signals the owned-input std::sync::Arc<str> \
11902                 and owned-`String` return-shape paths have drifted \
11903                 onto different emit-sets"
11904            );
11905            let owned_cow: std::borrow::Cow<'static, str> =
11906                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11907            assert_eq!(
11908                via_trait.as_ref(),
11909                owned_cow.as_ref(),
11910                "From<RestartPolicy> for std::sync::Arc<str> and \
11911                 From<RestartPolicy> for Cow<'static, str> must \
11912                 resolve identically on RestartPolicy::{variant:?} — \
11913                 divergence signals the owned-input std::sync::Arc<str> \
11914                 and Cow<'static, str> return-shape paths have drifted \
11915                 onto different emit-sets"
11916            );
11917            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11918            assert_eq!(
11919                via_trait.as_ref(),
11920                owned_box.as_ref(),
11921                "From<RestartPolicy> for std::sync::Arc<str> and \
11922                 From<RestartPolicy> for Box<str> must resolve \
11923                 identically on RestartPolicy::{variant:?} — \
11924                 divergence signals the owned-input std::sync::Arc<str> \
11925                 and Box<str> return-shape paths have drifted onto \
11926                 different emit-sets"
11927            );
11928        }
11929    }
11930
11931    #[test]
11932    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11933        // Fail-before-pass-after byte-parity pin on the newly lifted
11934        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
11935        // asserts the borrowed-input standard-library trait impl and
11936        // the substrate-primitive [`super::RestartPolicy::as_str`]
11937        // `pub const fn` accessor resolve to the same three-arm
11938        // emit-set across every arm the exhaustive
11939        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11940        // standard library carries `impl From<&str> for
11941        // std::sync::Arc<str>` and `impl From<String> for
11942        // std::sync::Arc<str>` but no blanket
11943        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11944        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11945        // so the borrowed-input [`std::sync::Arc<str>`] forward-
11946        // projection axis is a distinct trait-idiomatic surface that
11947        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
11948        // call site or a
11949        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11950        // shaped pipe reaches through this impl and no other — the
11951        // paired owned-input [`From<RestartPolicy> for
11952        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
11953        // input call site through an explicit [`Copy`] deref
11954        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
11955        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11956        // whose type bounds have no compile-time link back to the
11957        // substrate primitive.
11958        //
11959        // Closes the `{Self, &Self}` input-shape corner of the
11960        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
11961        // forward-projection family on the second (and third-and-
11962        // final) M2 OTP-shape closed-set fieldless typed enum peer
11963        // on the caixa surface (`:children :restart`), one commit
11964        // after b05724e opened the owned-input half — exactly as
11965        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
11966        // the sibling-restart [`RestartStrategy`] first-mover one
11967        // commit after its owning half (bca2ec8) landed, and as
11968        // cb1d068 closed the paired [`Box<str>`] corner on this
11969        // enum one commit after its owning half (0a1b313) landed.
11970        //
11971        // Also byte-parity witness against the paired owned-input
11972        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
11973        // sibling borrowed-input [`From<&RestartPolicy> for
11974        // &'static str`], [`From<&RestartPolicy> for String`],
11975        // [`From<&RestartPolicy> for Cow<'static, str>`], and
11976        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
11977        // locking the five return-shape × input-shape paths together
11978        // by construction so any future detour off the substrate-
11979        // primitive [`super::RestartPolicy::as_str`] accessor trips
11980        // at caixa-core test time. Then a
11981        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
11982        // over [`super::RestartPolicy::ALL`] — whose iterator yields
11983        // `&RestartPolicy` by construction, so the borrowed-input
11984        // [`std::sync::Arc<str>`] axis is what routes the pipe
11985        // through the substrate-primitive
11986        // [`super::RestartPolicy::as_str`] accessor without a
11987        // spurious [`Copy`] deref (which would only be reachable
11988        // through the owned-input
11989        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
11990        // first calling `.copied()` on the iterator).
11991        for &variant in RestartPolicy::ALL {
11992            let via_trait: std::sync::Arc<str> =
11993                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
11994            let via_method: &'static str = variant.as_str();
11995            assert_eq!(
11996                via_trait.as_ref(),
11997                via_method,
11998                "From<&RestartPolicy> for std::sync::Arc<str> impl \
11999                 must round-trip &RestartPolicy::{variant:?} to the \
12000                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12001                 RestartPolicy::as_str returns — divergence signals \
12002                 a silent detour off the substrate-primitive accessor"
12003            );
12004            let via_into: std::sync::Arc<str> = (&variant).into();
12005            assert_eq!(
12006                via_into.as_ref(),
12007                via_method,
12008                "Into<std::sync::Arc<str>>::into on \
12009                 &RestartPolicy::{variant:?} must byte-equal \
12010                 RestartPolicy::as_str on the same input — the \
12011                 blanket-derived Into shape must resolve to the same \
12012                 as_str dispatch as the explicit From impl"
12013            );
12014            let owned_arc: std::sync::Arc<str> =
12015                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12016            assert_eq!(
12017                via_trait, owned_arc,
12018                "From<&RestartPolicy> for std::sync::Arc<str> and \
12019                 From<RestartPolicy> for std::sync::Arc<str> must \
12020                 resolve identically on RestartPolicy::{variant:?} — \
12021                 divergence signals the borrowed-input and owned-input \
12022                 std::sync::Arc<str> forward-projection input-shape \
12023                 paths have drifted onto different emit-sets"
12024            );
12025            let borrowed_static: &'static str =
12026                <&'static str as From<&RestartPolicy>>::from(&variant);
12027            assert_eq!(
12028                via_trait.as_ref(),
12029                borrowed_static,
12030                "From<&RestartPolicy> for std::sync::Arc<str> and \
12031                 From<&RestartPolicy> for &'static str must resolve \
12032                 identically on RestartPolicy::{variant:?} — \
12033                 divergence signals the borrowed-input std::sync::Arc<str> \
12034                 and &'static str return-shape paths have drifted onto \
12035                 different emit-sets"
12036            );
12037            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12038            assert_eq!(
12039                via_trait.as_ref(),
12040                borrowed_string.as_str(),
12041                "From<&RestartPolicy> for std::sync::Arc<str> and \
12042                 From<&RestartPolicy> for String must resolve \
12043                 identically on RestartPolicy::{variant:?} — \
12044                 divergence signals the borrowed-input std::sync::Arc<str> \
12045                 and owned-`String` return-shape paths have drifted \
12046                 onto different emit-sets"
12047            );
12048            let borrowed_cow: std::borrow::Cow<'static, str> =
12049                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12050            assert_eq!(
12051                via_trait.as_ref(),
12052                borrowed_cow.as_ref(),
12053                "From<&RestartPolicy> for std::sync::Arc<str> and \
12054                 From<&RestartPolicy> for Cow<'static, str> must \
12055                 resolve identically on RestartPolicy::{variant:?} — \
12056                 divergence signals the borrowed-input std::sync::Arc<str> \
12057                 and Cow<'static, str> return-shape paths have drifted \
12058                 onto different emit-sets"
12059            );
12060            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12061            assert_eq!(
12062                via_trait.as_ref(),
12063                borrowed_box.as_ref(),
12064                "From<&RestartPolicy> for std::sync::Arc<str> and \
12065                 From<&RestartPolicy> for Box<str> must resolve \
12066                 identically on RestartPolicy::{variant:?} — \
12067                 divergence signals the borrowed-input std::sync::Arc<str> \
12068                 and Box<str> return-shape paths have drifted onto \
12069                 different emit-sets"
12070            );
12071        }
12072        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12073            .iter()
12074            .map(std::sync::Arc::<str>::from)
12075            .collect();
12076        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12077            .iter()
12078            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
12079            .collect();
12080        assert_eq!(
12081            via_iter, via_method,
12082            "`.iter().map(std::sync::Arc::<str>::from)` over \
12083             RestartPolicy::ALL — a call site whose iteration axis \
12084             holds `&RestartPolicy` by construction — must byte-\
12085             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
12086             on every arm — the borrowed-input std::sync::Arc<str> \
12087             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
12088             what makes the `std::sync::Arc::<str>::from` composition \
12089             route through the substrate-primitive \
12090             `RestartPolicy::as_str` accessor without a spurious \
12091             `Copy` deref (which would only be reachable through the \
12092             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
12093             axis by first calling `.copied()` on the iterator)"
12094        );
12095    }
12096
12097    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
12098
12099    #[test]
12100    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
12101        // The fail-before-pass-after pin: pre-lift there was no
12102        // single-source binding between the [`RestartPolicy`] variant
12103        // name the un-`rename`d `Serialize` derive emits under
12104        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
12105        // byte-string every downstream cluster-side dispatcher (the
12106        // future wasm-operator's per-child post-exit restart-decision
12107        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
12108        // materializer's admission-time enum-arm bind, the
12109        // `caixa-operator`'s hierarchical reconciliation scheduler's
12110        // per-child-policy fan-out) probes verbatim. A future
12111        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
12112        // or a per-variant `#[serde(rename = "…")]` override, or a
12113        // variant rename in the source — would silently rebrand the
12114        // emitted scalar under one spelling while every downstream
12115        // dispatcher still probed the other, with the failure surfacing
12116        // at the operator's reconcile posture (children coming up under
12117        // the `default()` `Permanent` arm rather than the typed slot's
12118        // declared policy — a `:temporary` `oneShot` child would be
12119        // restarted on clean exit, treating the successful-completion
12120        // signal as failure and re-running the completion-terminal
12121        // one-shot indefinitely; a `:transient` child that clean-exited
12122        // would be restarted, masking the clean-completion contract)
12123        // far from the source rebrand commit and with no field naming
12124        // the drift. Pinning the two paths (the `Serialize` derive's
12125        // serialized string AND the [`RestartPolicy::as_str`] helper)
12126        // to the same three lifted
12127        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
12128        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
12129        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
12130        // byte-strings makes any future drift on either endpoint fail
12131        // here at caixa-core build time. Peer of the sibling
12132        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
12133        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12134        // and the M3
12135        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
12136        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
12137        // same three-path-convergence discipline, extended to close the
12138        // third OTP-shaped closed-enum discriminator axis on the caixa
12139        // typed surface (per-child restart-decision policy).
12140        for (variant, expected) in [
12141            (
12142                RestartPolicy::Permanent,
12143                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12144            ),
12145            (
12146                RestartPolicy::Temporary,
12147                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12148            ),
12149            (
12150                RestartPolicy::Transient,
12151                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12152            ),
12153        ] {
12154            let json = serde_json::to_string(&variant).unwrap();
12155            assert_eq!(
12156                json,
12157                format!("\"{expected}\""),
12158                "RestartPolicy::{variant:?} must serialize to {expected:?}"
12159            );
12160            assert_eq!(
12161                variant.as_str(),
12162                expected,
12163                "RestartPolicy::{variant:?}.as_str() must return the lifted \
12164                 SUPERVISOR_CHILD_RESTART_* constant"
12165            );
12166        }
12167    }
12168
12169    #[test]
12170    fn supervisor_child_restart_consts_are_pairwise_distinct() {
12171        // Cross-arm drift-detection pin: a future collapse of two
12172        // canonical variant byte-strings onto the same value (e.g. an
12173        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
12174        // to also read `"Permanent"`) would silently reroute every
12175        // downstream operator's per-child-policy dispatch onto the
12176        // sibling arm's reconcile branch and pass every propagation-probe
12177        // test that expected only the stale arm's value — a `:transient`
12178        // child would come up under the `:permanent` restart-decision
12179        // posture on every subsequent clean exit, so a completion-terminal
12180        // child would be restarted indefinitely against its declared
12181        // policy. Peer of the sibling
12182        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
12183        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12184        // and the four-way distinct pin
12185        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
12186        // top-level `SUPERVISOR_KEY_*` axis.
12187        let all = [
12188            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12189            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12190            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12191        ];
12192        for (i, a) in all.iter().enumerate() {
12193            for (j, b) in all.iter().enumerate() {
12194                if i != j {
12195                    assert_ne!(
12196                        a, b,
12197                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
12198                         — got duplicate {a:?} at indices {i} and {j}",
12199                    );
12200                }
12201            }
12202        }
12203    }
12204
12205    #[test]
12206    fn restart_policy_display_routes_through_as_str_helper() {
12207        // The fail-before-pass-after pin on the first half of the
12208        // three-path convergence: pre-convergence [`RestartPolicy`]
12209        // carried a [`std::fmt::Display`] surface via its
12210        // `#[discriminant(also_display)]` gen-platform derive route,
12211        // which arrived kebab-case as `"permanent"` / `"temporary"`
12212        // / `"transient"` on this three-arm enum (whose variant
12213        // names each collapse to their own lowercase form under the
12214        // kebab-case transform) while the wire format ran as
12215        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
12216        // through the un-`rename`d serde derive. Every consumer
12217        // reaching for a policy byte-string past the wire format had
12218        // to pick between three paths ([`RestartPolicy::as_str`],
12219        // the `Serialize` derive's serialized string, or
12220        // `format!("{v}")` on the discriminant-Display route), any
12221        // two of which a future variant rename or
12222        // `#[serde(rename_all = "kebab-case")]` attribute would
12223        // silently desynchronize. Wiring [`std::fmt::Display`]
12224        // through [`RestartPolicy::as_str`] closes the third path:
12225        // every `format!("{v}")` call reaches the same lifted
12226        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
12227        // wire format and the [`RestartPolicy::as_str`] helper
12228        // already route through, so a future variant rename lands at
12229        // exactly one place. Pin the routing here so a future
12230        // `impl std::fmt::Display for RestartPolicy`
12231        // reimplementation that hand-rolls the arms instead of
12232        // delegating to [`RestartPolicy::as_str`] fails at
12233        // caixa-core build time. Peer of the sibling
12234        // [`restart_strategy_display_routes_through_as_str_helper`]
12235        // on the per-supervisor sibling-restart-strategy axis and
12236        // the M3
12237        // `placement_strategy_display_routes_through_as_str_helper`
12238        // (cc8f749) — the third of three OTP-shape closed-enum
12239        // discriminator axes on the caixa typed surface now
12240        // converged onto the same three-path
12241        // (Display → as_str → lifted const) discipline.
12242        for variant in [
12243            RestartPolicy::Permanent,
12244            RestartPolicy::Temporary,
12245            RestartPolicy::Transient,
12246        ] {
12247            assert_eq!(
12248                variant.to_string(),
12249                variant.as_str(),
12250                "RestartPolicy::{variant:?} Display must route through \
12251                 RestartPolicy::as_str (single source of truth: the lifted \
12252                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
12253            );
12254        }
12255    }
12256
12257    #[test]
12258    fn restart_policy_display_matches_serialized_wire_byte_string() {
12259        // The fail-before-pass-after pin on the second half of the
12260        // three-path convergence: `Display` (user-facing text) agrees
12261        // byte-for-byte with the `Serialize` derive's wire format
12262        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
12263        // scalar) on every variant. Pre-convergence the two paths
12264        // were structurally independent — a future
12265        // `#[serde(rename_all = "kebab-case")]` attribute on the
12266        // enum would silently rebrand the emitted wire scalar
12267        // (`permanent`, `temporary`, `transient`) while every
12268        // consumer that pretty-prints the policy (the future
12269        // wasm-operator's per-child post-exit restart-decision
12270        // diagnostic line, the future `feira app graph` per-child
12271        // restart column, the future M4
12272        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
12273        // per-child admission-webhook rejection body) would still
12274        // emit the PascalCase form the `as_str` / `Display` route
12275        // returns, with the mismatch surfacing at consumer parse
12276        // time / operator dispatch time far from the source rebrand
12277        // commit. Pin the two paths byte-for-byte here so any future
12278        // serde-attribute or variant-rename drift is a
12279        // caixa-core-build-time test failure at this call, not a
12280        // silent per-consumer dispatch miss. Peer of the sibling
12281        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
12282        // on the per-supervisor sibling-restart-strategy axis and
12283        // the M3
12284        // `placement_strategy_display_matches_serialized_wire_byte_string`
12285        // (cc8f749).
12286        for variant in [
12287            RestartPolicy::Permanent,
12288            RestartPolicy::Temporary,
12289            RestartPolicy::Transient,
12290        ] {
12291            let wire = serde_json::to_string(&variant).unwrap();
12292            let unquoted = wire
12293                .strip_prefix('"')
12294                .and_then(|s| s.strip_suffix('"'))
12295                .expect("serialized RestartPolicy is a JSON string");
12296            assert_eq!(
12297                variant.to_string(),
12298                unquoted,
12299                "RestartPolicy::{variant:?} Display byte-string must match the \
12300                 Serialize derive's wire byte-string (three-path convergence: \
12301                 Display + as_str + Serialize all resolve to the same \
12302                 SUPERVISOR_CHILD_RESTART_* const)"
12303            );
12304        }
12305    }
12306
12307    #[test]
12308    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
12309        // Fail-before-pass-after byte-parity pin on the lifted
12310        // `impl AsRef<str> for RestartPolicy` — asserts the
12311        // standard-library trait impl and the substrate-primitive
12312        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
12313        // to the same `&str` per instance across the three-arm
12314        // closed set, so any future silent detour that routes the
12315        // impl through a divergent projection (a per-arm inline
12316        // `match self { RestartPolicy::Permanent => "Permanent", … }`
12317        // re-inlining that opens a compile-time link to the un-lifted
12318        // arm-literal, a swap onto the kebab-case
12319        // [`gen_platform::Discriminant`] catalog identity that would
12320        // collide the wire axis with the dispatcher-catalog axis) trips
12321        // at caixa-core test time under `PartialEq` rather than at a
12322        // downstream `impl AsRef<str>`-bound consumer's silent split.
12323        // Sweeps every one of the three arms
12324        // [`RestartPolicy::ALL`] carries so no arm's projection is
12325        // covered only by the sibling wire-format `Serialize` derive
12326        // path. Peer of the sibling
12327        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
12328        // (63eb1a4) on the paired per-supervisor sibling-restart-
12329        // strategy axis and the [`crate::CaixaVersion`]
12330        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
12331        // top-level `:versao` typed newtype — the three pins together
12332        // cover the substrate primitive's `AsRef<str>` projection axis
12333        // on the paired newtype + M2 closed-set-typed-enum surface.
12334        for &variant in RestartPolicy::ALL {
12335            assert_eq!(
12336                <RestartPolicy as AsRef<str>>::as_ref(&variant),
12337                variant.as_str(),
12338                "AsRef<str> impl on RestartPolicy::{variant:?} must \
12339                 byte-equal RestartPolicy::as_str on the same instance \
12340                 — divergence signals a silent detour off the substrate-\
12341                 primitive accessor"
12342            );
12343        }
12344    }
12345
12346    #[test]
12347    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
12348        // Fail-before-pass-after byte-parity pin on the three-path
12349        // convergence discipline the M2 per-child-restart-policy
12350        // primitive now carries on the `&str`-projection axis:
12351        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
12352        // lifted impl), `format!("{v}")` (the pre-existing
12353        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
12354        // primitive `pub const fn` accessor both trait impls delegate
12355        // through) must resolve to the same byte-string on every
12356        // instance across the three-arm closed set. Refuses any future
12357        // divergence between the two trait impls (a stray
12358        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
12359        // rather than delegating through the shared accessor; a
12360        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
12361        // literal cascade) that would silently split the two
12362        // projection paths of the same closed-set typed enum. Mirrors
12363        // the sibling three-path-convergence discipline the peer
12364        // [`RestartStrategy`] typed enum carries on its
12365        // `AsRef<str>` / `Display` / `as_str` triple
12366        // (supervisor.rs pin
12367        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
12368        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
12369        // carries on the same triple (version.rs pin
12370        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
12371        // 16d5c7e).
12372        for &variant in RestartPolicy::ALL {
12373            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12374            let via_display: String = format!("{variant}");
12375            let via_accessor: &str = variant.as_str();
12376            assert_eq!(via_as_ref, via_accessor);
12377            assert_eq!(via_display, via_accessor);
12378            assert_eq!(via_as_ref, via_display.as_str());
12379        }
12380    }
12381
12382    #[test]
12383    fn restart_policy_all_enumerates_every_variant_exactly_once() {
12384        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
12385        // exhaustive-iteration surface: every variant appears exactly
12386        // once, and the slice length matches the arm count of the
12387        // closed set. Every consumer that walks the accepted-policy
12388        // set (a future `feira supervisor --restart …` CLI-side
12389        // arg-parse's "did you mean" hint, a future M4 admission-
12390        // webhook's per-child rejection body naming the accepted-
12391        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
12392        // projection consumers that iterate the accept-set for
12393        // diagnostic rendering) reads through this slice, so a future
12394        // arm addition that grows the enum but forgets to grow
12395        // [`Self::ALL`] silently truncates every downstream consumer's
12396        // accept-set at the same pre-addition boundary — this pin
12397        // fails at caixa-core build time on the pairwise-distinct +
12398        // arm-count invariants.
12399        //
12400        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
12401        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
12402        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
12403        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
12404        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
12405        // pins on the peer closed-set typed-enum axes.
12406        let all: &[RestartPolicy] = RestartPolicy::ALL;
12407        assert_eq!(
12408            all.len(),
12409            3,
12410            "RestartPolicy::ALL must enumerate every variant of the \
12411             three-arm closed set (Permanent, Temporary, Transient); \
12412             got {all:?}"
12413        );
12414        for (i, a) in all.iter().enumerate() {
12415            for (j, b) in all.iter().enumerate() {
12416                if i != j {
12417                    assert_ne!(
12418                        a, b,
12419                        "RestartPolicy::ALL must carry every variant exactly \
12420                         once — got duplicate {a:?} at indices {i} and {j}"
12421                    );
12422                }
12423            }
12424        }
12425        for variant in [
12426            RestartPolicy::Permanent,
12427            RestartPolicy::Temporary,
12428            RestartPolicy::Transient,
12429        ] {
12430            assert!(
12431                all.contains(&variant),
12432                "RestartPolicy::ALL must contain {variant:?} — a future arm \
12433                 addition that grows the enum but forgets to grow the ALL slice \
12434                 silently truncates every downstream consumer's accept-set at \
12435                 the pre-addition boundary"
12436            );
12437        }
12438    }
12439
12440    #[test]
12441    fn restart_policy_wire_names_covers_every_arm() {
12442        // Load-bearing pin on the substrate-canonical
12443        // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
12444        // the `PascalCase` wire byte-string axis: every variant of the
12445        // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
12446        // must project through [`RestartPolicy::as_str`] onto an entry
12447        // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
12448        // roster's length must byte-equal `RestartPolicy::ALL.len()` so
12449        // a silent skew between the [`RestartPolicy::as_str`] match's
12450        // arm-set and the roster's arm-set trips here at caixa-core
12451        // test time rather than at a downstream M4
12452        // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
12453        // rejection body's wire-form `:restart` accepted-set
12454        // enumeration miss / a `feira supervisor --restart …` "did you
12455        // mean" hint drift / a future wasm-operator per-reconcile-step
12456        // diagnostic log line's accepted-wire-form enumeration miss.
12457        // A future arm addition (an OTP-`intrinsic` fourth arm the
12458        // theory
12459        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
12460        // might reach for once the three canonical OTP restart policies
12461        // stop covering the substrate's discovered load-shape) extends
12462        // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
12463        // the new arm by iteration; the paired
12464        // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
12465        // this assertion trips. Every entry is further pinned to open
12466        // with an ASCII uppercase byte so a silent collapse of the
12467        // wire-form axis with the peer kebab-case dispatcher-catalog
12468        // axis (an entry byte-identical to a sibling
12469        // [`RestartPolicy::discriminant`] kebab byte-string that would
12470        // let a wire-axis consumer accept the dispatcher-catalog
12471        // vocabulary) trips here rather than at a downstream K8s-CR
12472        // round-trip miss.
12473        //
12474        // Peer of the sibling
12475        // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
12476        // pin on the first M2 OTP-shape sibling-restart closed-set
12477        // typed enum, the sibling
12478        // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
12479        // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
12480        // closed-set typed enum, the sibling
12481        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
12482        // (bd708bd) pin on the top-level typed-kind discriminator's
12483        // `PascalCase` wire byte-string axis, and the sibling
12484        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
12485        // (cc42c0e) /
12486        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
12487        // (1898d77) pins on the OTP-appup discriminator's two-axis
12488        // roster split — the same closed-set exhaustive-roster coverage
12489        // discipline extended here onto the second and final M2
12490        // OTP-shape sibling-enum on the caixa surface, closing the
12491        // per-child restart-decision-policy axis paired with the peer
12492        // per-supervisor sibling-restart-strategy axis on the same M2
12493        // `:supervisor` slot.
12494        //
12495        // Fail-before-pass-after locally verified by mutating one arm
12496        // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12497        // const family (e.g. dropping the trailing `t` from
12498        // `"Permanent"` → `"Permanen"`) — the length pin still passes
12499        // but the `contains` check fires on the mutated arm; and by
12500        // shortening the roster to two entries — the length pin fires
12501        // first.
12502        assert_eq!(
12503            RestartPolicy::WIRE_NAMES.len(),
12504            RestartPolicy::ALL.len(),
12505            "RestartPolicy::WIRE_NAMES.len() must byte-equal \
12506             RestartPolicy::ALL.len() — a mismatch means the roster \
12507             and the enum's arm-set have drifted; downstream consumers \
12508             that fan through both will silently disagree on the \
12509             accepted arm-set"
12510        );
12511        for &variant in RestartPolicy::ALL {
12512            let wire = variant.as_str();
12513            assert!(
12514                RestartPolicy::WIRE_NAMES.contains(&wire),
12515                "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
12516                 be a member of RestartPolicy::WIRE_NAMES — the \
12517                 emitter and the roster have drifted out of lockstep"
12518            );
12519        }
12520        for tag in RestartPolicy::WIRE_NAMES {
12521            let first = tag.chars().next().unwrap_or_else(|| {
12522                panic!(
12523                    "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
12524                     a non-empty PascalCase byte-string"
12525                )
12526            });
12527            assert!(
12528                first.is_ascii_uppercase(),
12529                "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
12530                 with an ASCII uppercase byte (PascalCase wire form) — \
12531                 a lowercase entry would collide the wire-form axis \
12532                 with the peer kebab-case dispatcher-catalog axis \
12533                 [`RestartPolicy::discriminant`] serves"
12534            );
12535        }
12536    }
12537
12538    #[test]
12539    fn restart_policy_from_wire_accepts_every_lifted_constant() {
12540        // Fail-before-pass-after pin on the forward accept-set of the
12541        // [`RestartPolicy::from_wire`] reverse projection: every
12542        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12543        // constant the [`RestartPolicy::as_str`] emitter walks parses
12544        // back to its paired variant. Any future arm addition that
12545        // grows the emitter's `as_str` match but forgets to grow the
12546        // parser's `from_wire` match silently splits the two halves of
12547        // the round-trip — the wire byte-string one non-serde consumer
12548        // parses from the one the emitter wrote — with the failure
12549        // surfacing at the operator's reconcile posture (a `:temporary`
12550        // `oneShot` child restarted on clean exit, a `:transient` child
12551        // restarted after clean completion) far from the rebrand
12552        // commit. Pinning the three-arm accept-set here catches the
12553        // drift at caixa-core build time.
12554        //
12555        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
12556        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
12557        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
12558        // accept-set pins on the peer closed-set typed-enum `str → Self`
12559        // axes.
12560        for (wire, expected) in [
12561            (
12562                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12563                RestartPolicy::Permanent,
12564            ),
12565            (
12566                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12567                RestartPolicy::Temporary,
12568            ),
12569            (
12570                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12571                RestartPolicy::Transient,
12572            ),
12573        ] {
12574            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12575                panic!(
12576                    "RestartPolicy::from_wire({wire:?}) must accept every \
12577                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
12578                     lifted canonical byte-string that RestartPolicy::{expected:?} \
12579                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
12580                )
12581            });
12582            assert_eq!(
12583                parsed, expected,
12584                "RestartPolicy::from_wire({wire:?}) must return \
12585                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
12586            );
12587        }
12588    }
12589
12590    #[test]
12591    fn restart_policy_from_wire_round_trips_through_as_str() {
12592        // Fail-before-pass-after pin on the closed round-trip between
12593        // the forward [`RestartPolicy::as_str`] emitter and the
12594        // reverse [`RestartPolicy::from_wire`] parser: for every
12595        // variant in [`RestartPolicy::ALL`], parsing the emitter's
12596        // output must return exactly the same variant. Any per-arm
12597        // divergence — a future arm added to `as_str` but not
12598        // `from_wire`, an accidental copy-paste flip in one but not
12599        // the other — silently splits the emit and parse halves and
12600        // the failure surfaces at consumer parse time far from the
12601        // drift site. The `ALL`-iterating shape means a future arm
12602        // addition picks up the coverage by construction.
12603        //
12604        // Peer of the sibling
12605        // [`restart_strategy_from_wire_round_trips_through_as_str`]
12606        // (4eec29c) round-trip pin on
12607        // [`RestartStrategy::from_wire`] and the M3
12608        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
12609        // (18c7342) round-trip pin on
12610        // [`crate::aplicacao::PlacementStrategy::from_wire`].
12611        for &variant in RestartPolicy::ALL {
12612            let wire = variant.as_str();
12613            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12614                panic!(
12615                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12616                     must be Some({variant:?}) — the two halves of the round-trip \
12617                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
12618                     got None on wire byte-string {wire:?}"
12619                )
12620            });
12621            assert_eq!(
12622                parsed, variant,
12623                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12624                 must round-trip to the same variant; got {parsed:?}"
12625            );
12626        }
12627    }
12628
12629    #[test]
12630    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
12631        // Fail-before-pass-after pin on the closed-set refusal
12632        // discipline of [`RestartPolicy::from_wire`]: every
12633        // byte-string outside the three-arm accept-set returns `None`
12634        // rather than silently collapsing onto the [`Default`]
12635        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
12636        // exercised here sweeps the load-bearing drift shapes: the
12637        // empty string (a stripped serde-attribute drift), all-
12638        // whitespace strings (the canonical text-editor accidental
12639        // padding shape), the kebab-case dispatcher-catalog identities
12640        // (`"permanent"` / `"temporary"` / `"transient"` — the
12641        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
12642        // accept-set, which parses the *other* axis of this enum's
12643        // two-axis split and must not leak into the `from_wire`
12644        // PascalCase-wire accept-set — a lowercase leak here would
12645        // silently accept the operator's kebab-case
12646        // dispatcher-catalog probe under the wire-axis parser and mis-
12647        // route a `:permanent` intent), the padded canonical scalar
12648        // (`" Permanent "`), the trailing-newline shapes
12649        // (`"Permanent\n"`), the uppercase-single-word forms
12650        // (`"PERMANENT"`), and neighboring-but-unknown arms
12651        // (`"Restart"` — the canonical typo direction toward the
12652        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
12653        //
12654        // Peer of the sibling
12655        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
12656        // (4eec29c) +
12657        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
12658        // (2aa6d23) +
12659        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
12660        // (18c7342) refusal pins on the peer closed-set typed-enum
12661        // axes.
12662        for bad in [
12663            "",
12664            " ",
12665            "\n",
12666            "\t",
12667            "permanent",
12668            "temporary",
12669            "transient",
12670            "PERMANENT",
12671            "TEMPORARY",
12672            "TRANSIENT",
12673            "Permanents",
12674            "Permanent ",
12675            " Permanent",
12676            " Transient ",
12677            "Permanent\n",
12678            "perma",
12679            "Trans",
12680            "OneForOne",
12681            "Restart",
12682            "?",
12683        ] {
12684            assert!(
12685                RestartPolicy::from_wire(bad).is_none(),
12686                "RestartPolicy::from_wire({bad:?}) must return None — the \
12687                 parser's accept-set is exactly the three RestartPolicy::as_str \
12688                 outputs (Permanent, Temporary, Transient), and this \
12689                 byte-string is outside that closed set"
12690            );
12691        }
12692    }
12693
12694    #[test]
12695    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
12696        // Fail-before-pass-after pin on the fourth path of the four-path
12697        // convergence: `from_wire` (the reverse projection) inverts the
12698        // `Serialize` derive's wire byte-string on every variant.
12699        // Together with the pre-existing three-path convergence
12700        // (`Display` + `as_str` + `Serialize` all resolve to the same
12701        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
12702        // pinned by
12703        // [`restart_policy_display_matches_serialized_wire_byte_string`])
12704        // this closes the round-trip: the wire byte-string the
12705        // `Serialize` derive emits parses back to the same variant
12706        // through `from_wire`, so any future serde-attribute or variant-
12707        // rename drift on the emit half now surfaces as a matched drift
12708        // on the parse half at caixa-core build time — the two halves
12709        // migrate as a unit through the lifted consts on any future
12710        // rename, and the round-trip cannot silently split.
12711        //
12712        // Peer of the sibling
12713        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12714        // (4eec29c) wire-format pin on
12715        // [`RestartStrategy::from_wire`] and the M3
12716        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12717        // (18c7342) wire-format pin on
12718        // [`crate::aplicacao::PlacementStrategy::from_wire`].
12719        for &variant in RestartPolicy::ALL {
12720            let wire = serde_json::to_string(&variant).unwrap();
12721            let unquoted = wire
12722                .strip_prefix('"')
12723                .and_then(|s| s.strip_suffix('"'))
12724                .expect("serialized RestartPolicy is a JSON string");
12725            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
12726                panic!(
12727                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
12728                     Serialize derive's wire byte-string for \
12729                     RestartPolicy::{variant:?} — the four-path convergence \
12730                     (Display + as_str + Serialize + from_wire) resolves through \
12731                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
12732                )
12733            });
12734            assert_eq!(
12735                parsed, variant,
12736                "RestartPolicy::from_wire of the Serialize derive's wire \
12737                 byte-string for RestartPolicy::{variant:?} must round-trip \
12738                 to the same variant; got {parsed:?}"
12739            );
12740        }
12741    }
12742
12743    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
12744    //
12745    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
12746    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
12747    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
12748    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
12749    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
12750    // the peer per-`:upgrade-from :from` axis. The three pins jointly
12751    // brace the accessor against every future silent detour that would
12752    // desynchronize it from the raw `.caixa` field access every consumer
12753    // previously open-coded.
12754
12755    #[test]
12756    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
12757        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
12758        // [`ChildSpec::nome`] must return the `:children :caixa` field
12759        // byte-for-byte across every DNS-1123-label value the upstream
12760        // [`crate::render::require_valid_dns_1123_label`] gate at
12761        // `SupervisorSpec::validate` admits. Peer of the sibling
12762        // `membro_nome_returns_caixa_byte_equal_across_permutations`
12763        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
12764        // substrate-primitive accessor must byte-equal the raw field
12765        // access verbatim across every author-declared value" discipline
12766        // extended to the M2 supervisor-tree per-`:children` arm. Pins
12767        // against a future silent detour that re-normalized the child
12768        // identity (an accidental `.to_lowercase()` — every `:children
12769        // :caixa` is validated as a DNS-1123 label upstream, so any
12770        // re-normalization is redundant + a drift surface between the
12771        // validator and the accessor), a namespace-prefix rewrite (an
12772        // accidental `format!("{namespace}/{caixa}")` per-CR
12773        // fully-qualified rewrite that didn't land on the peer axes), or
12774        // a per-cluster alias stamp the future wasm-operator's
12775        // hierarchical reconciliation scheduler authors on one consumer
12776        // without the others. Five values sweep the accept-set the
12777        // DNS-1123 gate upstream admits (short single-word / dashed /
12778        // v-suffixed / mixed-digit child names).
12779        for name in [
12780            "worker",
12781            "cache-server",
12782            "scratch-job",
12783            "orders-v2",
12784            "session-8080",
12785        ] {
12786            let c = ChildSpec {
12787                caixa: name.into(),
12788                versao: "^0.1".into(),
12789                restart: RestartPolicy::Permanent,
12790            };
12791            assert_eq!(
12792                c.nome(),
12793                name,
12794                "ChildSpec::nome must return :children :caixa verbatim \
12795                 (got {:?}, expected {name:?})",
12796                c.nome(),
12797            );
12798            assert_eq!(
12799                c.nome(),
12800                c.caixa.as_str(),
12801                "ChildSpec::nome must byte-equal the .caixa field access",
12802            );
12803        }
12804    }
12805
12806    #[test]
12807    fn child_spec_nome_borrows_from_caixa_storage() {
12808        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
12809        // `&str` slice that borrows from the typed slot's own [`String`]
12810        // storage — same-address invariant with `c.caixa.as_str()`. Pins
12811        // against a future silent detour that allocated a fresh `String`
12812        // (`self.caixa.clone()` in the body would type-check but silently
12813        // drop the borrow, and every downstream consumer that assumed
12814        // the returned slice outlives `&self` would break on a stale-
12815        // reference use-after-free — the [`crate::render::insert_first_seen`]
12816        // dedup key at [`SupervisorSpec::validate`], the
12817        // [`validate_no_self_supervision`] equality check against the
12818        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
12819        // borrow — each would silently misbehave if this accessor
12820        // produced a detached copy). Peer of the sibling
12821        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
12822        // M3 per-`:membros` axis and the
12823        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
12824        // first M2 slot scalar accessor.
12825        let c = ChildSpec {
12826            caixa: "worker".into(),
12827            versao: "^0.1".into(),
12828            restart: RestartPolicy::Permanent,
12829        };
12830        let name = c.nome();
12831        let caixa_slice = c.caixa.as_str();
12832        assert_eq!(
12833            name.as_ptr(),
12834            caixa_slice.as_ptr(),
12835            "ChildSpec::nome must borrow from the .caixa String's backing \
12836             storage — a fresh allocation here means the accessor no \
12837             longer names the substrate-primitive typed dispatch and \
12838             every downstream consumer would silently carry a detached \
12839             copy",
12840        );
12841        assert_eq!(
12842            name.len(),
12843            caixa_slice.len(),
12844            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
12845             as well as in address",
12846        );
12847    }
12848
12849    #[test]
12850    fn validate_gates_child_nome_through_lifted_accessor() {
12851        // Bilateral coherence pin: every `:children :caixa` that
12852        // [`SupervisorSpec::validate`] accepts is one
12853        // [`crate::render::require_valid_dns_1123_label`] accepts on the
12854        // accessor-projected value, and vice versa on the reject side.
12855        // This closes the "the validator reads through the accessor"
12856        // contract structurally — a future silent detour that made the
12857        // accessor return a different byte-string than the validator
12858        // gates against would surface here as a coverage mismatch, not
12859        // as an apply-time DNS-1123 rejection at
12860        // `metadata.name: Invalid value` far from the caixa.lisp source.
12861        // Peer of the M2 sibling
12862        // `validate_parses_prior_versao_through_lifted_accessor`
12863        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
12864        // `validate_membros` peer discipline.
12865        //
12866        // Accept-set sweep: five DNS-1123-label values the upstream gate
12867        // admits.
12868        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
12869            let s = SupervisorSpec {
12870                children: vec![ChildSpec {
12871                    caixa: ok_name.into(),
12872                    versao: "^0.1".into(),
12873                    restart: RestartPolicy::Permanent,
12874                }],
12875                ..SupervisorSpec::default()
12876            };
12877            s.validate().unwrap_or_else(|e| {
12878                panic!(
12879                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
12880                     (upstream DNS-1123 gate accepts it): got {e:?}",
12881                );
12882            });
12883            let c = ChildSpec {
12884                caixa: ok_name.into(),
12885                versao: "^0.1".into(),
12886                restart: RestartPolicy::Permanent,
12887            };
12888            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
12889                .unwrap_or_else(|()| {
12890                    panic!(
12891                        "require_valid_dns_1123_label must accept the accessor-projected \
12892                     :children :caixa {ok_name:?}",
12893                    );
12894                });
12895        }
12896        // Reject-set sweep: five DNS-1123-label-violating shapes the
12897        // upstream gate refuses (empty / uppercase / underscore / dot /
12898        // leading-hyphen). Every rejection at the validator must
12899        // correspond to a rejection when the accessor's projected value
12900        // is fed back through the shared gate.
12901        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
12902            let s = SupervisorSpec {
12903                children: vec![ChildSpec {
12904                    caixa: bad_name.into(),
12905                    versao: "^0.1".into(),
12906                    restart: RestartPolicy::Permanent,
12907                }],
12908                ..SupervisorSpec::default()
12909            };
12910            let err = s.validate().unwrap_err();
12911            assert!(
12912                matches!(
12913                    err,
12914                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
12915                ),
12916                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
12917                 via the DNS-1123 gate: got {err:?}",
12918            );
12919            let c = ChildSpec {
12920                caixa: bad_name.into(),
12921                versao: "^0.1".into(),
12922                restart: RestartPolicy::Permanent,
12923            };
12924            assert!(
12925                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
12926                    .is_err(),
12927                "require_valid_dns_1123_label must reject the accessor-projected \
12928                 :children :caixa {bad_name:?}",
12929            );
12930        }
12931    }
12932
12933    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
12934    //
12935    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
12936    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
12937    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
12938    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
12939    // trio on the peer per-`:children` `String`-carry axis. The three pins
12940    // jointly brace the accessor against every future silent detour that
12941    // would desynchronize it from the raw `.versao` field access the
12942    // requirement gate + error carrier previously open-coded.
12943    //
12944    // Closes the last unlifted per-`:children` `String`-carry axis: the
12945    // pair (`nome`, `versao_requirement`) now jointly projects the
12946    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
12947    // consumer that fans on per-child identity + version pin reads,
12948    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
12949    // pair discipline verbatim.
12950    #[test]
12951    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
12952        // The canonical per-`:children` child-`:versao`-scalar pin:
12953        // [`ChildSpec::versao_requirement`] must return the `:children
12954        // :versao` field byte-for-byte across every Cargo-shaped semver
12955        // requirement value the upstream
12956        // [`crate::render::require_valid_versao_requirement`] gate admits.
12957        // Peer of the sibling
12958        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
12959        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
12960        // substrate-primitive accessor must byte-equal the raw field
12961        // access verbatim across every author-declared value" discipline
12962        // extended to the M2 supervisor-tree per-`:children` arm. Pins
12963        // against a future silent detour that re-canonicalized the
12964        // requirement (an accidental `.to_string()` via
12965        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
12966        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
12967        // silently drifted the error carrier's quoted requirement away
12968        // from the source `caixa.lisp`, an accidental whitespace trim on
12969        // `"^ 0.1"` that no consumer ever produced from the field-access
12970        // side, an accidental per-cluster lacre-projected concrete-version
12971        // rewrite that didn't land on the peer requirement-gate call).
12972        // Five values sweep the accept-set the shared
12973        // [`crate::render::require_valid_versao_requirement`] gate admits
12974        // (caret / tilde / exact / wildcard / bare-major).
12975        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12976            let c = ChildSpec {
12977                caixa: "worker".into(),
12978                versao: req.into(),
12979                restart: RestartPolicy::Permanent,
12980            };
12981            assert_eq!(
12982                c.versao_requirement(),
12983                req,
12984                "ChildSpec::versao_requirement must return :children :versao \
12985                 verbatim (got {:?}, expected {req:?})",
12986                c.versao_requirement(),
12987            );
12988            assert_eq!(
12989                c.versao_requirement(),
12990                c.versao.as_str(),
12991                "ChildSpec::versao_requirement must byte-equal the .versao \
12992                 field access",
12993            );
12994        }
12995    }
12996
12997    #[test]
12998    fn child_spec_versao_requirement_borrows_from_versao_storage() {
12999        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
13000        // return a `&str` slice that borrows from the typed slot's own
13001        // [`String`] storage — same-address invariant with
13002        // `c.versao.as_str()`. Pins against a future silent detour that
13003        // allocated a fresh `String` (`self.versao.clone()` in the body
13004        // would type-check but silently drop the borrow, and every
13005        // downstream consumer that assumed the returned slice outlives
13006        // `&self` — the [`crate::render::require_valid_versao_requirement`]
13007        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
13008        // `.to_string()` carrier's byte-length assumption — would silently
13009        // misbehave if this accessor produced a detached copy). Peer of
13010        // the sibling `child_spec_nome_borrows_from_caixa_storage`
13011        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
13012        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
13013        // pin on the peer per-`:membros` `:versao` axis.
13014        let c = ChildSpec {
13015            caixa: "worker".into(),
13016            versao: "^0.1".into(),
13017            restart: RestartPolicy::Permanent,
13018        };
13019        let req = c.versao_requirement();
13020        let versao_slice = c.versao.as_str();
13021        assert_eq!(
13022            req.as_ptr(),
13023            versao_slice.as_ptr(),
13024            "ChildSpec::versao_requirement must borrow from the .versao \
13025             String's backing storage — a fresh allocation here means the \
13026             accessor no longer names the substrate-primitive typed \
13027             dispatch and every downstream consumer would silently carry \
13028             a detached copy",
13029        );
13030        assert_eq!(
13031            req.len(),
13032            versao_slice.len(),
13033            "ChildSpec::versao_requirement and .versao.as_str() must \
13034             byte-equal in length as well as in address",
13035        );
13036    }
13037
13038    #[test]
13039    fn validate_gates_child_versao_through_lifted_accessor() {
13040        // Bilateral coherence pin: every `:children :versao` that
13041        // [`SupervisorSpec::validate`] accepts is one
13042        // [`crate::render::require_valid_versao_requirement`] accepts on
13043        // the accessor-projected value, and vice versa on the reject side.
13044        // This closes the "the validator reads through the accessor"
13045        // contract structurally — a future silent detour that made the
13046        // accessor return a different byte-string than the validator gates
13047        // against would surface here as a coverage mismatch, not as a
13048        // resolver-time semver-parse rejection at lacre-closure time far
13049        // from the caixa.lisp source. Peer of the sibling
13050        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
13051        // the per-`:children :caixa` axis and the M2
13052        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
13053        // on the peer per-`:upgrade-from :from` axis.
13054        //
13055        // Accept-set sweep: five Cargo-shaped semver requirement values
13056        // the upstream gate admits (caret / tilde / exact / wildcard /
13057        // bare-major).
13058        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
13059            let s = SupervisorSpec {
13060                children: vec![ChildSpec {
13061                    caixa: "worker".into(),
13062                    versao: ok_req.into(),
13063                    restart: RestartPolicy::Permanent,
13064                }],
13065                ..SupervisorSpec::default()
13066            };
13067            s.validate().unwrap_or_else(|e| {
13068                panic!(
13069                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
13070                     (upstream versao-requirement gate accepts it): got {e:?}",
13071                );
13072            });
13073            let c = ChildSpec {
13074                caixa: "worker".into(),
13075                versao: ok_req.into(),
13076                restart: RestartPolicy::Permanent,
13077            };
13078            crate::render::require_valid_versao_requirement(
13079                c.versao_requirement(),
13080                || (),
13081                |_reason| (),
13082            )
13083            .unwrap_or_else(|()| {
13084                panic!(
13085                    "require_valid_versao_requirement must accept the accessor-projected \
13086                     :children :versao {ok_req:?}",
13087                );
13088            });
13089        }
13090        // Reject-set sweep: five requirement-violating shapes the upstream
13091        // gate refuses. The empty string closes the empty-first arm of the
13092        // shared [`crate::render::require_valid_versao_requirement`]
13093        // cascade; the four non-empty arms exercise distinct semver-parse
13094        // failure modes the M3 peer per-`:membros` reject-set already pins
13095        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
13096        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
13097        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
13098        // shared parser routing means the same reject-set must fail
13099        // identically at the M2 supervisor-tree per-`:children` accessor
13100        // arm here. Every rejection at the validator must correspond to a
13101        // rejection when the accessor's projected value is fed back
13102        // through the shared gate.
13103        //
13104        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
13105        // `"not-a-semver"` are intentionally *not* in the reject-set: the
13106        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
13107        // and the identifier-tail arm's grammar admits some non-canonical
13108        // shapes — matching what the M3 peer test suite already documents
13109        // as the shared parser's accept-set edges.)
13110        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
13111            let s = SupervisorSpec {
13112                children: vec![ChildSpec {
13113                    caixa: "worker".into(),
13114                    versao: bad_req.into(),
13115                    restart: RestartPolicy::Permanent,
13116                }],
13117                ..SupervisorSpec::default()
13118            };
13119            let err = s.validate().unwrap_err();
13120            assert!(
13121                matches!(
13122                    err,
13123                    SupervisorError::EmptyChildVersion { .. }
13124                        | SupervisorError::ChildVersaoInvalid { .. }
13125                ),
13126                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
13127                 via the versao-requirement gate: got {err:?}",
13128            );
13129            let c = ChildSpec {
13130                caixa: "worker".into(),
13131                versao: bad_req.into(),
13132                restart: RestartPolicy::Permanent,
13133            };
13134            assert!(
13135                crate::render::require_valid_versao_requirement(
13136                    c.versao_requirement(),
13137                    || (),
13138                    |_reason| (),
13139                )
13140                .is_err(),
13141                "require_valid_versao_requirement must reject the accessor-projected \
13142                 :children :versao {bad_req:?}",
13143            );
13144        }
13145    }
13146
13147    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
13148    //
13149    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
13150    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
13151    // already project the `String`-carry `(caixa, versao)` fields; the
13152    // `Copy`-composite-enum `restart` field is the third and final axis).
13153    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
13154    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
13155    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
13156    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
13157    // strategy scalar accessor — same "one typed dispatch on the substrate
13158    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
13159    // extended onto the M2 supervisor-slot per-`:children` restart-decision
13160    // axis. The pin below covers the accessor's byte-equal projection
13161    // against the raw field access across every variant in the closed
13162    // accept-set (`Permanent`, `Transient`, `Temporary`).
13163
13164    #[test]
13165    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
13166        // The canonical per-`:children` restart-decision-policy-scalar
13167        // pin: [`ChildSpec::restart`] must return the `:children :restart`
13168        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
13169        // typed slot's own [`RestartPolicy`] storage across every variant
13170        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
13171        // Pins against a future silent detour that re-derived the policy
13172        // from a peer axis (an accidental fallback to
13173        // `if is_supervisor_child { Permanent } else { Temporary }` that
13174        // collapsed the child's kind axis into the restart discriminator),
13175        // a variant remap the operator authors on one consumer without the
13176        // other, or a stale-derive detour that substituted
13177        // [`RestartPolicy::default`] when the field held any explicit
13178        // variant (which would silently collapse the distinction between
13179        // "author explicitly declared `:restart Permanent`" and "author
13180        // omitted the slot and inherited the default" the future
13181        // per-cluster restart-decision override slot depends on).
13182        //
13183        // Peer of the sibling per-`:supervisor`
13184        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13185        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
13186        // axis and the M3
13187        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13188        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
13189        // — same "the substrate-primitive accessor must byte-equal the raw
13190        // field access verbatim across every author-declared value"
13191        // discipline extended onto the M2 supervisor-slot per-`:children`
13192        // restart-decision-policy axis, closing the last unlifted axis on
13193        // the per-`:children` [`ChildSpec`] type.
13194        for restart in [
13195            RestartPolicy::Permanent,
13196            RestartPolicy::Transient,
13197            RestartPolicy::Temporary,
13198        ] {
13199            let c = ChildSpec {
13200                caixa: "worker".into(),
13201                versao: "^0.1".into(),
13202                restart,
13203            };
13204            assert_eq!(
13205                c.restart(),
13206                restart,
13207                "ChildSpec::restart must return :children :restart \
13208                 verbatim (got {:?}, expected {restart:?})",
13209                c.restart(),
13210            );
13211            assert_eq!(
13212                c.restart(),
13213                c.restart,
13214                "ChildSpec::restart accessor and .restart field access \
13215                 must byte-equal — the accessor is the substrate-primitive \
13216                 typed dispatch every downstream per-child restart-\
13217                 decision consumer must route through",
13218            );
13219        }
13220    }
13221
13222    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
13223    //
13224    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
13225    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
13226    // distribution-strategy accessor discipline onto the M2 supervisor-slot
13227    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
13228    // scalar axis. The two pins below cover (1) the accessor's byte-equal
13229    // projection against the raw field access across every variant in the
13230    // closed accept-set, and (2) the two-consumer coherence between the
13231    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
13232    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
13233    // carrier's `estrategia:` field — peer of the sibling M3
13234    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13235    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
13236    // pair on the per-`:placement` distribution-strategy axis.
13237
13238    #[test]
13239    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
13240        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
13241        // pin: [`SupervisorSpec::estrategia`] must return the
13242        // `:supervisor :estrategia` field verbatim as a
13243        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
13244        // [`RestartStrategy`] storage across every variant in the closed
13245        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
13246        // `SimpleOneForOne`). Pins against a future silent detour that
13247        // re-derived the strategy from a peer axis (an accidental
13248        // fallback to `if children.is_empty() { SimpleOneForOne } else {
13249        // OneForOne }` collapse that read the children-count axis into
13250        // the strategy discriminator), a variant remap the operator
13251        // authors on one consumer without the other, or a stale-derive
13252        // detour that substituted [`RestartStrategy::default`] when the
13253        // field held any explicit variant (which would silently collapse
13254        // the distinction between "author explicitly declared
13255        // `:estrategia OneForOne`" and "author omitted the slot and
13256        // inherited the default" the future per-cluster strategy override
13257        // slot depends on). Peer of the sibling M3
13258        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13259        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
13260        // axis — same "the substrate-primitive accessor must byte-equal
13261        // the raw field access verbatim across every author-declared
13262        // value" discipline extended onto the M2 supervisor-slot
13263        // per-`:supervisor` sibling-restart-strategy axis.
13264        for &estrategia in RestartStrategy::ALL {
13265            // `SimpleOneForOne` requires `children.is_empty()`; the peer
13266            // three strategies require a non-empty static children list.
13267            // Build each shape coherently so the pin's fixture would
13268            // itself pass [`SupervisorSpec::validate`] once fed through
13269            // the sibling coherence pin below — the byte-equal projection
13270            // asserted here is a strictly weaker property (a `Copy` field
13271            // read) that does not depend on `validate` running, but
13272            // keeping the fixture validate-clean means a future extension
13273            // of the pin to exercise `validate` end-to-end does not have
13274            // to re-author the children shape.
13275            //
13276            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
13277            // shape partition through the [`gen_platform::IsVariant`]
13278            // derive-generated
13279            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
13280            // than the raw `matches!(estrategia, RestartStrategy::
13281            // SimpleOneForOne)` open-coded pattern-match — same closed-
13282            // set-typed-enum arm-discriminator dispatch discipline the
13283            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
13284            // convergence (915a934) extended onto its two paired positive
13285            // / negated `matches!` sites and the peer
13286            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
13287            // predicate convergence (766ec63) extended onto the M3 mesh-
13288            // slot per-`:placement` distribution-strategy discriminator
13289            // axis. See the sibling `round_trip_all_strategies` and the
13290            // peer `manifest::tests::
13291            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
13292            // fixture for the two peer sites the same lift closes on.
13293            let children = if estrategia.is_simple_one_for_one() {
13294                Vec::new()
13295            } else {
13296                vec![ChildSpec {
13297                    caixa: "worker".into(),
13298                    versao: "^0.1".into(),
13299                    restart: RestartPolicy::Permanent,
13300                }]
13301            };
13302            let s = SupervisorSpec {
13303                estrategia,
13304                children,
13305                ..SupervisorSpec::default()
13306            };
13307            assert_eq!(
13308                s.estrategia(),
13309                estrategia,
13310                "SupervisorSpec::estrategia must return :supervisor :estrategia \
13311                 verbatim (got {:?}, expected {estrategia:?})",
13312                s.estrategia(),
13313            );
13314            assert_eq!(
13315                s.estrategia(),
13316                s.estrategia,
13317                "SupervisorSpec::estrategia accessor and .estrategia field \
13318                 access must byte-equal — the accessor is the substrate-\
13319                 primitive typed dispatch every downstream sibling-restart-\
13320                 strategy consumer must route through",
13321            );
13322        }
13323    }
13324
13325    #[test]
13326    fn validate_reads_through_lifted_estrategia_accessor() {
13327        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
13328        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
13329        // dispatch (which reads through [`SupervisorSpec::estrategia`]
13330        // to fan across the strategy-arm shape-gate cascades) and the
13331        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
13332        // error carrier's `estrategia:` field (which reads through
13333        // [`SupervisorSpec::estrategia`] to name the strategy the empty
13334        // `:children` list was declared against) must both key off the
13335        // lifted accessor, so any future rebrand on the typed slot's
13336        // reader shape lands at exactly one place. Pins the two-site
13337        // coherence by exercising the `NoChildren` error surface end-to-
13338        // end across every non-`SimpleOneForOne` variant and asserting
13339        // the surfaced `estrategia:` field byte-equals the accessor's
13340        // return. Peer of the sibling M3
13341        // `validate_placement_reads_through_lifted_estrategia_accessor`
13342        // (921fe1b) three-consumer coherence pin on the per-`:placement`
13343        // distribution-strategy axis.
13344        for estrategia in [
13345            RestartStrategy::OneForOne,
13346            RestartStrategy::OneForAll,
13347            RestartStrategy::RestForOne,
13348        ] {
13349            let s = SupervisorSpec {
13350                estrategia,
13351                children: Vec::new(),
13352                ..SupervisorSpec::default()
13353            };
13354            let err = s.validate().unwrap_err();
13355            match err {
13356                SupervisorError::NoChildren { estrategia: e } => {
13357                    assert_eq!(
13358                        e,
13359                        s.estrategia(),
13360                        "NoChildren.estrategia must byte-equal \
13361                         SupervisorSpec::estrategia() — the empty-`:children` \
13362                         refusal reads through the lifted accessor",
13363                    );
13364                    assert_eq!(
13365                        e, estrategia,
13366                        "NoChildren.estrategia must carry the author-declared \
13367                         :supervisor :estrategia variant verbatim (got {e:?}, \
13368                         expected {estrategia:?})",
13369                    );
13370                }
13371                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
13372            }
13373        }
13374    }
13375
13376    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
13377    //
13378    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
13379    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
13380    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
13381    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
13382    // The two pins below cover (1) the accessor's byte-equal projection
13383    // against the raw field access across every representative value in
13384    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
13385    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
13386    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
13387    // zero-floor / cap composition — the validate gate and the accessor
13388    // must route through the same substrate-primitive typed dispatch, so
13389    // any future silent detour that had the accessor perform a
13390    // bounds-collapsing clamp would fail here at caixa-core build time.
13391    // Peer of the sibling M3
13392    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13393    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
13394
13395    #[test]
13396    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
13397        // The canonical per-`:supervisor` restart-budget-count scalar pin:
13398        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
13399        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
13400        // typed slot's own `u32` storage, byte-equal to the raw field
13401        // access across every representative value in the accept-set —
13402        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
13403        // accept-set the surrounding [`SupervisorSpec::validate`] gate
13404        // carves out on the sibling `ZeroMaxRestarts` refusal),
13405        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
13406        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
13407        // (a past-the-guard sentinel that pins the accessor doesn't
13408        // perform a silent bounds-collapse into `1` on the zero arm —
13409        // validate rejects zero but the accessor must ship the raw slot
13410        // verbatim so a validate-time gate regression surfaces at the
13411        // emit boundary rather than being silently absorbed), `u32::MAX`
13412        // (a past-the-guard sentinel that pins the accessor doesn't
13413        // perform a silent bounds-collapse through
13414        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
13415        //
13416        // Peer of the sibling M3
13417        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13418        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
13419        // required-scalar axis — same "the substrate-primitive accessor
13420        // must byte-equal the raw field access verbatim across every
13421        // value in the `u32` accept-set" discipline extended onto the M2
13422        // supervisor-slot per-`:supervisor` restart-budget-count axis.
13423        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
13424            let s = SupervisorSpec {
13425                max_restarts,
13426                ..SupervisorSpec::default()
13427            };
13428            assert_eq!(
13429                s.max_restarts(),
13430                max_restarts,
13431                "SupervisorSpec::max_restarts must return :supervisor \
13432                 :max-restarts verbatim (got {}, expected {max_restarts})",
13433                s.max_restarts(),
13434            );
13435            assert_eq!(
13436                s.max_restarts(),
13437                s.max_restarts,
13438                "SupervisorSpec::max_restarts accessor and .max_restarts \
13439                 field access must byte-equal — the accessor is the \
13440                 substrate-primitive typed dispatch every downstream \
13441                 restart-budget-count consumer must route through",
13442            );
13443        }
13444    }
13445
13446    #[test]
13447    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
13448        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
13449        // zero-floor + upper-cap bracket must key off
13450        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
13451        // field access. Structurally: a `SupervisorSpec { max_restarts:
13452        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
13453        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
13454        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
13455        // (with the offending count carried verbatim from the accessor
13456        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
13457        // lower boundary of the accept-set) plus a `SupervisorSpec {
13458        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
13459        // boundary) must pass validate. The four together jointly pin the
13460        // accessor + validate-gate composition: any future silent detour
13461        // that had the accessor return a fresh `1` on the zero arm (a
13462        // `.max_restarts().max(1)` collapse) would silently absorb the
13463        // `ZeroMaxRestarts` refusal at the accessor boundary and the
13464        // validate gate would accept a struct-literal `SupervisorSpec {
13465        // max_restarts: 0, .. }` — the composition pin catches that at
13466        // caixa-core build time.
13467        //
13468        // Peer of the sibling M3
13469        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
13470        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
13471        // composition axis — same "the validate / shape-gate predicate
13472        // must route through the substrate-primitive typed dispatch"
13473        // discipline extended onto the peer M2 supervisor-slot
13474        // required-`u32` composition axis.
13475        let child = ChildSpec {
13476            caixa: "worker".into(),
13477            versao: "^0.1".into(),
13478            restart: RestartPolicy::Permanent,
13479        };
13480        // Zero-floor arm.
13481        let s = SupervisorSpec {
13482            max_restarts: 0,
13483            children: vec![child.clone()],
13484            ..SupervisorSpec::default()
13485        };
13486        assert_eq!(
13487            s.validate().unwrap_err(),
13488            SupervisorError::ZeroMaxRestarts,
13489            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
13490             — the accessor and the validate gate must route through the \
13491             same substrate-primitive typed dispatch on the zero-floor arm",
13492        );
13493        // Cap arm — the surfaced `max_restarts:` field must byte-equal
13494        // the accessor's return so a future rebrand on the accessor
13495        // lands in the diagnostic without a coordinated rewrite.
13496        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13497        let s = SupervisorSpec {
13498            max_restarts: over_cap,
13499            children: vec![child.clone()],
13500            ..SupervisorSpec::default()
13501        };
13502        match s.validate().unwrap_err() {
13503            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
13504                assert_eq!(
13505                    max_restarts,
13506                    s.max_restarts(),
13507                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
13508                     SupervisorSpec::max_restarts() — the cap-arm refusal \
13509                     reads through the lifted accessor",
13510                );
13511                assert_eq!(
13512                    max_restarts, over_cap,
13513                    "MaxRestartsExceedsCap.max_restarts must carry the \
13514                     author-declared :supervisor :max-restarts value \
13515                     verbatim (got {max_restarts}, expected {over_cap})",
13516                );
13517            }
13518            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
13519        }
13520        // Lower + upper accept-set boundaries.
13521        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
13522            let s = SupervisorSpec {
13523                max_restarts,
13524                children: vec![child.clone()],
13525                ..SupervisorSpec::default()
13526            };
13527            assert!(
13528                s.validate().is_ok(),
13529                "validate must accept max_restarts == {max_restarts} \
13530                 (an accept-set boundary of \
13531                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
13532            );
13533        }
13534    }
13535
13536    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
13537    //
13538    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
13539    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
13540    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
13541    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
13542    // supervisor-slot per-`:supervisor` restart-intensity-denominator
13543    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
13544    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
13545    // per-`:supervisor` scalar-value axis. The three pins below cover
13546    // (1) the accessor's byte-equal projection against the raw field
13547    // access across every representative value in the `Option<Duration>`
13548    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
13549    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
13550    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
13551    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
13552    // `if let Some(w) = self.restart_window() { … }` bracket-arm
13553    // composition — the validate gate and the accessor must route through
13554    // the same substrate-primitive typed dispatch, so any future silent
13555    // detour that had the accessor perform a bounds-collapsing clamp
13556    // would fail here at caixa-core build time, and (3) the accessor's
13557    // by-copy idempotence pin — the returned `Option<Duration>` must
13558    // outlive `&self` and two successive calls must return byte-equal
13559    // values. Peer of the sibling M2
13560    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13561    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
13562    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13563    // (7073d0f) pin on the per-`:politicas :timeout` axis.
13564
13565    #[test]
13566    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
13567        // The canonical per-`:supervisor` restart-intensity-denominator
13568        // scalar pin: [`SupervisorSpec::restart_window`] must return the
13569        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
13570        // `Option<Duration>`, `Copy`-projected from the typed slot's own
13571        // `Option<Duration>` storage, byte-equal to the raw field access
13572        // across every representative value in the accept-set — `None`
13573        // (the "never reset — every restart across the supervisor's
13574        // lifetime counts against the sibling `:max-restarts` budget"
13575        // sentinel the field's own docstring names and the peer
13576        // `validate_accepts_none_restart_window` pin locks in on the
13577        // [`SupervisorSpec::validate`] entry-side),
13578        // `Some(Duration::from_millis(1))` (the structural minimum a
13579        // validated `:restart-window` may carry, the integer-millisecond
13580        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
13581        // everything sub-ms; `Duration::ZERO` is separately rejected by
13582        // [`SupervisorError::RestartWindowZero`]),
13583        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
13584        // surrounding [`SupervisorSpec::validate`] gate carves out on the
13585        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
13586        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
13587        // accessor doesn't perform a silent bounds-collapse into `None` on
13588        // the zero-Duration arm — validate rejects zero but the accessor
13589        // must ship the raw slot verbatim so a validate-time gate
13590        // regression surfaces at the emit boundary rather than being
13591        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
13592        // sentinel that pins the accessor doesn't perform a silent
13593        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
13594        // return path).
13595        //
13596        // Peer of the sibling M2
13597        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13598        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
13599        // sibling M3
13600        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13601        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
13602        // substrate-primitive accessor must byte-equal the raw field
13603        // access verbatim across every value in the `Option<Duration>`
13604        // accept-set" discipline extended onto the M2 supervisor-slot
13605        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
13606        // silent detour that re-derived the restart-window from a peer
13607        // axis (an accidental `.max_restarts.into()` collapse that read
13608        // the restart-budget-count as a duration — the two axes serve
13609        // different halves of the `MaxIntensity / Period` restart-
13610        // intensity ratio, and confusing them silently inverts the
13611        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
13612        // "zero means never reset" collapse (the canonical
13613        // `Option<Duration>` → `Duration` collapse footgun the
13614        // [`SupervisorError::RestartWindowZero`] validate arm guards on
13615        // the peer zero-floor axis; a zero period either trips on the
13616        // first failure or never trips depending on operator
13617        // interpretation, neither of which is the author's "never reset"
13618        // intent that `None` expresses structurally), or a per-arm
13619        // variant swap that landed on one consumer without the other.
13620        for restart_window in [
13621            None,
13622            Some(Duration::from_millis(1)),
13623            Some(SUPERVISOR_RESTART_WINDOW_MAX),
13624            Some(Duration::ZERO),
13625            Some(Duration::MAX),
13626        ] {
13627            let s = SupervisorSpec {
13628                restart_window,
13629                ..SupervisorSpec::default()
13630            };
13631            assert_eq!(
13632                s.restart_window(),
13633                restart_window,
13634                "SupervisorSpec::restart_window must return :supervisor \
13635                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
13636                s.restart_window(),
13637            );
13638            assert_eq!(
13639                s.restart_window(),
13640                s.restart_window,
13641                "SupervisorSpec::restart_window accessor and \
13642                 .restart_window field access must byte-equal — the \
13643                 accessor is the substrate-primitive typed dispatch every \
13644                 downstream restart-intensity-denominator consumer must \
13645                 route through",
13646            );
13647        }
13648    }
13649
13650    #[test]
13651    fn validate_restart_window_bracket_arm_routes_through_accessor() {
13652        // Composition pin: [`SupervisorSpec::validate`]'s
13653        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
13654        // zero-floor + integer-millisecond canonical-form + upper-cap
13655        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
13656        // the raw `.restart_window` field access. Structurally: a
13657        // `SupervisorSpec { restart_window: None, .. }` must pass the
13658        // arm gate structurally (the `if let Some(_)` shape returns
13659        // early on the `None` arm — the accessor and the validate gate
13660        // must agree on `None → skip the bracket cascade` so an authored
13661        // `:restart-window ()` structurally routes through the "never
13662        // reset" sentinel path), a `SupervisorSpec { restart_window:
13663        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
13664        // refusal exactly, a `SupervisorSpec { restart_window:
13665        // Some(Duration::from_micros(1500)), .. }` must surface the
13666        // `RestartWindowNotCanonical` refusal exactly (with the offending
13667        // duration carried verbatim from the accessor return), a
13668        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
13669        // + Duration::from_millis(1)), .. }` must surface the
13670        // `RestartWindowExceedsCap` refusal exactly (with the offending
13671        // duration carried verbatim from the accessor return), and a
13672        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
13673        // .. }` (the lower boundary of the accept-set) plus a
13674        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
13675        // .. }` (the upper boundary) must pass validate. The six together
13676        // jointly pin the accessor + validate-gate composition: any future
13677        // silent detour that had the accessor return a fresh `None` on any
13678        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
13679        // collapse) would silently absorb the `RestartWindowZero` refusal
13680        // at the accessor boundary and the validate gate would accept a
13681        // struct-literal `SupervisorSpec { restart_window:
13682        // Some(Duration::ZERO), .. }` — the composition pin catches that
13683        // at caixa-core build time.
13684        //
13685        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
13686        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
13687        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
13688        // accessor-composition pin on the per-`:politicas :timeout` axis —
13689        // same "the validate / shape-gate predicate must route through
13690        // the substrate-primitive typed dispatch" discipline extended
13691        // onto the peer M2 supervisor-slot optional-`Duration` axis.
13692        let child = ChildSpec {
13693            caixa: "worker".into(),
13694            versao: "^0.1".into(),
13695            restart: RestartPolicy::Permanent,
13696        };
13697        // None arm — must not surface any :restart-window-shaped refusal;
13698        // the `if let Some(_)` bracket returns early on `None` structurally.
13699        let s = SupervisorSpec {
13700            restart_window: None,
13701            children: vec![child.clone()],
13702            ..SupervisorSpec::default()
13703        };
13704        assert!(
13705            s.validate().is_ok(),
13706            "validate must accept restart_window: None (the never-reset \
13707             sentinel) — the `if let Some(_)` bracket returns early on \
13708             the None arm and the accessor must agree",
13709        );
13710        // Zero-floor arm.
13711        let s = SupervisorSpec {
13712            restart_window: Some(Duration::ZERO),
13713            children: vec![child.clone()],
13714            ..SupervisorSpec::default()
13715        };
13716        assert_eq!(
13717            s.validate().unwrap_err(),
13718            SupervisorError::RestartWindowZero,
13719            "validate must reject restart_window == Some(Duration::ZERO) \
13720             with RestartWindowZero — the accessor and the validate gate \
13721             must route through the same substrate-primitive typed \
13722             dispatch on the zero-floor arm",
13723        );
13724        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
13725        // byte-equal the accessor's return so a future rebrand on the
13726        // accessor lands in the diagnostic without a coordinated rewrite.
13727        let sub_ms = Duration::from_micros(1500);
13728        let s = SupervisorSpec {
13729            restart_window: Some(sub_ms),
13730            children: vec![child.clone()],
13731            ..SupervisorSpec::default()
13732        };
13733        match s.validate().unwrap_err() {
13734            SupervisorError::RestartWindowNotCanonical { window } => {
13735                assert_eq!(
13736                    Some(window),
13737                    s.restart_window(),
13738                    "RestartWindowNotCanonical.window must byte-equal \
13739                     SupervisorSpec::restart_window().unwrap() — the \
13740                     non-canonical-arm refusal reads through the lifted \
13741                     accessor",
13742                );
13743                assert_eq!(
13744                    window, sub_ms,
13745                    "RestartWindowNotCanonical.window must carry the \
13746                     author-declared :supervisor :restart-window value \
13747                     verbatim (got {window:?}, expected {sub_ms:?})",
13748                );
13749            }
13750            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
13751        }
13752        // Cap arm — the surfaced `window:` field must byte-equal the
13753        // accessor's return.
13754        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13755        let s = SupervisorSpec {
13756            restart_window: Some(over_cap),
13757            children: vec![child.clone()],
13758            ..SupervisorSpec::default()
13759        };
13760        match s.validate().unwrap_err() {
13761            SupervisorError::RestartWindowExceedsCap { window } => {
13762                assert_eq!(
13763                    Some(window),
13764                    s.restart_window(),
13765                    "RestartWindowExceedsCap.window must byte-equal \
13766                     SupervisorSpec::restart_window().unwrap() — the \
13767                     cap-arm refusal reads through the lifted accessor",
13768                );
13769                assert_eq!(
13770                    window, over_cap,
13771                    "RestartWindowExceedsCap.window must carry the \
13772                     author-declared :supervisor :restart-window value \
13773                     verbatim (got {window:?}, expected {over_cap:?})",
13774                );
13775            }
13776            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
13777        }
13778        // Lower + upper accept-set boundaries.
13779        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
13780            let s = SupervisorSpec {
13781                restart_window: Some(restart_window),
13782                children: vec![child.clone()],
13783                ..SupervisorSpec::default()
13784            };
13785            assert!(
13786                s.validate().is_ok(),
13787                "validate must accept restart_window == Some({restart_window:?}) \
13788                 (an accept-set boundary of \
13789                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
13790            );
13791        }
13792    }
13793
13794    #[test]
13795    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
13796        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
13797        // `Option<Duration>` by copy — `Duration` is `Copy` (so
13798        // `Option<Duration>` is `Copy`) and the accessor must return by
13799        // value, not by reference. Peer of the sibling M2
13800        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
13801        // per-`:limits :wall-clock` axis and the sibling M3
13802        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
13803        // per-`:politicas :timeout` axis, extended onto the peer M2
13804        // supervisor-slot `Option<Duration>` copy-invariant shape — the
13805        // accessor's returned `Option<Duration>` must outlive `&self`
13806        // (multiple calls must return equal values from a dropped-`&self`
13807        // copy, since the returned Option carries no borrow), and calling
13808        // the accessor twice on the same SupervisorSpec must yield the
13809        // same `Option<Duration>` verbatim (idempotent, no side effects
13810        // on `&self`).
13811        //
13812        // Pins against a future silent detour that returned
13813        // `Option<&Duration>` (which would type-check but silently break
13814        // every downstream caller — the future wasm-operator's
13815        // per-supervisor restart-intensity counter consumes `Duration` by
13816        // value and `&Duration` would fold to a detached copy at the call
13817        // site), an accidental `Option::as_ref()` projection
13818        // (`self.restart_window.as_ref()` would also type-check but
13819        // return `Option<&Duration>`), or a one-arm-only accessor that
13820        // reads `Some(*w)` in the Some arm but reads a fresh
13821        // `Default::default()` (which would collapse to `Duration::ZERO`,
13822        // not `None`) in the None arm — a footgun the
13823        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
13824        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
13825        // requires `Period > 0` and `None` structurally expresses "never
13826        // reset" instead.
13827        for restart_window in [
13828            None,
13829            Some(Duration::from_millis(1)),
13830            Some(Duration::from_secs(60)),
13831            Some(SUPERVISOR_RESTART_WINDOW_MAX),
13832        ] {
13833            let s = SupervisorSpec {
13834                restart_window,
13835                ..SupervisorSpec::default()
13836            };
13837            let first = s.restart_window();
13838            let second = s.restart_window();
13839            assert_eq!(
13840                first, second,
13841                "SupervisorSpec::restart_window must be idempotent — two \
13842                 successive calls on the same &self must return the \
13843                 same Option<Duration>",
13844            );
13845            assert_eq!(
13846                first, restart_window,
13847                "SupervisorSpec::restart_window must return :supervisor \
13848                 :restart-window verbatim by copy — got {first:?}, \
13849                 expected {restart_window:?}",
13850            );
13851        }
13852    }
13853
13854    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
13855    //
13856    // The [`SupervisorSpec::children`] accessor lift is the seed of the
13857    // slice-return (`&[T]`) accessor discipline on the substrate — the four
13858    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
13859    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
13860    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
13861    // access at the time of this seed, and inherit this pin family's
13862    // discipline as future compounding runs migrate their consumers. The
13863    // three pins below cover (1) the accessor's byte-equal projection
13864    // against the raw field access across the empty / singleton / cohort
13865    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
13866    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
13867    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
13868    // consumer routing through the accessor on both arms, and (3) the
13869    // per-child validate loop's traversal reading the same slice-view the
13870    // accessor projects. Peer of the sibling M2
13871    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13872    // two-consumer coherence pin on the per-`:supervisor`
13873    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
13874    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
13875
13876    #[test]
13877    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
13878        // The canonical per-`:supervisor` static-child-list scalar-shape
13879        // pin: [`SupervisorSpec::children`] must return the `:supervisor
13880        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
13881        // slice-view over the same backing buffer the raw
13882        // `self.children.as_slice()` field access borrows from, byte-
13883        // equal across every representative fixture in the accept-set —
13884        // the empty slice (the `SimpleOneForOne`-arm sentinel),
13885        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
13886        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
13887        // with the peer three restart-policy variants in play).
13888        //
13889        // Pins against a future silent detour that returned
13890        // `&Vec<ChildSpec>` (which would type-check but leak the
13891        // storage-side `Vec`'s grow/push/reserve surface no consumer of
13892        // the typed view reaches for), a fresh-allocated
13893        // `Vec<ChildSpec>` copy (which would type-check via a coercion
13894        // but silently break every downstream caller that relied on the
13895        // slice sharing the backing buffer's identity), or an
13896        // out-of-order or length-drifted projection (which would silently
13897        // split the per-child validate loop's traversal input from the
13898        // paired partition-dispatch `.is_empty()` probe's input).
13899        //
13900        // Peer of the sibling
13901        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13902        // (eafb619) `Copy`-composite-enum byte-equal pin on the
13903        // per-`:supervisor` sibling-restart-strategy axis, extended onto
13904        // the per-`:supervisor` static-child-list `Vec`-carry axis.
13905        let fixtures: Vec<Vec<ChildSpec>> = vec![
13906            Vec::new(),
13907            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13908            vec![
13909                child("worker", "^0.1", RestartPolicy::Permanent),
13910                child("cache-server", "^0.1", RestartPolicy::Transient),
13911            ],
13912            vec![
13913                child("worker", "^0.1", RestartPolicy::Permanent),
13914                child("cache-server", "^0.1", RestartPolicy::Transient),
13915                child("scratch-job", "^0.1", RestartPolicy::Temporary),
13916            ],
13917        ];
13918        for children in fixtures {
13919            let s = SupervisorSpec {
13920                children: children.clone(),
13921                ..SupervisorSpec::default()
13922            };
13923            assert_eq!(
13924                s.children(),
13925                children.as_slice(),
13926                "SupervisorSpec::children must return :supervisor \
13927                 :children verbatim (got {:?}, expected {:?})",
13928                s.children(),
13929                children.as_slice(),
13930            );
13931            assert_eq!(
13932                s.children(),
13933                s.children.as_slice(),
13934                "SupervisorSpec::children accessor and \
13935                 .children.as_slice() field access must byte-equal — \
13936                 the accessor is the substrate-primitive typed \
13937                 dispatch every downstream static-child-list consumer \
13938                 must route through",
13939            );
13940            assert_eq!(
13941                s.children().len(),
13942                s.children.len(),
13943                "SupervisorSpec::children().len() must byte-equal \
13944                 self.children.len() — a length-drift would silently \
13945                 split the paired partition-dispatch `.is_empty()` \
13946                 probe input from the per-child validate loop's \
13947                 traversal input",
13948            );
13949        }
13950    }
13951
13952    #[test]
13953    fn validate_reads_through_lifted_children_accessor() {
13954        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
13955        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
13956        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
13957        // when the accessor projects a non-empty slice under a
13958        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
13959        // `self.children().is_empty()` refusal probe (which must trip
13960        // [`SupervisorError::NoChildren`] when the accessor projects the
13961        // empty slice under any peer estrategia), and the per-child
13962        // validate loop's `for child in self.children()` traversal
13963        // (which must reach every entry in the same order the accessor
13964        // projects) must all key off the lifted accessor, so any future
13965        // rebrand on the typed slot's reader shape lands at exactly one
13966        // place. Pins the three-site coherence by exercising each
13967        // production consumer end-to-end: (1) the
13968        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
13969        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
13970        // refusal under the empty slice + non-`SimpleOneForOne`
13971        // estrategia across every peer variant, and (3) the per-child
13972        // duplicate-detection surface fires on the second entry of a
13973        // two-child cohort that shares a `:caixa` name (which requires
13974        // the loop to reach both entries — a first-entry-only projection
13975        // would silently pass since the dedup HashSet has room for the
13976        // first insert).
13977        //
13978        // Peer of the sibling M2
13979        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13980        // two-consumer coherence pin on the per-`:supervisor`
13981        // sibling-restart-strategy axis, extended onto the
13982        // per-`:supervisor` static-child-list `Vec`-carry axis.
13983
13984        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
13985        // `SimpleOneForOne` estrategia must trip
13986        // `SimpleOneForOneWithStaticChildren`.
13987        let s = SupervisorSpec {
13988            estrategia: RestartStrategy::SimpleOneForOne,
13989            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13990            ..SupervisorSpec::default()
13991        };
13992        assert_eq!(
13993            s.validate().unwrap_err(),
13994            SupervisorError::SimpleOneForOneWithStaticChildren,
13995            "SimpleOneForOne + non-empty children must trip \
13996             SimpleOneForOneWithStaticChildren — the accessor projects \
13997             a non-empty slice, and the SimpleOneForOne-arm refusal \
13998             probe reads through the lifted accessor",
13999        );
14000        assert!(
14001            !s.children().is_empty(),
14002            "the SimpleOneForOne-arm refusal input must be a non-empty \
14003             slice per the accessor's projection",
14004        );
14005
14006        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
14007        // under any peer estrategia must trip `NoChildren`.
14008        for estrategia in [
14009            RestartStrategy::OneForOne,
14010            RestartStrategy::OneForAll,
14011            RestartStrategy::RestForOne,
14012        ] {
14013            let s = SupervisorSpec {
14014                estrategia,
14015                children: Vec::new(),
14016                ..SupervisorSpec::default()
14017            };
14018            match s.validate().unwrap_err() {
14019                SupervisorError::NoChildren { estrategia: e } => {
14020                    assert_eq!(
14021                        e, estrategia,
14022                        "NoChildren.estrategia must carry the author-\
14023                         declared :supervisor :estrategia variant \
14024                         verbatim (got {e:?}, expected {estrategia:?})",
14025                    );
14026                }
14027                other => panic!(
14028                    "expected NoChildren, got {other:?} for \
14029                     estrategia={estrategia:?}"
14030                ),
14031            }
14032            assert!(
14033                s.children().is_empty(),
14034                "the non-SimpleOneForOne-arm refusal input must be the \
14035                 empty slice per the accessor's projection",
14036            );
14037        }
14038
14039        // (3) Per-child validate loop: a two-child cohort that shares a
14040        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
14041        // reach both entries through the accessor.
14042        let s = SupervisorSpec {
14043            estrategia: RestartStrategy::OneForOne,
14044            children: vec![
14045                child("worker", "^0.1", RestartPolicy::Permanent),
14046                child("worker", "^0.2", RestartPolicy::Transient),
14047            ],
14048            ..SupervisorSpec::default()
14049        };
14050        match s.validate().unwrap_err() {
14051            SupervisorError::DuplicateChildCaixa { caixa } => {
14052                assert_eq!(
14053                    caixa, "worker",
14054                    "DuplicateChildCaixa.caixa must carry the shared \
14055                     child `:caixa` name verbatim",
14056                );
14057            }
14058            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
14059        }
14060        assert_eq!(
14061            s.children().len(),
14062            2,
14063            "the per-child validate loop's traversal input must be a \
14064             two-element slice per the accessor's projection",
14065        );
14066    }
14067
14068    // Shared helper for the M2 per-`:children` per-slot-gate ≡
14069    // `validate` equivalence pins: builds an `OneForOne`-estrategia
14070    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
14071    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
14072    // bracket all pass cleanly so the sole failing surface is the
14073    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
14074    // pins the two-altitude equivalence on the paired probe.
14075    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
14076        let s = SupervisorSpec {
14077            estrategia: RestartStrategy::OneForOne,
14078            children,
14079            ..SupervisorSpec::default()
14080        };
14081        let via_gate = s.validate_children().unwrap_err();
14082        let via_validate = s.validate().unwrap_err();
14083        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
14084        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
14085        assert_eq!(
14086            via_gate, via_validate,
14087            "per-slot gate ≡ validate() must discriminate the same \
14088             refusal shape",
14089        );
14090    }
14091
14092    #[test]
14093    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
14094        // Fail-before-pass-after equivalence pin on the M2
14095        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
14096        // convergence — sibling of the M3 mesh-slot
14097        // `validate_membros_*` / `validate_contratos_*` /
14098        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
14099        // peer per-entry axes. Sweeps four of the five refusal shapes
14100        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
14101        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
14102        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
14103        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
14104        // duplicate-`:caixa` fan-out. Companion pin
14105        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
14106        // covers `ChildVersaoInvalid` (whose parser-owned reason string
14107        // needs pattern-matching, not equality) and the clean-pass
14108        // canonical fixture; together the two pins guarantee the
14109        // per-slot gate and `validate` discriminate the same set on
14110        // every per-child-covered input.
14111        assert_validate_children_matches_gate(
14112            vec![child("", "^0.1", RestartPolicy::Permanent)],
14113            &SupervisorError::EmptyChildName,
14114        );
14115        assert_validate_children_matches_gate(
14116            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
14117            &SupervisorError::ChildCaixaInvalid {
14118                caixa: "Worker".into(),
14119                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
14120            },
14121        );
14122        assert_validate_children_matches_gate(
14123            vec![child("worker", "", RestartPolicy::Permanent)],
14124            &SupervisorError::EmptyChildVersion {
14125                caixa: "worker".into(),
14126            },
14127        );
14128        assert_validate_children_matches_gate(
14129            vec![
14130                child("worker", "^0.1", RestartPolicy::Permanent),
14131                child("worker", "^0.2", RestartPolicy::Transient),
14132            ],
14133            &SupervisorError::DuplicateChildCaixa {
14134                caixa: "worker".into(),
14135            },
14136        );
14137    }
14138
14139    #[test]
14140    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
14141        // Second half of the two-altitude equivalence pin — covers the
14142        // one refusal shape whose reason string is parser-owned
14143        // (`ChildVersaoInvalid`, whose reason comes from the shared
14144        // [`crate::version::parse_requirement`] impl and may drift) and
14145        // the clean-pass canonical fixture. Sibling pin
14146        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
14147        // covers the four equality-comparable refusal shapes.
14148        let s_bad_versao = SupervisorSpec {
14149            estrategia: RestartStrategy::OneForOne,
14150            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
14151            ..SupervisorSpec::default()
14152        };
14153        let via_gate = s_bad_versao.validate_children().unwrap_err();
14154        let via_validate = s_bad_versao.validate().unwrap_err();
14155        match (&via_gate, &via_validate) {
14156            (
14157                SupervisorError::ChildVersaoInvalid {
14158                    caixa: cg,
14159                    versao: vg,
14160                    ..
14161                },
14162                SupervisorError::ChildVersaoInvalid {
14163                    caixa: cv,
14164                    versao: vv,
14165                    ..
14166                },
14167            ) => {
14168                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
14169                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
14170                assert_eq!(cv, "worker", "validate() :caixa carrier");
14171                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
14172            }
14173            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
14174        }
14175        assert_eq!(
14176            via_gate, via_validate,
14177            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
14178        );
14179
14180        let s_ok = SupervisorSpec {
14181            estrategia: RestartStrategy::OneForOne,
14182            children: vec![
14183                child("worker-a", "^0.1", RestartPolicy::Permanent),
14184                child("worker-b", "~0.2.3", RestartPolicy::Transient),
14185                child("collector", "*", RestartPolicy::Temporary),
14186            ],
14187            ..SupervisorSpec::default()
14188        };
14189        s_ok.validate_children()
14190            .expect("per-slot gate must accept the clean-pass fixture");
14191        s_ok.validate()
14192            .expect("validate() must accept the clean-pass fixture");
14193    }
14194
14195    #[test]
14196    fn validate_children_is_self_contained_on_children_slot() {
14197        // Self-containment pin: [`SupervisorSpec::validate_children`]
14198        // resolves the per-child cascade against `&self` alone, without
14199        // depending on the peer `:estrategia`/`:max-restarts`/
14200        // `:restart-window` gates having run first — same posture the M3
14201        // peer per-slot gates carry (`validate_membros`,
14202        // `validate_contratos`, `validate_entrada`, `validate_placement`,
14203        // routing through their own oracles rather than borrowing state
14204        // threaded down from `validate`). A future consumer that reaches
14205        // the per-slot gate directly on a spec whose peer slots would
14206        // fail `validate` still surfaces the per-child refusal, not the
14207        // peer refusal.
14208        //
14209        // Construct a spec whose `:max-restarts` is `0` (which would
14210        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
14211        // the partition-dispatch) and whose `:children` carries a
14212        // `DuplicateChildCaixa` shape: the per-slot gate called directly
14213        // must surface `DuplicateChildCaixa`, proving it does not depend
14214        // on the peer `:max-restarts` gate running first.
14215        let s = SupervisorSpec {
14216            estrategia: RestartStrategy::OneForOne,
14217            max_restarts: 0,
14218            restart_window: Some(Duration::from_secs(60)),
14219            children: vec![
14220                child("worker", "^0.1", RestartPolicy::Permanent),
14221                child("worker", "^0.2", RestartPolicy::Transient),
14222            ],
14223        };
14224        assert_eq!(
14225            s.validate_children().unwrap_err(),
14226            SupervisorError::DuplicateChildCaixa {
14227                caixa: "worker".into(),
14228            },
14229            "per-slot gate must resolve per-child refusal directly against \
14230             `&self` — a dependency on the peer `:max-restarts` gate \
14231             running first would surface ZeroMaxRestarts here instead",
14232        );
14233        // The peer gate is still the surface `validate` reaches — pin
14234        // the ordering to establish that `validate_children` truly runs
14235        // last in `validate`'s dispatch, so a direct call bypasses the
14236        // peer gates on any spec whose per-child cascade would fail.
14237        assert_eq!(
14238            s.validate().unwrap_err(),
14239            SupervisorError::ZeroMaxRestarts,
14240            "validate() must surface the peer `:max-restarts` gate before \
14241             reaching the per-child cascade — this pins the dispatch \
14242             ordering the per-slot gate's self-containment complements",
14243        );
14244    }
14245
14246    #[test]
14247    fn child_spec_restart_accessor_is_const_fn() {
14248        // The [`ChildSpec::restart`] per-`:children` restart-decision-
14249        // policy `Copy`-return scalar accessor is declared
14250        // `#[must_use] pub const fn` — matching the sibling M2
14251        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
14252        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
14253        // both converted in this commit), the sibling M2
14254        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
14255        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
14256        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
14257        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
14258        // `Copy`-return `pub const fn` scalar accessors on the sibling
14259        // M3 surface. Pin the `const`-eval posture here so a future
14260        // accidental downgrade to non-`const` (an added runtime helper
14261        // reachable only from a non-`const` context, an
14262        // `Option<RestartPolicy>`-shape migration on the per-child
14263        // restart-decision axis once heterogeneous per-cluster
14264        // restart-policy overlays land that would silently drop the
14265        // `const` qualifier, a manual hand-rolled shadow) trips at
14266        // caixa-core build time rather than surfacing as a downstream
14267        // `const`-context regression far from the declaration.
14268        //
14269        // Same shape as the sibling M3
14270        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
14271        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
14272        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
14273        // accessor axis — the load-bearing witness lives in the
14274        // module-scope `const fn` wrapper `restart_via_const_fn` below:
14275        // a body that calls [`ChildSpec::restart`] under a `const fn`
14276        // signature is well-formed only when the callee is itself
14277        // `const fn`, so any future accidental downgrade of
14278        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
14279        // build time (const-eval E0015 `cannot call non-const method`),
14280        // strictly stronger than a runtime `assert!(CONST)` and
14281        // side-stepping the destructor-in-const restriction that
14282        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
14283        // items on `ChildSpec`'s `String` carriers.
14284        //
14285        // The runtime body sweeps every closed-set [`RestartPolicy`]
14286        // arm and asserts the wrapped and direct dispatches agree.
14287        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
14288            c.restart()
14289        }
14290        for restart in [
14291            RestartPolicy::Permanent,
14292            RestartPolicy::Transient,
14293            RestartPolicy::Temporary,
14294        ] {
14295            let c = ChildSpec {
14296                caixa: "worker".into(),
14297                versao: "^0.1".into(),
14298                restart,
14299            };
14300            assert_eq!(
14301                restart_via_const_fn(&c),
14302                c.restart(),
14303                "const-fn-wrapped and direct dispatch on \
14304                 ChildSpec::restart must agree for {restart:?}",
14305            );
14306            assert_eq!(
14307                c.restart(),
14308                restart,
14309                "ChildSpec::restart must return the storage-side \
14310                 RestartPolicy verbatim for {restart:?} (a violation \
14311                 means the accessor stopped being a raw field-return \
14312                 copy)",
14313            );
14314        }
14315    }
14316
14317    #[test]
14318    fn supervisor_spec_estrategia_accessor_is_const_fn() {
14319        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
14320        // sibling-restart-strategy `Copy`-return scalar accessor is
14321        // declared `#[must_use] pub const fn` — matching the sibling M2
14322        // per-`:children` [`ChildSpec::restart`] (pinned by
14323        // [`child_spec_restart_accessor_is_const_fn`] above, both
14324        // converted in this commit), the sibling M2 per-`:supervisor`
14325        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
14326        // accessor already `pub const fn`, and mirroring the peer M3
14327        // mesh-slot per-`:placement`
14328        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
14329        // `pub const fn` scalar accessor whose method-name discipline
14330        // the [`SupervisorSpec::estrategia`] method was authored to
14331        // match. Pin the `const`-eval posture here so a future
14332        // accidental downgrade to non-`const` (an added runtime helper
14333        // reachable only from a non-`const` context, an
14334        // `Option<RestartStrategy>`-shape migration once the substrate
14335        // grows per-cluster strategy overlays that would silently drop
14336        // the `const` qualifier, a manual hand-rolled shadow) trips at
14337        // caixa-core build time rather than surfacing as a downstream
14338        // `const`-context regression far from the declaration.
14339        //
14340        // Same shape as the sibling
14341        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
14342        // load-bearing witness lives in the module-scope `const fn`
14343        // wrapper `estrategia_via_const_fn` below: a body that calls
14344        // [`SupervisorSpec::estrategia`] under a `const fn` signature
14345        // is well-formed only when the callee is itself `const fn`,
14346        // side-stepping the destructor-in-const restriction that would
14347        // otherwise block a direct
14348        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
14349        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
14350        // carriers.
14351        //
14352        // The runtime body sweeps every closed-set [`RestartStrategy`]
14353        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
14354        // direct dispatches agree.
14355        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
14356            s.estrategia()
14357        }
14358        for &estrategia in RestartStrategy::ALL {
14359            let s = SupervisorSpec {
14360                estrategia,
14361                max_restarts: 5,
14362                restart_window: Some(Duration::from_secs(60)),
14363                children: Vec::new(),
14364            };
14365            assert_eq!(
14366                estrategia_via_const_fn(&s),
14367                s.estrategia(),
14368                "const-fn-wrapped and direct dispatch on \
14369                 SupervisorSpec::estrategia must agree for {estrategia:?}",
14370            );
14371            assert_eq!(
14372                s.estrategia(),
14373                estrategia,
14374                "SupervisorSpec::estrategia must return the storage-side \
14375                 RestartStrategy verbatim for {estrategia:?} (a violation \
14376                 means the accessor stopped being a raw field-return \
14377                 copy)",
14378            );
14379        }
14380    }
14381
14382    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
14383    // macro definition (see the paired doc-block above the macro
14384    // definition) — every generated `<ctor>(caixa: &str) -> Self`
14385    // constructor folds the uniform `Self::<Variant> { caixa:
14386    // caixa.to_string() }` one-field struct-literal onto one substrate
14387    // primitive. The three per-variant equivalence pins below
14388    // (fail-before-pass-after by construction — a byte-mismatched macro
14389    // arm would trip its equivalence pin first) lock each generated
14390    // constructor to its struct-literal peer under `PartialEq`, so
14391    // every wire-up in [`SupervisorSpec::validate_children`] and
14392    // [`validate_no_self_supervision`] on that variant produces a
14393    // byte-equal `SupervisorError` to the pre-lift open-coded
14394    // struct-literal. The cross-axis pin that follows (non-default
14395    // caixa name) routes the sole constructor input axis through
14396    // `.to_string()`, so the fold does not silently collapse onto a
14397    // fixed name.
14398    //
14399    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
14400    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
14401    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
14402    // `missing_entry_ctor_matches_struct_literal_wrap` /
14403    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
14404    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
14405    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
14406    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
14407    // on the six sibling ctor families the recent trajectory closed
14408    // on the peer `LayoutError` / `AplicacaoError` envelopes.
14409
14410    #[test]
14411    fn empty_child_version_ctor_matches_struct_literal_wrap() {
14412        assert_eq!(
14413            SupervisorError::empty_child_version("worker"),
14414            SupervisorError::EmptyChildVersion {
14415                caixa: "worker".to_string(),
14416            },
14417            "generated empty_child_version ctor must produce byte-equal \
14418             SupervisorError to the open-coded struct-literal wrap on the \
14419             same &str fixture",
14420        );
14421    }
14422
14423    #[test]
14424    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
14425        assert_eq!(
14426            SupervisorError::duplicate_child_caixa("worker"),
14427            SupervisorError::DuplicateChildCaixa {
14428                caixa: "worker".to_string(),
14429            },
14430            "generated duplicate_child_caixa ctor must produce byte-equal \
14431             SupervisorError to the open-coded struct-literal wrap on the \
14432             same &str fixture",
14433        );
14434    }
14435
14436    #[test]
14437    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
14438        assert_eq!(
14439            SupervisorError::child_supervises_self("orquestra"),
14440            SupervisorError::ChildSupervisesSelf {
14441                caixa: "orquestra".to_string(),
14442            },
14443            "generated child_supervises_self ctor must produce byte-equal \
14444             SupervisorError to the open-coded struct-literal wrap on the \
14445             same &str fixture",
14446        );
14447    }
14448
14449    // Per-variant equivalence pins for the two lifted
14450    // [`SupervisorError::child_caixa_invalid`] /
14451    // [`SupervisorError::child_versao_invalid`] inherent constructors
14452    // (fail-before-pass-after by construction — a byte-mismatched ctor body
14453    // would trip its equivalence pin first). Each pins the ctor output to
14454    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
14455    // in [`SupervisorSpec::validate_children`] on the two variants
14456    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
14457    // struct-literal on the same scalar fixtures. Peers of the sibling
14458    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
14459    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
14460    // the peer `AplicacaoError` envelope's
14461    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
14462
14463    #[test]
14464    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
14465        let caixa = "Worker";
14466        let reason = "sample reason text";
14467        assert_eq!(
14468            SupervisorError::child_caixa_invalid(caixa, reason),
14469            SupervisorError::ChildCaixaInvalid {
14470                caixa: caixa.to_string(),
14471                reason: reason.to_string(),
14472            },
14473            "lifted child_caixa_invalid ctor must produce byte-equal \
14474             SupervisorError to the open-coded struct-literal wrap on the \
14475             same (&str, reason) fixture",
14476        );
14477    }
14478
14479    #[test]
14480    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
14481        let caixa = "worker";
14482        let versao = "not-a-req";
14483        let reason = "sample reason text";
14484        assert_eq!(
14485            SupervisorError::child_versao_invalid(caixa, versao, reason),
14486            SupervisorError::ChildVersaoInvalid {
14487                caixa: caixa.to_string(),
14488                versao: versao.to_string(),
14489                reason: reason.to_string(),
14490            },
14491            "lifted child_versao_invalid ctor must produce byte-equal \
14492             SupervisorError to the open-coded struct-literal wrap on the \
14493             same (&str, &str, reason) fixture",
14494        );
14495    }
14496
14497    #[test]
14498    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
14499        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
14500        // against a `&str`-literal vs. `format!(…)` reason input to pin
14501        // both constructors accept the `impl Into<String>` bound
14502        // uniformly, so neither wire-up site drifts under a per-arm
14503        // wrapper transformation on the caller-side `reason` axis. Peer
14504        // of the sibling
14505        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
14506        // sweep on the peer `AplicacaoError` envelope.
14507        let via_literal = "literal reason text";
14508        let via_format = format!("{} reason text", "literal");
14509        assert_eq!(
14510            SupervisorError::child_caixa_invalid("Worker", via_literal),
14511            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
14512        );
14513        assert_eq!(
14514            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
14515            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
14516        );
14517    }
14518
14519    #[test]
14520    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
14521        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
14522        // &str`) through a non-default fixture name against every
14523        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
14524        // so any wrapper-side lowercase / trim / truncate / re-order on
14525        // the `caixa.to_string()` sole-field construction surfaces
14526        // here rather than at a downstream diagnostic-shape mismatch.
14527        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
14528        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
14529        // through_to_string` / `contrato_target_ctors_route_edge_
14530        // triple_through_verbatim` / `contrato_empty_pair_ctors_
14531        // route_edge_pair_through_verbatim` cross-axis routing pins on
14532        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
14533        // here onto the `SupervisorError` `{ caixa: String }` envelope
14534        // so every substrate-primitive ctor family in caixa-core
14535        // guarantees the sole-field construction routes the caller's
14536        // `&str` through `.to_string()` verbatim.
14537        let name = "cache-v2";
14538        assert_eq!(
14539            SupervisorError::empty_child_version(name),
14540            SupervisorError::EmptyChildVersion {
14541                caixa: name.to_string(),
14542            },
14543        );
14544        assert_eq!(
14545            SupervisorError::duplicate_child_caixa(name),
14546            SupervisorError::DuplicateChildCaixa {
14547                caixa: name.to_string(),
14548            },
14549        );
14550        assert_eq!(
14551            SupervisorError::child_supervises_self(name),
14552            SupervisorError::ChildSupervisesSelf {
14553                caixa: name.to_string(),
14554            },
14555        );
14556    }
14557
14558    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
14559    //
14560    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
14561    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
14562    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
14563    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
14564    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
14565    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
14566    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
14567    // / silent constant-substitution on any one variant surfaces here rather
14568    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
14569    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
14570    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
14571    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
14572    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
14573    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
14574    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
14575    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
14576    #[test]
14577    fn no_children_ctor_matches_struct_literal_wrap() {
14578        let estrategia = RestartStrategy::OneForAll;
14579        assert_eq!(
14580            SupervisorError::no_children(estrategia),
14581            SupervisorError::NoChildren { estrategia },
14582            "generated no_children ctor must produce byte-equal \
14583             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
14584             on the same `Copy`-`RestartStrategy` fixture",
14585        );
14586    }
14587
14588    #[test]
14589    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
14590        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14591        assert_eq!(
14592            SupervisorError::max_restarts_exceeds_cap(max_restarts),
14593            SupervisorError::MaxRestartsExceedsCap { max_restarts },
14594            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
14595             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
14596             struct-literal wrap on the same `Copy`-`u32` fixture",
14597        );
14598    }
14599
14600    #[test]
14601    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
14602        let window = Duration::from_micros(1_500);
14603        assert_eq!(
14604            SupervisorError::restart_window_not_canonical(window),
14605            SupervisorError::RestartWindowNotCanonical { window },
14606            "generated restart_window_not_canonical ctor must produce \
14607             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
14608             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14609        );
14610    }
14611
14612    #[test]
14613    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
14614        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14615        assert_eq!(
14616            SupervisorError::restart_window_exceeds_cap(window),
14617            SupervisorError::RestartWindowExceedsCap { window },
14618            "generated restart_window_exceeds_cap ctor must produce \
14619             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
14620             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14621        );
14622    }
14623
14624    #[test]
14625    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
14626        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
14627        // constructor input axis through a non-default `Copy` fixture against
14628        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
14629        // side silent `.into()` / silent constant-substitution / silent field
14630        // re-name away from the canonical `estrategia | max_restarts | window`
14631        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
14632        // axis silently rerouted through some other `Copy` coercion, surfaces
14633        // here rather than at a downstream per-`:supervisor` diagnostic-shape
14634        // drift. Peer of the sibling
14635        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
14636        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
14637        // envelope's per-`:politicas` per-axis ctor family, extended here onto
14638        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
14639        // variant family folded onto a substrate primitive.
14640        //
14641        // Fixtures picked out of each variant's accept-set boundary rather
14642        // than the default value so a silent constant-substitution to a per-
14643        // variant sentinel surfaces here on the structural-equality assertion.
14644        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
14645        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
14646        // isn't the `SimpleOneForOne` arm the sibling
14647        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
14648        // `max_restarts` fixture picks an above-cap magnitude the cap arm
14649        // rejects; the two `Duration` fixtures pick the sub-millisecond and
14650        // above-cap ends of the `:restart-window` canonical-form + cap
14651        // bracket respectively.
14652        let estrategia = RestartStrategy::RestForOne;
14653        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
14654        let sub_ms = Duration::from_micros(1_500);
14655        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
14656        assert_eq!(
14657            SupervisorError::no_children(estrategia),
14658            SupervisorError::NoChildren { estrategia },
14659        );
14660        assert_eq!(
14661            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
14662            SupervisorError::MaxRestartsExceedsCap {
14663                max_restarts: above_cap_restarts,
14664            },
14665        );
14666        assert_eq!(
14667            SupervisorError::restart_window_not_canonical(sub_ms),
14668            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
14669        );
14670        assert_eq!(
14671            SupervisorError::restart_window_exceeds_cap(above_hour),
14672            SupervisorError::RestartWindowExceedsCap { window: above_hour },
14673        );
14674    }
14675
14676    #[test]
14677    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
14678        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
14679        // generated ctor `const fn` so a caller can pin a `SupervisorError`
14680        // at compile time — the same zero-runtime-work property the pre-lift
14681        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
14682        // its `Copy`-pass-through construction path (no `.to_string()` /
14683        // `.into()` allocation, no branching). If any future edit silently
14684        // drops the `const` qualifier from the macro body the per-arm `const`
14685        // bindings below fail to compile, which surfaces the regression at
14686        // the substrate-primitive definition rather than at some downstream
14687        // consumer that had come to rely on the `const`-constructibility.
14688        // Peer of the sibling
14689        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
14690        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
14691        // per-`:politicas` per-axis ctor family.
14692        const NO_CHILDREN: SupervisorError =
14693            SupervisorError::no_children(RestartStrategy::OneForAll);
14694        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
14695        const WINDOW_NC: SupervisorError =
14696            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
14697        const WINDOW_CAP: SupervisorError =
14698            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
14699        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
14700        assert!(matches!(
14701            MAX_RESTARTS_CAP,
14702            SupervisorError::MaxRestartsExceedsCap { .. }
14703        ));
14704        assert!(matches!(
14705            WINDOW_NC,
14706            SupervisorError::RestartWindowNotCanonical { .. }
14707        ));
14708        assert!(matches!(
14709            WINDOW_CAP,
14710            SupervisorError::RestartWindowExceedsCap { .. }
14711        ));
14712    }
14713}