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/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
1428/// reverse projection on the first M2 OTP-shape closed-set fieldless
1429/// typed enum peer on the caixa surface ([`RestartStrategy`]) — the
1430/// byte-mirror of the [`From<RestartStrategy> for String`] str-owned
1431/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
1432/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
1433/// (cd4c4e0) lifted on this same enum. Routes byte-for-byte through
1434/// the substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1435/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
1436/// consumer that binds a [`RestartStrategy`] through the standard-
1437/// library `impl From<RestartStrategy> for Vec<u8>` axis
1438/// (equivalently `<T: Into<Vec<u8>>>`) — a future
1439/// [`std::io::Write::write_all`]-shape per-supervisor audit-log byte-
1440/// sink whose input parameter is an owned [`Vec<u8>`] payload, a
1441/// future `bytes::Bytes::from(Vec::<u8>::from(strategy))` composer
1442/// folding the per-arm sibling-restart-topology byte-tag into the
1443/// [`bytes::Bytes`] framing surface, a future
1444/// `hasher.update(&Vec::<u8>::from(strategy))`-shape BLAKE3 content-
1445/// address closure that needs the owned byte-tail buffered before
1446/// folding into the [`crate::Lacre`] closure body, a future per-
1447/// strategy protobuf/CBOR/msgpack payload composer whose framer takes
1448/// an owned [`Vec<u8>`] rather than a borrowed byte-slice — reaches
1449/// the substrate primitive through one trait dispatch rather than an
1450/// open-coded per-call-site `strategy.as_str().as_bytes().to_vec()`
1451/// composition whose type bounds have no compile-time link back to
1452/// the substrate primitive.
1453///
1454/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1455/// projection axis onto the first M2-OTP-shape closed-set fieldless
1456/// typed-enum peer, matching the trajectory the first-mover
1457/// [`crate::CaixaKind`] `From<{Self, &Self}> for Vec<u8>` lift
1458/// (b245fd6), the second-mover [`crate::dialeto::CaixaDialeto`] lift
1459/// (4cceaf5), and the third-mover [`crate::dep::DepList`] lift
1460/// (e974ca2) established across the caixa-core-internal tier. Every
1461/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
1462/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1463/// might reach for once the four canonical OTP strategies stop
1464/// covering the substrate's discovered load-shape) grows the byte-
1465/// owned axis through one edit on the substrate-primitive
1466/// [`RestartStrategy::as_str`] accessor, mirroring the discipline the
1467/// paired [`AsRef<[u8]>`] borrowed byte-view axis campaign already
1468/// tracked across every closed-set fieldless typed enum peer on the
1469/// substrate.
1470///
1471/// Pinned load-bearing by
1472/// [`tests::restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
1473/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1474/// four-arm [`RestartStrategy::ALL`] emit-set binding the byte-owned
1475/// reverse-projection axis against the paired [`AsRef<[u8]>`]
1476/// borrowed byte-view axis and the str-owned reverse-projection
1477/// family (`String`, `Cow<'static, str>`, `Box<str>`,
1478/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
1479/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
1480/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
1481/// witness on both owned and borrowed input shapes).
1482impl From<RestartStrategy> for Vec<u8> {
1483    fn from(strategy: RestartStrategy) -> Vec<u8> {
1484        strategy.as_str().as_bytes().to_vec()
1485    }
1486}
1487
1488/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
1489/// owned reverse projection on the first M2 OTP-shape closed-set
1490/// fieldless typed enum peer on the caixa surface
1491/// ([`RestartStrategy`]) — the borrowed-input peer of
1492/// [`From<RestartStrategy> for Vec<u8>`], closing the
1493/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
1494/// axis in one lift. Routes byte-for-byte through the substrate-
1495/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor so
1496/// every consumer that holds a borrowed [`&RestartStrategy`] and
1497/// needs an owned [`Vec<u8>`] — a future
1498/// `.iter().map(Vec::<u8>::from).collect()` pipe over
1499/// `&[RestartStrategy]` (whose iterator yields `&RestartStrategy`,
1500/// not `RestartStrategy`, so the owned-input axis alone forces every
1501/// call site through an explicit `.copied()` / spurious [`Copy`]
1502/// deref restatement rather than the direct trait-idiomatic
1503/// projection), a future admission-webhook rejection body composer
1504/// that walks [`RestartStrategy::ALL`] through an `Into<Vec<u8>>`-
1505/// bound per-arm byte-writer to surface the accepted `:estrategia`
1506/// set — reaches the substrate primitive through one trait dispatch
1507/// rather than a `Vec::<u8>::from(*strategy)` spurious-`Copy`-deref
1508/// restatement.
1509impl From<&RestartStrategy> for Vec<u8> {
1510    fn from(strategy: &RestartStrategy) -> Vec<u8> {
1511        strategy.as_str().as_bytes().to_vec()
1512    }
1513}
1514
1515/// Per-child restart policy.
1516///
1517/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1518#[derive(
1519    Serialize,
1520    Deserialize,
1521    Debug,
1522    Clone,
1523    Copy,
1524    PartialEq,
1525    Eq,
1526    Hash,
1527    gen_platform::TypedDispatcher,
1528    gen_platform::Discriminant,
1529    gen_platform::IsVariant,
1530    gen_platform::FromStrKind,
1531)]
1532pub enum RestartPolicy {
1533    /// Always restart the child, regardless of how it died. Used for
1534    /// long-running services that must always be up.
1535    Permanent,
1536    /// Never restart. Used for one-shot work whose completion is
1537    /// itself the success signal (`oneShot` triggers map here).
1538    Temporary,
1539    /// Restart only when the child died *abnormally* (non-zero exit
1540    /// or unhandled exception). A clean exit completes the child.
1541    Transient,
1542}
1543
1544impl Default for RestartPolicy {
1545    fn default() -> Self {
1546        // Route the [`Default for RestartPolicy`] impl's return arm through
1547        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1548        // `pub const` rather than a raw `Self::Permanent` arm — one source
1549        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1550        // default across the two production consumers that currently
1551        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1552        // and the serde-side `#[serde(default)]` on
1553        // [`ChildSpec::restart`] that resolves an author-omitted
1554        // `:children :restart` slot through `RestartPolicy::default()`).
1555        // Peer of the sibling per-`:supervisor` axis
1556        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1557        // route (95ffacc) — the two impls now share one substrate-primitive
1558        // lift discipline, so any future coherent rebrand of the OTP-shape
1559        // supervisor+child default set migrates through typed constants in
1560        // lockstep instead of splitting a lifted supervisor half against
1561        // an open-coded child half. Pinned by
1562        // `restart_policy_default_routes_through_lifted_default` +
1563        // `child_spec_serde_default_restart_routes_through_lifted_default`
1564        // in the tests module.
1565        SUPERVISOR_CHILD_RESTART_DEFAULT
1566    }
1567}
1568
1569impl RestartPolicy {
1570    /// Exhaustive iteration surface for every consumer that walks the
1571    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1572    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1573    /// per-child admission-webhook rejection body naming the accepted-
1574    /// `:restart` list, a future `feira supervisor --restart …` CLI
1575    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1576    /// over the slice, the future `feira app graph` per-child restart
1577    /// column, any future round-trip fuzz harness that sweeps every
1578    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1579    /// theory
1580    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1581    /// might reach for once the three canonical OTP restart policies
1582    /// stop covering the substrate's discovered load-shape) extends
1583    /// this slice as one edit and every consumer picks up the new entry
1584    /// by construction; the compiler-checked exhaustiveness on the
1585    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1586    /// is the build-time guarantee that no arm forgets to grow.
1587    ///
1588    /// Peer of the sibling closed-set typed enums'
1589    /// [`RestartStrategy::ALL`] (4eec29c) /
1590    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1591    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1592    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1593    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1594    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1595    /// closed-set typed enum on the caixa surface to converge onto the
1596    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1597    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1598    /// sibling-restart-strategy axis; this closes the per-child
1599    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1600    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1601
1602    /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1603    /// `PascalCase` wire byte-string axis — the closed three-arm roster
1604    /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1605    /// through the paired
1606    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1607    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1608    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1609    /// `pub const` roster the [`Self::as_str`] emitter (and the
1610    /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1611    /// walks — and byte-for-byte the same three strings the un-`rename`d
1612    /// `Serialize` derive emits under the paired
1613    /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1614    /// JSON / YAML CR round-trip.
1615    ///
1616    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1617    /// roster on the top-level typed-kind discriminator's `PascalCase`
1618    /// wire byte-string axis, the sibling
1619    /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1620    /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1621    /// closed-set typed enum to converge onto the paired-roster
1622    /// discipline), the sibling
1623    /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1624    /// roster on the first M3 mesh-shape distribution-strategy closed-
1625    /// set typed enum, and the sibling
1626    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1627    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1628    /// rosters on the OTP-appup discriminator's two-axis roster split —
1629    /// the same closed-set exhaustive-accept-set roster discipline
1630    /// extended here onto the second and final M2 OTP-shape sibling-
1631    /// enum on the caixa surface, closing the per-child restart-decision-
1632    /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1633    /// per-supervisor sibling-restart-strategy axis on the same M2
1634    /// `:supervisor` slot.
1635    ///
1636    /// Downstream consumers of the closed accepted-wire-form set — a
1637    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1638    /// webhook rejection body enumerating the accepted JSON `:restart`
1639    /// values verbatim (as distinct from the kebab-case dispatcher-
1640    /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1641    /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1642    /// disagrees with the wire byte-string these `PascalCase` entries
1643    /// carry — the split the sibling
1644    /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1645    /// pin already makes load-bearing), a future `feira supervisor
1646    /// --restart …` CLI-side "did you mean" hint whose candidate-list
1647    /// must byte-match the wire form the operator's per-child dispatch
1648    /// keys off, a future `feira app graph` per-child `:restart`-
1649    /// histogram column that renders zero-count arms, a future
1650    /// `caixa-operator` per-reconcile-step diagnostic log line
1651    /// enumerating accepted wire forms on an unknown-policy rejection,
1652    /// a future
1653    /// `tracing::field::valuable::Value::List` structured-log accepted-
1654    /// wire-form emit — now reach for one lifted substrate-primitive
1655    /// roster rather than open-coding a three-string array-literal
1656    /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1657    /// compile-time link back to the typed [`RestartPolicy`] enum. A
1658    /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1659    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1660    /// might reach for once the three canonical OTP restart policies
1661    /// stop covering the substrate's discovered load-shape) extends
1662    /// this roster as a single edit — paired with the [`Self::as_str`]
1663    /// match's compiler-checked exhaustiveness on the new arm — and
1664    /// every consumer picks up the new wire form by construction rather
1665    /// than a coordinated array-literal rewrite across every downstream
1666    /// site.
1667    ///
1668    /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1669    /// (three) by
1670    /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1671    /// variant's [`Self::as_str`] projection is pinned to a member of
1672    /// the roster so a silent skew between the emitter's arm-set and
1673    /// this const's arm-set trips at caixa-core test time rather than at
1674    /// a downstream consumer's accepted-set enumeration miss, and every
1675    /// entry is further pinned to open with an ASCII uppercase byte so
1676    /// a silent collapse of the `PascalCase` wire-form axis with the
1677    /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1678    /// to a sibling [`Self::discriminant`] kebab byte-string that would
1679    /// let a wire-axis consumer accept the dispatcher-catalog
1680    /// vocabulary) trips here rather than at a downstream K8s-CR round-
1681    /// trip miss.
1682    pub const WIRE_NAMES: &'static [&'static str] = &[
1683        crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1684        crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1685        crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1686    ];
1687
1688    /// Canonical PascalCase discriminator scalar this variant serializes
1689    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1690    /// arms return the paired
1691    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1692    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1693    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1694    /// constants so every substrate consumer that dispatches on the
1695    /// per-child restart-decision policy (the future wasm-operator's
1696    /// per-child post-exit restart-decision branch, the future M4
1697    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1698    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1699    /// reconciliation scheduler's per-child-policy fan-out) reads the
1700    /// same byte-string the `Serialize` derive emits — the pin test in
1701    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1702    /// asserts the two paths agree, peer of the M2
1703    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1704    /// sibling-restart-strategy axis and the M3
1705    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1706    /// per-Aplicacao distribution-strategy axis — the third of three
1707    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1708    /// surface to converge onto the same three-path-convergence
1709    /// (`Serialize` derive → `as_str` helper → lifted constant)
1710    /// drift-detection posture.
1711    #[must_use]
1712    pub const fn as_str(self) -> &'static str {
1713        match self {
1714            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1715            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1716            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1717        }
1718    }
1719
1720    /// Substrate-canonical reverse projection on the `:children :restart`
1721    /// closed-set axis — parses the `PascalCase` discriminator scalar
1722    /// back to the typed variant, or `None` when `s` is outside the
1723    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1724    /// the same lifted
1725    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1726    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1727    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1728    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1729    /// of the round-trip migrate through one caixa-core edit on any
1730    /// future arm addition.
1731    ///
1732    /// Prior to this lift the substrate carried only the forward
1733    /// `Self → &str` projection on the OTP per-child restart-policy
1734    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1735    /// impl routed through it, the `Serialize` derive that emits the
1736    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1737    /// plus the kebab-case dispatcher-catalog identity via
1738    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1739    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1740    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1741    /// "Transient" => …, _ => … }` cascade that expressed no
1742    /// compile-time link back to the typed variant's canonical lifted
1743    /// constant. A future variant rename or per-arm serde-attribute
1744    /// drift would silently split the wire byte-string one non-serde
1745    /// consumer parsed from the one the emitter wrote, with the failure
1746    /// surfacing at the operator's reconcile posture (a `:temporary`
1747    /// `oneShot` child being restarted on clean exit, treating the
1748    /// successful-completion signal as failure and re-running the
1749    /// completion-terminal one-shot indefinitely; a `:transient` child
1750    /// that clean-exited being restarted, masking the clean-completion
1751    /// contract) far from the rebrand commit and with no field naming
1752    /// the drift.
1753    ///
1754    /// Distinct axis from the [`std::str::FromStr`] impl the
1755    /// [`gen_platform::FromStrKind`] derive already installs on this
1756    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1757    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1758    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1759    /// this method inverts the `PascalCase` wire byte-string
1760    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1761    /// catalog identity live in kebab-case (where every peer catalog
1762    /// identifier already lives) without forcing a wire-format rename
1763    /// on the tatara-lisp author surface (`:restart Permanent`,
1764    /// `PascalCase`) — the same two-axis distinction the sibling
1765    /// [`RestartStrategy::from_wire`] (4eec29c) /
1766    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1767    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1768    /// carry on their peer closed-set typed-enum wire round-trips.
1769    ///
1770    /// Same closed-set-reverse-projection discipline the sibling
1771    /// [`RestartStrategy::from_wire`] (4eec29c) /
1772    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1773    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1774    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1775    /// carry on the peer wire-side `str → Self` axes — extended onto
1776    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1777    /// sixth substrate-side closed-set typed enum (and the third and
1778    /// final OTP-shape closed-enum discriminator axis) to converge on
1779    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1780    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1781    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1782    /// derive already installs on the sibling kebab-case axis. Returns
1783    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1784    /// shapes: the caller picks the diagnostic form appropriate for
1785    /// its use site.
1786    #[must_use]
1787    pub fn from_wire(s: &str) -> Option<Self> {
1788        match s {
1789            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1790            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1791            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1792            _ => None,
1793        }
1794    }
1795}
1796
1797/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1798/// pretty-printed byte-string every consumer that formats the policy as
1799/// user-facing text lands on (the future wasm-operator's per-child
1800/// post-exit restart-decision diagnostic line, the future `feira app
1801/// graph` per-child restart column, the future M4
1802/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1803/// admission-webhook rejection body) reaches for the same lifted
1804/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1805/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1806/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1807/// wire-format `Serialize` derive already emits under
1808/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1809/// [`RestartPolicy::as_str`] helper already returns.
1810///
1811/// Pre-convergence the two paths structurally disagreed — the
1812/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1813/// route (now retired here) sent [`std::fmt::Display`] through the
1814/// gen-platform discriminant catalog string, which arrives kebab-case as
1815/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1816/// (whose variant names each collapse to their own lowercase form under
1817/// the kebab-case transform), while the wire format ran as `PascalCase`
1818/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1819/// serde derive. Every consumer that formatted the policy for a
1820/// diagnostic line, a graph column, or a rejection body under
1821/// `format!("{v}")` therefore landed under a different byte-string than
1822/// the wire format the operator's per-child-policy dispatch keyed off —
1823/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1824/// diagnostic quoting `"permanent"` while the wire scalar the operator
1825/// probed was `"Permanent"`) surfaced as a confused correlate at
1826/// operator-log time far from the two-declaration site.
1827///
1828/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1829/// path: every `format!("{v}")` call reaches the same lifted
1830/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1831/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1832/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1833/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1834/// byte-string per variant. A future variant rename or
1835/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1836/// exactly one place, structurally.
1837///
1838/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1839/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1840/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1841/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1842/// registration keys the catalog off the same kebab identity. The two
1843/// naming worlds now live on separate typed methods (`Display` /
1844/// `as_str` for the wire byte-string, `discriminant` for the catalog
1845/// identity) rather than sharing one `Display` route that structurally
1846/// disagrees with the wire format.
1847///
1848/// Pin tests
1849/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1850/// and
1851/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1852/// assert the three paths agree byte-for-byte on every variant, so a
1853/// future variant rename or per-arm serde attribute drift is a build
1854/// error visible at caixa-core test time, not a silent per-consumer
1855/// dispatch miss at apply / reconcile time.
1856///
1857/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1858/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1859/// and the sibling [`RestartStrategy`] `Display` impl on the
1860/// per-supervisor sibling-restart-strategy axis — same three-path-
1861/// convergence discipline, extended to close the third and final of
1862/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1863/// surface.
1864impl std::fmt::Display for RestartPolicy {
1865    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1866        f.write_str(self.as_str())
1867    }
1868}
1869
1870/// Substrate-canonical [`AsRef<str>`] projection on the M2
1871/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1872/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1873/// scalar accessor the paired [`std::fmt::Display`] impl and the
1874/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1875/// future consumer that binds a [`RestartPolicy`] through the
1876/// standard-library `impl AsRef<str>` bound (a future
1877/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1878/// composes the emitted `PascalCase` wire scalar into a
1879/// [`std::process::Command::arg`] shell-out of the future
1880/// wasm-operator's per-child admission gate, a per-child structured-
1881/// log recorder on the future `caixa-operator`'s hierarchical
1882/// reconciliation surface that accepts `impl AsRef<str>` at the
1883/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1884/// lookup keyed on the restart-policy wire byte through
1885/// `map.get::<str>(policy.as_ref())` on a future per-policy
1886/// dispatch table) reaches the paired
1887/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1888/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1889/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1890/// lifted-const through one substrate-primitive dispatch rather
1891/// than an open-coded `.as_str()` projection at every wire-up.
1892///
1893/// Peer of the sibling [`std::fmt::Display`] impl on the same
1894/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1895/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1896/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1897/// byte-string per instance by construction. A future variant rename
1898/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1899/// enum reaches every one of the three paths (plus the wire-format
1900/// `Serialize` derive that already routes through the same lifted
1901/// const) through exactly one caixa-core edit.
1902///
1903/// Same "route the trait impl through the substrate-primitive
1904/// accessor" discipline the sibling [`crate::CaixaVersion`]
1905/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1906/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1907/// the axis onto the paired per-child-restart-decision-policy
1908/// sibling on the same M2 `:supervisor` slot (the second M2
1909/// OTP-shape closed-set typed enum to converge onto the standard-
1910/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1911/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1912/// primitive so a caller who has one has both; before this lift,
1913/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1914/// [`AsRef<str>`] impl the convention names.
1915///
1916/// Pinned load-bearing by
1917/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1918/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1919/// three-arm closed set) and
1920/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1921/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1922/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1923/// arm) — any future silent detour that routes the impl through a
1924/// divergent projection (a per-arm inline `match self { … }`
1925/// re-inlining that opens a compile-time link to the un-lifted
1926/// arm-literal, a swap onto the kebab-case
1927/// [`gen_platform::Discriminant`] catalog identity that would
1928/// collide the wire axis with the dispatcher-catalog axis) trips at
1929/// caixa-core test time under `assert_eq!` rather than at a
1930/// downstream `impl AsRef<str>`-bound consumer's silent split.
1931impl AsRef<str> for RestartPolicy {
1932    fn as_ref(&self) -> &str {
1933        self.as_str()
1934    }
1935}
1936
1937/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1938/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1939/// byte-for-byte through the paired substrate-primitive
1940/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1941/// consumer that binds a `PascalCase` `:children :restart` wire
1942/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1943/// axis (a future [`caixa-feira`] `feira supervisor --restart
1944/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1945/// `let restart: RestartPolicy = s.try_into()?`, a future
1946/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1947/// `spec.children[*].restart: String` field through
1948/// `RestartPolicy::try_from(&s)?`, a generic
1949/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1950/// set typed enums) reaches the same three-arm accept-set the sibling
1951/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1952/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1953/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1954/// … }` cascade whose arm-set has no compile-time link back to the
1955/// substrate primitive.
1956///
1957/// Complements the pre-existing forward-projection triple
1958/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1959/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1960/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1961/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1962/// caller who can project *out to* a `&str` can also project *in from*
1963/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1964/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1965/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1966/// trigger under a `FromStr` impl and to avoid colliding with the
1967/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1968/// already installs on the paired *kebab-case dispatcher-catalog* axis
1969/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1970/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1971/// idiomatic reverse axis on the *`PascalCase` wire* half without
1972/// disturbing either the method-named `from_wire` shape every sibling
1973/// closed-set typed enum on the substrate already carries or the
1974/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1975/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1976///
1977/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1978/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1979/// caller picks the diagnostic form appropriate for its use site (a
1980/// future `feira supervisor --restart` arg-parse composes its own
1981/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1982/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1983/// wraps the `Err(())` outcome with the accepted-set enumeration for
1984/// operator diagnostics, a `Result::map_err` at the call site lifts the
1985/// unit-error to a per-verb error type). Same shape the peer
1986/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1987/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1988/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1989/// their peer closed-set typed enums' reverse projections.
1990///
1991/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1992/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1993/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1994/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1995/// might reach for once the three canonical OTP restart policies stop
1996/// covering the substrate's discovered load-shape) grows the trait-
1997/// idiomatic axis by construction — one caixa-core edit on
1998/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1999/// projection every existing consumer keys off and the trait-idiomatic
2000/// reverse projection this impl exposes, without a coordinated rewrite
2001/// across every future `TryFrom<&str>`-bound consumer's arm-set.
2002///
2003/// Extends the substrate-wide closed-set-enum reverse-projection family
2004/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
2005/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
2006/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
2007/// closed-enum discriminator axis on the caixa surface — the paired
2008/// per-child `:children :restart` closed set the future wasm-operator's
2009/// hierarchical reconciliation scheduler's per-child post-exit
2010/// restart-decision branch keys off end-to-end.
2011///
2012/// Pinned load-bearing by
2013/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
2014/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
2015/// three-arm accept-set),
2016/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
2017/// (rejection witness against silent accept-set widening), and
2018/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
2019/// (cross-axis partition pin locking the trait and method-named
2020/// projections onto one accept-set).
2021impl TryFrom<&str> for RestartPolicy {
2022    type Error = ();
2023
2024    fn try_from(s: &str) -> Result<Self, Self::Error> {
2025        Self::from_wire(s).ok_or(())
2026    }
2027}
2028
2029/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
2030/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2031/// byte-for-byte through the paired substrate-primitive
2032/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
2033/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
2034/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
2035/// &str` with `'static` lifetime, so the trait's return-type promise is
2036/// upheld structurally without a [`String::leak`] cast or a per-arm inline
2037/// literal.
2038///
2039/// Every future consumer that specifically needs `&'static str` lifetime
2040/// bytes on the per-child restart-decision axis (a
2041/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
2042/// arm's typing demands `&'static str`, a
2043/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
2044/// on the future M4 admission-webhook rejection body where the
2045/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
2046/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
2047/// or error formatter that requires the `'static` bound) reaches the same
2048/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2049/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2050/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
2051/// primitive dispatch rather than an open-coded per-arm literal cascade
2052/// whose arm-set has no compile-time link back to the substrate primitive.
2053///
2054/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
2055/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
2056/// the second (and second-of-two-in-M2) closed-set typed enum on the
2057/// caixa surface to converge onto the paired trait-idiomatic forward-
2058/// projection axis. With this lift the paired per-child
2059/// `:children :restart` closed-set typed enum carries the full sibling
2060/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2061/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
2062/// lift) plus the round-trip witness through both the trait-idiomatic
2063/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
2064/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
2065/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
2066/// (an OTP-`intrinsic` fourth arm the theory
2067/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2068/// might reach for once the three canonical OTP restart policies stop
2069/// covering the substrate's discovered load-shape) grows the trait-
2070/// idiomatic forward axis by construction: one caixa-core edit on
2071/// [`RestartPolicy::as_str`] extends every one of the five sibling
2072/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
2073/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
2074/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
2075/// bytes) without a coordinated rewrite across every future
2076/// `Into<&'static str>`-bound consumer's arm-set.
2077///
2078/// Pinned load-bearing by
2079/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2080/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2081/// three-arm emit-set, plus a `const`-context materialization witness for
2082/// the `&'static str` lifetime promise) and
2083/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2084/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
2085/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
2086/// round-trip witness through the paired trait-idiomatic reverse-
2087/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2088/// `policy.into::<&'static str>()` output re-parses back through
2089/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2090/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2091impl From<RestartPolicy> for &'static str {
2092    fn from(policy: RestartPolicy) -> &'static str {
2093        policy.as_str()
2094    }
2095}
2096
2097/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2098/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2099/// companion to the paired owned-input [`From<RestartPolicy> for
2100/// &'static str`] impl immediately above. Routes byte-for-byte through
2101/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2102/// fn` accessor so every consumer that binds a `&RestartPolicy`
2103/// through the standard-library `.into()` / [`From<&Self> for &'static
2104/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2105/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2106/// whose iterator over `&'static [RestartPolicy]` yields
2107/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2108/// [`From<RestartPolicy>`] axis alone forces every call site through
2109/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2110/// rather than the direct trait-idiomatic projection; a future generic
2111/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2112/// that walks the `iter().map(Into::into)` shape verbatim across every
2113/// substrate-wide closed-set typed enum; the future wasm-operator's
2114/// per-child post-exit restart-decision diagnostic line that composes
2115/// the accepted-set enumeration from an iterated
2116/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2117/// per-arm `match p { … }` cascade; a future
2118/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2119///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2120/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2121/// cannot compose without this borrowed-input axis in place) reaches
2122/// the same three-arm lifted
2123/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2124/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2125/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2126/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2127/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2128/// [`RestartPolicy::as_str`] surfaces already return.
2129///
2130/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2131/// forward-projection family opened on [`crate::dep::DepList`]
2132/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2133/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2134/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2135/// (e941836). Rust's `From` trait does not auto-derive the
2136/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2137/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2138/// exist in `core`), so every closed-set typed enum that carries the
2139/// owned-input axis but not the borrowed-input axis forces every
2140/// borrowed-input call site through a `.copied()` /
2141/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2142/// type bounds have no compile-time link to the substrate primitive.
2143/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2144/// OTP-shape peer to converge onto this campaign — sibling of the
2145/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2146/// with this lift both closed-set typed enums on the M2 `:supervisor`
2147/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2148/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2149/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2150/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2151/// forward-projection axis on the M2 OTP-shape slot as a unit.
2152///
2153/// Same three-path convergence discipline as the paired owned-input
2154/// impl (this borrowed-input axis, the paired owned-input
2155/// [`From<RestartPolicy> for &'static str`], and
2156/// [`RestartPolicy::as_str`] all route through the same lifted
2157/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2158/// variant rename or per-arm serde-attribute drift reaches every one
2159/// of the six sibling forward-projection paths
2160/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2161/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2162/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2163/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2164/// edit.
2165///
2166/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2167/// parse share the same `PascalCase` vocabulary by construction, so
2168/// the borrowed-input forward axis and the reverse axis compose
2169/// directly — the round-trip witness pin below locks this direct
2170/// composition without the intermediate wire-vocab hop the peer
2171/// [`crate::CaixaKind`] axis pair requires.
2172///
2173/// Pinned load-bearing by
2174/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2175/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2176/// three-arm emit-set via a borrowed input, plus a `const`-context
2177/// materialization witness for the `&'static str` lifetime promise,
2178/// plus a blanket `.into()` shape) and
2179/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2180/// (cross-axis partition pin against the paired owned-input
2181/// [`From<RestartPolicy> for &'static str`] impl, plus a
2182/// `.iter().map(Into::into)` pipe witness over
2183/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2184/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2185/// Self` round-trip without the wire-vocab intermediate the peer
2186/// [`crate::CaixaKind`] axis pair requires).
2187impl From<&RestartPolicy> for &'static str {
2188    fn from(policy: &RestartPolicy) -> &'static str {
2189        policy.as_str()
2190    }
2191}
2192
2193/// Trait-idiomatic *owned-`String`* forward projection on the second
2194/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2195/// owned-heap-string companion to the paired `&'static str`-returning
2196/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2197/// for &'static str`] impls immediately above. Routes byte-for-byte
2198/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2199/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2200/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2201/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2202/// future `serde_json::Value::String(policy.into())` structured-payload
2203/// composer where the `Value::String` arm typing demands an owned
2204/// [`String`] and the sibling [`&'static str`]-returning axis forces
2205/// an explicit `.to_owned()` / `String::from` restatement at every
2206/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2207/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2208/// lookup where the map's key type is owned [`String`] rather than
2209/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2210/// composer on the future M4 admission-webhook rejection body's
2211/// owned-arm, the future wasm-operator's per-child post-exit
2212/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2213/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2214/// — reaches the same three-arm lifted
2215/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2216/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2217/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2218/// paired [`std::fmt::Display`], [`AsRef<str>`],
2219/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2220/// forward-projection impls already return.
2221///
2222/// Extends the trait-idiomatic *owned-`String`* forward-projection
2223/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2224/// the caixa surface — mirror of the first-mover
2225/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2226/// axis on the sibling supervisor-level strategy enum. Rust's standard
2227/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2228/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2229/// every closed-set typed enum that carries the paired `AsRef<str>` /
2230/// `Display` / `From<Self> for &'static str` triple but not the
2231/// owned-[`String`] axis forces every owned-string call site through a
2232/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2233/// detour whose type bounds have no compile-time link to the
2234/// substrate primitive.
2235///
2236/// Deliberately routes through the human-readable
2237/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2238/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2239/// the diagnostic byte-string share the same vocabulary by
2240/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2241/// two axes diverge), so the owned-[`String`] projection lands
2242/// byte-identically on both the wire vocabulary the paired
2243/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2244/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2245/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2246/// axis parses the same `PascalCase` vocabulary — the direct two-way
2247/// `Self → String → Self` round-trip composes without the wire-vocab
2248/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2249/// axis pair requires.
2250///
2251/// Pinned load-bearing by
2252/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2253/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2254/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2255/// witness) and
2256/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2257/// (cross-axis partition pin against the paired owned-input
2258/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2259/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2260/// plus a `.iter().copied().map(String::from)` pipe witness over
2261/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2262/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2263/// borrow that closes the two-way `Self → String → Self` round-trip
2264/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2265/// pair).
2266impl From<RestartPolicy> for String {
2267    fn from(policy: RestartPolicy) -> String {
2268        policy.as_str().to_owned()
2269    }
2270}
2271
2272/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2273/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2274/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2275/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2276/// projection family on this enum, mirror of the first-mover
2277/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2278/// 2×2-completion corner on the sibling supervisor-level strategy
2279/// enum. Routes byte-for-byte through the substrate-primitive
2280/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2281/// [`str::to_owned`]) so every consumer that holds a borrowed
2282/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2283/// `serde_json::Value::String(String::from(&policy))` structured-payload
2284/// composer over a borrowed field, a future `Iterator::map` over
2285/// `&[RestartPolicy]` that projects to owned keys through
2286/// `.iter().map(String::from)`, a future `HashMap::<String,
2287/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2288/// where dereferencing the policy would force an unnecessary `Copy` at
2289/// every step, the future wasm-operator's per-supervisor
2290/// `child_policies.iter().map(String::from).collect()` per-child post-
2291/// exit restart-decision diagnostic emit whose iteration axis is
2292/// borrowed by construction — reaches the same three-arm lifted
2293/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2294/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2295/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2296/// paired [`std::fmt::Display`], [`AsRef<str>`],
2297/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2298/// forward-projection impls
2299/// ([`From<RestartPolicy> for &'static str`],
2300/// [`From<&RestartPolicy> for &'static str`],
2301/// [`From<RestartPolicy> for String`]) already return.
2302///
2303/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2304/// owned-`String` output* forward-projection family opened on
2305/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2306/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2307/// both M2 OTP-shape sibling peers (the paired supervisor-level
2308/// sibling-restart-strategy axis and the per-child restart-decision-
2309/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2310/// full four-corner family by construction. Rust's standard library
2311/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2312/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2313/// closed-set typed enum that carries the paired `AsRef<str>` /
2314/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2315/// &'static str` / `From<Self> for String` quintuple but not the
2316/// borrowed-input owned-[`String`] axis forces every borrowed-input
2317/// owned-string call site through a `policy.as_str().to_owned()` /
2318/// `String::from(*policy)` (with a spurious `Copy`) /
2319/// `policy.to_string()` (through `Display`) detour whose type bounds
2320/// have no compile-time link to the substrate primitive.
2321///
2322/// Deliberately routes through the human-readable
2323/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2324/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2325/// the diagnostic byte-string share the same vocabulary by
2326/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2327/// two axes diverge), so the borrowed-input owned-[`String`]
2328/// projection lands byte-identically on both the wire vocabulary the
2329/// paired [`serde::Serialize`] derive emits and the diagnostic
2330/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2331/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2332/// reverse-projection axis parses the same `PascalCase` vocabulary —
2333/// the direct two-way `&Self → String → Self` round-trip composes
2334/// without the wire-vocab intermediate hop the peer
2335/// [`crate::CaixaKind`] axis pair requires.
2336///
2337/// The remaining thirteen closed-set typed enums on the caixa
2338/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2339/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2340/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2341/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2342/// of this 2×2-completion campaign — each carries the same paired
2343/// quintuple that this borrowed-input owned-[`String`] axis extends
2344/// onto.
2345///
2346/// Pinned load-bearing by
2347/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2348/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2349/// three-arm emit-set through the borrowed-input surface) and
2350/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2351/// (cross-axis partition pin against the paired owned-input owned-
2352/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2353/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2354/// &'static str`] impl, and the sibling [`ToString::to_string`]
2355/// surface routed through [`std::fmt::Display`], plus a direct round-
2356/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2357/// [`String::as_str`] borrow that closes the two-way
2358/// `&Self → String → Self` round-trip on the trait-idiomatic
2359/// borrowed-input owned-[`String`] forward + reverse axis pair).
2360impl From<&RestartPolicy> for String {
2361    fn from(policy: &RestartPolicy) -> String {
2362        policy.as_str().to_owned()
2363    }
2364}
2365
2366/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2367/// output* forward projection on the M2 OTP-shape per-child-restart
2368/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2369/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2370/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2371/// borrowed-input) and first extended off it onto the sibling M2
2372/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2373/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2374/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2375/// surface (`:children :restart`). Routes byte-for-byte through the
2376/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2377/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2378/// that binds a [`RestartPolicy`] through the trait-idiomatic
2379/// [`std::borrow::Cow<'static, str>`] axis — a future
2380/// `axum::response::IntoResponse` composer whose per-policy
2381/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2382/// borrowed return, a future M4 admission-webhook rejection body
2383/// that composes the accepted-policy enumeration through the same
2384/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2385/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2386/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2387/// emitter on a per-child-policy diagnostic column — reaches the same
2388/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2389/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2390/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2391/// paired [`std::fmt::Display`], [`AsRef<str>`],
2392/// [`RestartPolicy::as_str`], and the four
2393/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2394/// forward-projection corners already return.
2395///
2396/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2397/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2398/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2399/// str` lifetime by construction (each `match` arm resolves to a
2400/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2401/// with static lifetime), so the zero-alloc borrowed arm is the
2402/// type-correct projection with no runtime allocation.
2403///
2404/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2405/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2406/// From<T> for Cow<'static, str>`), so the paired sibling
2407/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2408/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2409/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2410/// [`Cow<'static, str>`]-bound call site — every such site is forced
2411/// through a `Cow::Borrowed(policy.as_str())` /
2412/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2413/// no compile-time link back to the substrate primitive until this
2414/// lift.
2415///
2416/// Second peer to extend the substrate-wide trait-idiomatic
2417/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2418/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2419/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2420/// tier of the campaign (both sibling peers, `RestartStrategy` and
2421/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2422/// forward projection) so the remaining eleven peers
2423/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2424/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2425/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2426/// `FerriteRuntime`) are the future targets. Every future arm addition
2427/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2428/// might reach for once the three canonical OTP restart policies stop
2429/// covering the substrate's discovered load-shape) grows the
2430/// Cow<'static, str> axis by construction through one caixa-core edit
2431/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2432/// across every future Cow<'static, str>-bound consumer site.
2433///
2434/// Pinned load-bearing by
2435/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2436/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2437/// against [`RestartPolicy::as_str`] across the three-arm
2438/// [`RestartPolicy::ALL`]) and
2439/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2440/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2441/// for &'static str`], [`From<RestartPolicy> for String`], and
2442/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2443/// `.iter().copied().map(Cow::from)` pipe witness over
2444/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2445/// through the [`Cow<'static, str>`] axis alone and pins the
2446/// zero-alloc discipline on every element).
2447impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2448    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2449        std::borrow::Cow::Borrowed(policy.as_str())
2450    }
2451}
2452
2453/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2454/// output* forward projection on the M2 OTP-shape per-child-restart
2455/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2456/// companion to the paired owned-input
2457/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2458/// immediately above (0612398). Routes byte-for-byte through the same
2459/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2460/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2461/// that holds a `&RestartPolicy` and needs a
2462/// [`std::borrow::Cow<'static, str>`] — a
2463/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2464/// per-arm accept-set materializer (whose iterator over
2465/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2466/// `RestartPolicy`, so the paired owned-input
2467/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2468/// alone forces every call site through an explicit `.copied()` /
2469/// dereference / [`Copy`]-bound restatement rather than the direct
2470/// trait-idiomatic projection), a future generic
2471/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2472/// on a per-child-policy diagnostic column that walks the
2473/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2474/// webhook rejection body that composes the accepted-policy
2475/// enumeration from an iterated
2476/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2477/// per-arm `match p { … }` cascade — reaches the same three-arm
2478/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2479/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2480/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2481/// paired [`std::fmt::Display`], [`AsRef<str>`],
2482/// [`RestartPolicy::as_str`], the four
2483/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2484/// forward-projection corners, and the paired owned-input
2485/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2486/// already return.
2487///
2488/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2489/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2490/// [`RestartPolicy::as_str`] accessor's return carries the
2491/// `&'static str` lifetime by construction (each `match` arm resolves
2492/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2493/// with static lifetime), so the zero-alloc borrowed arm is the
2494/// type-correct projection with no runtime allocation.
2495///
2496/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2497/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2498/// one commit prior (0612398) on the paired owned-input
2499/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2500/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2501/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2502/// which carries both {Self, &Self} × Cow<'static, str> corners since
2503/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2504/// closed it on the top-level [`crate::CaixaKind`] one commit after
2505/// the owning half (99c1735) landed. This lift closes the whole M2
2506/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2507/// forward-projection campaign on both input-shape corners
2508/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2509/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2510/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2511/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2512/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2513/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2514/// standard library does not carry a blanket
2515/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2516/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2517/// closed-set fieldless typed enum peer on the substrate that carries
2518/// the paired owned-input [`Cow<'static, str>`] axis but not the
2519/// borrowed-input axis forces every borrowed-input
2520/// [`Cow<'static, str>`]-parameterized call site through a spurious
2521/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2522/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2523/// bounds have no compile-time link to the substrate primitive.
2524///
2525/// Pinned load-bearing by
2526/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2527/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2528/// against [`RestartPolicy::as_str`] across the three-arm
2529/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2530/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2531/// (cross-axis partition pin against the paired owned-input
2532/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2533/// paired borrowed-input owned-`&'static str`
2534/// [`From<&RestartPolicy> for &'static str`], and the paired
2535/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2536/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2537/// over [`RestartPolicy::ALL`] — whose iterator yields
2538/// `&RestartPolicy` by construction, so the borrowed-input
2539/// [`Cow<'static, str>`] axis is what routes the pipe through the
2540/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2541/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2542/// spurious [`Copy`] deref).
2543impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2544    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2545        std::borrow::Cow::Borrowed(policy.as_str())
2546    }
2547}
2548
2549/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2550/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2551/// closed-set fieldless typed enum — extends the substrate-wide
2552/// `Box<str>` forward-projection campaign tier opened one commit prior
2553/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2554/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2555/// typed enum peer on the caixa surface (`:children :restart`),
2556/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2557/// b4dc55c) closed the
2558/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2559/// corner on this enum. Routes byte-for-byte through the
2560/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2561/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2562/// so every consumer that binds a
2563/// `let key: Box<str> = policy.into();`-shaped call site — a
2564/// per-child metric-key materializer that stashes the policy
2565/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2566/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2567/// hierarchical reconciliation scheduler's per-child restart-decision
2568/// fan-out carries), a future admission-webhook rejection body whose
2569/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2570/// handle — reaches the same three-arm lifted
2571/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2572/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2573/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2574/// sibling
2575/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2576/// forward-projection corner already returns. Rust's standard library
2577/// carries `impl From<&str> for Box<str>` and
2578/// `impl From<String> for Box<str>` but no blanket
2579/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2580/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2581/// this axis is a distinct trait-idiomatic surface that a downstream
2582/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2583/// no other — without a `Box::from(policy.as_str())` open-code whose
2584/// type bounds have no compile-time link back to the substrate
2585/// primitive.
2586///
2587/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2588/// forward-projection family opened on the sibling-restart
2589/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2590/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2591/// projection campaign's owned-input corner on both M2 OTP-shape
2592/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2593/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2594/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2595/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2596/// are the future targets of the campaign.
2597///
2598/// Pinned load-bearing by
2599/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2600/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2601/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2602/// surface, plus a blanket-derived [`Into`] shape witness).
2603impl From<RestartPolicy> for Box<str> {
2604    fn from(policy: RestartPolicy) -> Box<str> {
2605        Box::<str>::from(policy.as_str())
2606    }
2607}
2608
2609/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2610/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2611/// closed-set fieldless typed enum — the borrowed-input companion to
2612/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2613/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2614/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2615/// projection axis on the second (and third-and-final) M2 OTP-shape
2616/// closed-set fieldless typed enum peer on the caixa surface
2617/// (`:children :restart`), routing byte-for-byte through the
2618/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2619/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2620/// Every consumer that holds a `&RestartPolicy` and needs a
2621/// [`Box<str>`] — a
2622/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2623/// per-arm accept-set materializer (whose iterator over
2624/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2625/// `RestartPolicy`, so the paired owned-input
2626/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2627/// call site through an explicit [`Copy`] deref or a
2628/// `.copied()` restatement rather than the direct trait-idiomatic
2629/// projection), a per-child metric-key materializer holding
2630/// `&RestartPolicy` through a `caixa-operator` hierarchical
2631/// reconciliation scheduler's borrow lifetime, a future admission-
2632/// webhook rejection body whose per-arm `Box<str>` field composes
2633/// from a borrowed `&RestartPolicy` handle — reaches the
2634/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2635/// this impl and no other, without a
2636/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2637/// have no compile-time link back to the substrate primitive.
2638///
2639/// Rust's standard library carries `impl From<&str> for Box<str>`
2640/// and `impl From<String> for Box<str>` but no blanket
2641/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2642/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2643/// set fieldless typed enum peer on the substrate that carries the
2644/// paired owned-input `Box<str>` axis but not the borrowed-input
2645/// axis forces every borrowed-input `Box<str>`-parameterized call
2646/// site through a spurious [`Copy`] deref
2647/// (`Box::<str>::from((*policy).as_str())`) or a
2648/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2649/// have no compile-time link back to the substrate primitive.
2650///
2651/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2652/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2653/// — closes the whole `{Self, &Self}` input-shape corner of the
2654/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2655/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2656/// closed the paired [`Cow<'static, str>`] axis one commit after
2657/// its owning half (0612398) landed on this enum. The remaining
2658/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2659/// core / render-side / outside-caixa-core tiers are the future
2660/// targets of the [`Box<str>`] campaign.
2661///
2662/// Pinned load-bearing by
2663/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2664/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2665/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2666/// surface, plus a blanket-derived [`Into`] shape witness, a
2667/// cross-axis partition pin against the paired owned-input
2668/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2669/// input `{&'static str, String, Cow<'static, str>}` return-shape
2670/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2671/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2672/// by construction, so the borrowed-input [`Box<str>`] axis is
2673/// what routes the pipe through the substrate-primitive
2674/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2675/// deref).
2676impl From<&RestartPolicy> for Box<str> {
2677    fn from(policy: &RestartPolicy) -> Box<str> {
2678        Box::<str>::from(policy.as_str())
2679    }
2680}
2681
2682/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2683/// forward projection on the M2 OTP-shape per-child-restart
2684/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2685/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2686/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2687/// returned `&'static str`, so every consumer that binds a
2688/// [`RestartPolicy`] through the standard-library `.into()` /
2689/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2690/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2691/// per-request `Sync` + `Send`-safe structured-log field composed
2692/// across an `.await` boundary through a
2693/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2694/// a future wasm-operator's per-child post-exit restart-decision
2695/// pipeline holding a shared-ownership per-arm cache key, a
2696/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2697/// collector recording a per-child-policy field onto the parent
2698/// span's shared-ownership context — reaches the same three-arm
2699/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2700/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2701/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2702/// sibling
2703/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2704/// forward-projection corner already returns.
2705///
2706/// Second peer on the substrate-wide trait-idiomatic
2707/// [`std::sync::Arc<str>`] forward-projection family opened one
2708/// projection tier prior (bca2ec8) on the paired sibling-restart
2709/// [`RestartStrategy`] owned-input first-mover — extends the tier
2710/// onto the second (and third-and-final) M2 OTP-shape closed-set
2711/// fieldless typed enum peer on the caixa surface
2712/// (`:children :restart`), immediately after the paired [`Box<str>`]
2713/// axis (0a1b313 / cb1d068) closed the whole
2714/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2715/// 2×4 corner on this enum. Rust's standard library carries
2716/// `impl From<&str> for std::sync::Arc<str>` and
2717/// `impl From<String> for std::sync::Arc<str>` but no blanket
2718/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2719/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2720/// axis is a distinct trait-idiomatic surface that a
2721/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2722/// reaches through this impl and no other — a paired
2723/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2724/// compile-time link back to the substrate primitive, and a two-step
2725/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2726/// through the owned-`String` axis allocates twice (once into the
2727/// intermediate `String`, once into the [`Arc<str>`] on the
2728/// `From<String>` conversion) where the single-step trait impl
2729/// allocates once.
2730///
2731/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2732/// same "extends the substrate-wide projection tier onto the next
2733/// M2 OTP-shape peer" discipline, extended onto the
2734/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2735/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2736/// owned-move return-shape cannot provide.
2737///
2738/// Pinned load-bearing by
2739/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2740/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2741/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2742/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2743/// axis byte-parity pins against the sibling owned-input
2744/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2745/// axes).
2746impl From<RestartPolicy> for std::sync::Arc<str> {
2747    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2748        std::sync::Arc::<str>::from(policy.as_str())
2749    }
2750}
2751
2752/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2753/// forward projection on the M2 OTP-shape per-child-restart
2754/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2755/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2756/// forward-projection axis on the second (and third-and-final) M2
2757/// OTP-shape closed-set fieldless typed enum peer on the caixa
2758/// surface (`:children :restart`), companion to the paired
2759/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2760/// one commit prior (b05724e). Routes byte-for-byte through the
2761/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2762/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2763/// `&'static str`), so every consumer that binds a
2764/// [`&RestartPolicy`] through the standard-library `.into()` /
2765/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2766/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2767/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2768/// `Sync` + `Send`-safe structured-log field across an `.await`
2769/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2770/// diagnostic-column dispatch, a future wasm-operator's per-child
2771/// post-exit restart-decision pipeline whose
2772/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2773/// into the shared-ownership per-arm key without a spurious [`Copy`]
2774/// deref (which would only be reachable through the owned-input
2775/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2776/// calling `.copied()` on the iterator), a future
2777/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2778/// collector recording a borrowed-`&RestartPolicy` per-arm field
2779/// onto the parent span's shared-ownership context — reaches the
2780/// same three-arm lifted
2781/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2782/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2783/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2784/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2785/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2786/// Box<str>}` forward-projection corner already return.
2787///
2788/// Closes the substrate-wide trait-idiomatic
2789/// [`std::sync::Arc<str>`] forward-projection family opened one
2790/// commit prior (b05724e) on the paired owned-input
2791/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2792/// the `{Self, &Self}` input-shape corner of the
2793/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2794/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2795/// surface, exactly as b3e72d7 closed the paired
2796/// [`std::sync::Arc<str>`] corner on the sibling-restart
2797/// [`RestartStrategy`] first-mover one commit after its owning half
2798/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2799/// corner on this enum one commit after its owning half (0a1b313)
2800/// landed. Rust's standard library carries `impl From<&str> for
2801/// std::sync::Arc<str>` and `impl From<String> for
2802/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2803/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2804/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2805/// enum peer on the substrate that carries the paired owned-input
2806/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2807/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2808/// call site through a spurious [`Copy`] deref
2809/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2810/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2811/// type bounds have no compile-time link back to the substrate
2812/// primitive.
2813///
2814/// Pinned load-bearing by
2815/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2816/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2817/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2818/// surface, plus a blanket-derived [`Into`] shape witness, a
2819/// cross-axis pin against the paired owned-input
2820/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2821/// borrowed-input `{&'static str, String, Cow<'static, str>,
2822/// Box<str>}` return-shape axes, and a
2823/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2824/// [`RestartPolicy::ALL`]).
2825impl From<&RestartPolicy> for std::sync::Arc<str> {
2826    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2827        std::sync::Arc::<str>::from(policy.as_str())
2828    }
2829}
2830
2831/// Trait-idiomatic byte-view surface on the per-child restart-decision
2832/// policy typed enum.
2833///
2834/// Every consumer that binds its input through the standard-library
2835/// [`AsRef<[u8]>`] trait bound — a byte-keyed
2836/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
2837/// table lookup on the future wasm-operator supervisor scheduler; a
2838/// `blake3::Hasher::update` / `ring::digest::Context::update` /
2839/// `sha2::Sha256::update` byte-input surface on any future per-child
2840/// content-address digest folded into the [`crate::Lacre`] closure so
2841/// downstream cache-keys partition on the three OTP restart policies
2842/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
2843/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
2844/// reaches the substrate primitive through one trait dispatch rather
2845/// than open-coding the two-hop `restart.as_str().as_bytes()`
2846/// composition at every call site. Routed byte-for-byte through the
2847/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
2848/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
2849/// [`RestartPolicy::as_str`]) and the five reverse-projection
2850/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
2851/// `std::sync::Arc<str>`) return-shape axes already resolve through,
2852/// so any future divergence between the byte-view and str-view axes
2853/// trips at caixa-core test time rather than at a downstream byte-
2854/// consumer's silent split.
2855///
2856/// Peer of the sibling per-supervisor-restart-strategy axis
2857/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
2858/// shape supervisor slot enum to open this axis) — the sixth
2859/// closed-set fieldless typed enum on the caixa surface to converge
2860/// onto the trait-idiomatic byte-view discipline, and the second (and
2861/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
2862/// axis across the paired `:supervisor :estrategia` +
2863/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
2864/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
2865/// (fail-before-pass-after byte-parity pin against
2866/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
2867/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
2868/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
2869/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
2870/// cross-axis witness against the paired reverse-projection
2871/// `{&'static str, String, Cow<'static, str>, Box<str>,
2872/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
2873/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
2874/// byte-input function accepts a [`RestartPolicy`] directly through
2875/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
2876/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
2877/// consumer axis to reach the caixa-lacre compounding target). Any
2878/// future silent detour that routes the byte-view impl off the
2879/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
2880/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
2881/// compile-time link to the un-lifted arm-literal, a swap onto the
2882/// kebab-case [`gen_platform::Discriminant`] catalog identity that
2883/// would collide the wire axis with the dispatcher-catalog axis) trips
2884/// at caixa-core test time rather than at a downstream byte-consumer's
2885/// silent split.
2886impl AsRef<[u8]> for RestartPolicy {
2887    fn as_ref(&self) -> &[u8] {
2888        self.as_str().as_bytes()
2889    }
2890}
2891
2892/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
2893/// reverse projection on the second (and final) M2 OTP-shape closed-set
2894/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
2895/// the byte-mirror of the [`From<RestartPolicy> for String`] str-owned
2896/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
2897/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
2898/// (98b08fa) lifted on this same enum. Routes byte-for-byte through
2899/// the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2900/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
2901/// consumer that binds a [`RestartPolicy`] through the standard-
2902/// library `impl From<RestartPolicy> for Vec<u8>` axis
2903/// (equivalently `<T: Into<Vec<u8>>>`) — a future
2904/// [`std::io::Write::write_all`]-shape per-child audit-log byte-sink
2905/// whose input parameter is an owned [`Vec<u8>`] payload, a future
2906/// `bytes::Bytes::from(Vec::<u8>::from(restart))` composer folding
2907/// the per-arm restart-decision-policy byte-tag into the
2908/// [`bytes::Bytes`] framing surface, a future
2909/// `hasher.update(&Vec::<u8>::from(restart))`-shape BLAKE3 content-
2910/// address closure that needs the owned byte-tail buffered before
2911/// folding into the [`crate::Lacre`] closure body, a future per-child
2912/// protobuf/CBOR/msgpack payload composer whose framer takes an owned
2913/// [`Vec<u8>`] rather than a borrowed byte-slice — reaches the
2914/// substrate primitive through one trait dispatch rather than an
2915/// open-coded per-call-site `restart.as_str().as_bytes().to_vec()`
2916/// composition whose type bounds have no compile-time link back to
2917/// the substrate primitive.
2918///
2919/// Closes the substrate-wide trait-idiomatic byte-owned reverse-
2920/// projection axis on the M2-OTP-shape `:supervisor :estrategia` +
2921/// `:children :restart` slot pair the sibling
2922/// [`RestartStrategy`] first-mover (63e5dd0) opened one commit prior,
2923/// matching the discipline the paired [`AsRef<[u8]>`] borrowed byte-
2924/// view axis campaign already carried across the same slot pair
2925/// (cd4c4e0 → 98b08fa). Every future arm addition (an OTP-
2926/// `intrinsic` fourth arm the theory
2927/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2928/// might reach for once the three canonical OTP restart policies
2929/// stop covering the substrate's discovered load-shape) grows the
2930/// byte-owned axis through one edit on the substrate-primitive
2931/// [`RestartPolicy::as_str`] accessor.
2932///
2933/// Pinned load-bearing by
2934/// [`tests::restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
2935/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2936/// three-arm [`RestartPolicy::ALL`] emit-set binding the byte-owned
2937/// reverse-projection axis against the paired [`AsRef<[u8]>`]
2938/// borrowed byte-view axis and the str-owned reverse-projection
2939/// family (`String`, `Cow<'static, str>`, `Box<str>`,
2940/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
2941/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
2942/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
2943/// witness on both owned and borrowed input shapes).
2944impl From<RestartPolicy> for Vec<u8> {
2945    fn from(policy: RestartPolicy) -> Vec<u8> {
2946        policy.as_str().as_bytes().to_vec()
2947    }
2948}
2949
2950/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
2951/// owned reverse projection on the second (and final) M2 OTP-shape
2952/// closed-set fieldless typed enum peer on the caixa surface
2953/// ([`RestartPolicy`]) — the borrowed-input peer of
2954/// [`From<RestartPolicy> for Vec<u8>`], closing the
2955/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
2956/// axis in one lift. Routes byte-for-byte through the substrate-
2957/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor so
2958/// every consumer that holds a borrowed [`&RestartPolicy`] and needs
2959/// an owned [`Vec<u8>`] — a future
2960/// `.iter().map(Vec::<u8>::from).collect()` pipe over
2961/// `&[RestartPolicy]` (whose iterator yields `&RestartPolicy`,
2962/// not `RestartPolicy`, so the owned-input axis alone forces every
2963/// call site through an explicit `.copied()` / spurious [`Copy`]
2964/// deref restatement rather than the direct trait-idiomatic
2965/// projection), a future admission-webhook rejection body composer
2966/// that walks [`RestartPolicy::ALL`] through an `Into<Vec<u8>>`-
2967/// bound per-arm byte-writer to surface the accepted `:children
2968/// :restart` set — reaches the substrate primitive through one
2969/// trait dispatch rather than a `Vec::<u8>::from(*policy)` spurious-
2970/// [`Copy`]-deref restatement.
2971impl From<&RestartPolicy> for Vec<u8> {
2972    fn from(policy: &RestartPolicy) -> Vec<u8> {
2973        policy.as_str().as_bytes().to_vec()
2974    }
2975}
2976
2977// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2978// supervisor surface — two more typed shadows over Erlang/OTP
2979// primitives the substrate now mechanically tracks (see
2980// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2981// theory/TYPED-ABSORPTION.md for the absorption arc).
2982gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2983gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2984
2985/// One child entry in the supervisor's `:children` list.
2986///
2987/// Every child references another caixa by `:caixa <nome>` + version
2988/// constraint. The supervisor materializes one ComputeUnit per entry.
2989#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2990#[serde(rename_all = "camelCase")]
2991pub struct ChildSpec {
2992    /// The child caixa's `:nome`. Must resolve via the same dependency
2993    /// resolution path as `:deps` (caixa-resolver).
2994    pub caixa: String,
2995
2996    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2997    /// [`crate::dep::Dep::versao`].
2998    pub versao: String,
2999
3000    /// Restart policy — an author-omitted slot degrades onto the
3001    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
3002    /// (`permanent`, the Erlang/OTP worker-child default) through the
3003    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
3004    /// to.
3005    #[serde(default)]
3006    pub restart: RestartPolicy,
3007}
3008
3009impl ChildSpec {
3010    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
3011    /// accessor every consumer that reads the OTP-shape supervised
3012    /// child's identity keys off — returns the author-declared
3013    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
3014    /// from the typed slot's own [`String`] storage.
3015    ///
3016    /// The `:children :caixa` slot carries the DNS-1123 label — the
3017    /// child caixa's `:nome` — that every emitted cluster artifact
3018    /// derives its `metadata.name` from verbatim: the rendered
3019    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
3020    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
3021    /// identity, and the per-child K8s Service `metadata.name` the
3022    /// future wasm-operator (M3) provisions for inter-child supervision-
3023    /// tree wiring. Every downstream consumer that fans on the child's
3024    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
3025    /// per-child DNS-1123 gate at
3026    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
3027    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
3028    /// [`validate_no_self_supervision`] cross-slot equality check
3029    /// against the parent's `:nome`, every `SupervisorError` variant
3030    /// carrying the offending child caixa verbatim for `feira lint`
3031    /// rendering, the future wasm-operator's hierarchical reconciliation
3032    /// scheduler's per-child ComputeUnit-name projection, the future M4
3033    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3034    /// admission webhook).
3035    ///
3036    /// Prior to this lift the `.caixa` byte-string was accessed inline
3037    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
3038    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
3039    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
3040    /// carriers' `child.caixa.clone()`, the dedup key's
3041    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
3042    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
3043    /// field-accesses that expressed no compile-time link back to the
3044    /// typed slot. A future extension of the `:children :caixa` axis to
3045    /// a richer author surface (a per-cluster alias table the operator
3046    /// pins through a future `:placement`-scoped slot on the supervisor
3047    /// tree, a namespace-qualified rewrite the M4 CR materializer
3048    /// applies per-CR, a per-child overlay from the future `:children
3049    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
3050    /// acknowledges) would have had to be threaded through every
3051    /// open-coded copy in lockstep or one consumer would silently
3052    /// disagree with the peers on which caixa a given child resolves to
3053    /// — a child-set lookup that treated the name as `"cart-worker"`
3054    /// while the peer duplicate-detector treated it as
3055    /// `"tenant-a/cart-worker"` would silently split the
3056    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
3057    /// self-supervision detector's parent-equality check, a two-consumer
3058    /// split at the validator far from the source `caixa.lisp` with no
3059    /// field naming the identity-drift root cause. Lifting the resolution
3060    /// rule to a typed method on the substrate primitive means every
3061    /// downstream consumer of the Supervisor's per-`:children` identity
3062    /// surface reaches for exactly one typed dispatch — the resolver's
3063    /// accept-set migrates as a unit on any future axis addition.
3064    ///
3065    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
3066    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
3067    /// mesh-slot surface — same "one typed dispatch on the substrate
3068    /// primitive, thin projections at each consumer" discipline extended
3069    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
3070    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
3071    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
3072    /// accessor discipline for the shared substrate concept "another
3073    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
3074    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
3075    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
3076    /// slot family's typed-accessor discipline now spans both the
3077    /// upgrade axis (`:upgrade-from`) and the supervision axis
3078    /// (`:children`), matching the closed M3 mesh-slot accessor family's
3079    /// shape. Named `nome()` to match the tatara-lisp author-surface
3080    /// term the field's docstring already reaches for ("The child
3081    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
3082    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
3083    /// discipline the substrate already carries — the accessor's name
3084    /// maps directly onto the canonical caixa-identity vocabulary rather
3085    /// than shadowing the field's storage-side `caixa` label.
3086    #[must_use]
3087    pub const fn nome(&self) -> &str {
3088        self.caixa.as_str()
3089    }
3090
3091    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
3092    /// requirement scalar accessor every consumer that reads the OTP-shape
3093    /// supervised child's version pin keys off — returns the author-declared
3094    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
3095    /// the typed slot's own [`String`] storage.
3096    ///
3097    /// The `:children :versao` slot carries the Cargo-shaped semver
3098    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
3099    /// which release of the supervised child caixa the OTP-shape supervisor
3100    /// tree materializes against — the same requirement grammar the peer
3101    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
3102    /// shared [`crate::render::require_valid_versao_requirement`] cascade
3103    /// and the shared [`crate::version::parse_requirement`] parser. Every
3104    /// downstream consumer that fans on the child's version pin keys off
3105    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
3106    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
3107    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
3108    /// for `feira lint` rendering, every future per-cluster version-lock
3109    /// overlay the caixa-operator's hierarchical reconciliation scheduler
3110    /// pins through a future `:placement`-scoped supervisor-tree slot, the
3111    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3112    /// per-child version resolver, the future wasm-operator's per-child
3113    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
3114    ///
3115    /// Prior to this lift the `.versao` byte-string was accessed inline at
3116    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
3117    /// [`SupervisorSpec::validate`] requirement-gate call
3118    /// `require_valid_versao_requirement(&child.versao, …)` and the
3119    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
3120    /// `versao: child.versao.clone()` — two open-coded field-accesses that
3121    /// expressed no compile-time link back to the typed slot. A future
3122    /// extension of the `:children :versao` axis to a richer author surface
3123    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3124    /// flow, a lacre-projected concrete-version rewrite the operator
3125    /// materializes at CR-admission time, a future `:children :versao-lock`
3126    /// per-cluster override slot the wasm-operator's hierarchical
3127    /// reconciliation scheduler authors per-CR) would have had to be
3128    /// threaded through both open-coded copies in lockstep or one consumer
3129    /// would silently disagree with the peer on which release constraint a
3130    /// given child resolves to — the requirement-gate call reading
3131    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
3132    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
3133    /// the actual gate rejection input, a two-consumer split at the
3134    /// validator far from the source `caixa.lisp` with no field naming the
3135    /// version-pin drift root cause. Lifting the resolution rule to a typed
3136    /// method on the substrate primitive means every downstream
3137    /// requirement-facing consumer of the Supervisor's per-`:children`
3138    /// version-pin surface reaches for exactly one typed dispatch — the
3139    /// resolver's accept-set migrates as a unit on any future axis addition.
3140    ///
3141    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
3142    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
3143    /// surface — same "one typed dispatch on the substrate primitive, thin
3144    /// projections at each consumer" discipline extended onto the M2
3145    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
3146    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
3147    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
3148    /// one accessor discipline for the shared substrate concept "another
3149    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
3150    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
3151    /// `:nome` scalar accessor — the pair
3152    /// `(nome(), versao_requirement())` jointly projects the
3153    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
3154    /// that fans on per-child identity + version pin keys off, closing the
3155    /// last unlifted per-`:children` `String`-carry axis so every downstream
3156    /// per-`:children` reader now routes through a typed dispatch on the
3157    /// substrate primitive. Named `versao_requirement()` rather than
3158    /// `versao()` because the field's storage-side `.versao` label is
3159    /// already the author-surface term (`:versao`); the accessor's name
3160    /// carries the semantic role — the semver *requirement* string the
3161    /// shared [`crate::version::parse_requirement`] entry-point consumes —
3162    /// so a raw field access and a typed dispatch read differently at every
3163    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
3164    /// naming discipline verbatim.
3165    #[must_use]
3166    pub const fn versao_requirement(&self) -> &str {
3167        self.versao.as_str()
3168    }
3169
3170    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
3171    /// per-child post-exit restart-decision policy scalar accessor every
3172    /// consumer that dispatches on the supervised child's post-exit
3173    /// reconcile posture keys off — returns the author-declared
3174    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
3175    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
3176    /// storage.
3177    ///
3178    /// The `:children :restart` slot carries the closed-set OTP-shaped
3179    /// per-child restart-decision policy discriminator
3180    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
3181    /// worker-child default; [`RestartPolicy::Transient`] — restart only
3182    /// on abnormal exit, the OTP `transient` clean-completion-aware
3183    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
3184    /// `temporary` one-shot default) that every downstream consumer of
3185    /// the Supervisor's per-child post-exit reconcile branch keys off.
3186    /// Every future downstream consumer that fans on the per-child
3187    /// restart-decision keys off this scalar (the future `feira app
3188    /// graph` per-child restart column, the future wasm-operator's
3189    /// per-child post-exit restart-decision branch, the future M4
3190    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3191    /// admission webhook, the `caixa-operator`'s hierarchical
3192    /// reconciliation scheduler's per-child post-exit reconcile branch,
3193    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
3194    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
3195    /// pin threads through).
3196    ///
3197    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
3198    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
3199    /// scalar accessor and the M3 mesh-slot
3200    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
3201    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
3202    /// — same "one typed dispatch on the substrate primitive,
3203    /// `Copy`-projected closed-set enum-arm discriminator that partitions
3204    /// the downstream renderer's per-arm fan-out" discipline extended
3205    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
3206    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
3207    /// [`ChildSpec`] type — companion to the sibling per-`:children`
3208    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
3209    /// and the per-`:children` [`ChildSpec::versao_requirement`]
3210    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
3211    /// on the sibling `String`-carry axes. The triple
3212    /// `(nome(), versao_requirement(), restart())` jointly projects the
3213    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
3214    /// tree consumer that fans on per-child identity + version pin +
3215    /// restart-decision keys off, closing the last unlifted per-`:children`
3216    /// axis so every downstream per-`:children` reader now routes through
3217    /// a typed dispatch on the substrate primitive. Named `restart()` to
3218    /// match the storage field's name and the author-surface
3219    /// `:children :restart` slot term verbatim; the accessor's identity
3220    /// name maps onto the canonical OTP-shape per-child restart-decision-
3221    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
3222    /// carries.
3223    ///
3224    /// Declared `pub const fn` to close the last non-`const`
3225    /// `Copy`-return raw-field-getter posture on the M2
3226    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
3227    /// of the sibling M2 per-`:supervisor`
3228    /// [`SupervisorSpec::estrategia`] (converted in this commit)
3229    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
3230    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3231    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
3232    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
3233    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
3234    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
3235    /// downstream substrate-side `const`-context consumer of the
3236    /// per-`:children` restart-decision-policy scalar (a future
3237    /// module-scope `const _:() = assert!(matches!(child.restart(),
3238    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
3239    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3240    /// admission-webhook `const fn` per-child restart-decision floor
3241    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
3242    /// composer over the substrate primitive that fans on the per-child
3243    /// restart-decision policy at compile time) now reaches through the
3244    /// same typed dispatch on the substrate primitive at const-eval
3245    /// time as at runtime. A future non-`Copy`-return promotion of the
3246    /// scalar (an `Option<RestartPolicy>`-shape migration on the
3247    /// per-child restart-decision axis once heterogeneous per-cluster
3248    /// restart-policy overlays land, a per-tenant restart-policy-alias
3249    /// table the M4 CR materializer resolves per-CR) that would drop
3250    /// the `const` qualifier fails the fail-before-pass-after pin
3251    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
3252    /// build time rather than surfacing as a downstream consumer
3253    /// regression.
3254    #[must_use]
3255    pub const fn restart(&self) -> RestartPolicy {
3256        self.restart
3257    }
3258}
3259
3260/// Supervisor-typed slots that live alongside the standard Caixa
3261/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
3262/// the manifest stays a single typed form; this struct exists for
3263/// validation + conversion.
3264#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3265#[serde(rename_all = "camelCase")]
3266pub struct SupervisorSpec {
3267    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
3268    #[serde(default)]
3269    pub estrategia: RestartStrategy,
3270
3271    /// Max restarts within [`Self::restart_window`] before the
3272    /// supervisor itself terminates (and its parent supervisor decides
3273    /// what to do). Default 5.
3274    #[serde(default = "default_max_restarts")]
3275    pub max_restarts: u32,
3276
3277    /// Sliding window for `max_restarts`. Authored as a duration
3278    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
3279    /// is rejected by [`Self::validate`] — Erlang/OTP's
3280    /// `MaxIntensity / Period` invariant requires a positive window
3281    /// (a zero-period supervisor either trips on the first failure or
3282    /// never trips, depending on operator interpretation, neither of
3283    /// which is the author's intent). Omit the slot to express "no
3284    /// reset"; carry a positive duration to express the sliding window.
3285    #[serde(
3286        default,
3287        skip_serializing_if = "Option::is_none",
3288        with = "duration_codec"
3289    )]
3290    pub restart_window: Option<Duration>,
3291
3292    /// Static children. Empty for `SimpleOneForOne` (children added
3293    /// dynamically); required for the other three strategies.
3294    #[serde(default)]
3295    pub children: Vec<ChildSpec>,
3296}
3297
3298const fn default_max_restarts() -> u32 {
3299    // Route the private serde-`#[serde(default = "…")]` helper through
3300    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
3301    // `pub const` rather than the raw `5` literal — one source of truth
3302    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3303    // default across the two production consumers that currently
3304    // dispatch on it (this helper via `#[serde(default = "…")]` on
3305    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
3306    // impl at line 962). Pinned by
3307    // `default_max_restarts_helper_routes_through_lifted_default` +
3308    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
3309    // in the tests module; peer of the sibling caixa-core
3310    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
3311    // that now routes its author-omitted `:max-restarts` arm through
3312    // the same lifted constant.
3313    SUPERVISOR_MAX_RESTARTS_DEFAULT
3314}
3315
3316/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
3317/// count default for the `:supervisor :max-restarts` axis — the
3318/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
3319/// Erlang's worker-supervisor default, extracted as a typed `pub const`
3320/// so every substrate-side consumer that resolves "what
3321/// [`SupervisorSpec::max_restarts`] value does an author-omitted
3322/// `:max-restarts` slot degrade onto?" reaches for exactly one
3323/// substrate-primitive `u32`.
3324///
3325/// The `:max-restarts` default axis has two production consumers on the
3326/// substrate side today (both prior to this lift folded onto raw `5`
3327/// literals with no compile-time link back to a shared truth): the
3328/// serde-`#[serde(default = "default_max_restarts")]` helper on
3329/// [`SupervisorSpec::max_restarts`] that every author-omitted
3330/// `:supervisor :max-restarts` slot lands in past the derive-macro's
3331/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
3332/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
3333/// the composed [`SupervisorSpec`] altitude reaches through
3334/// (`feira app graph`, the future wasm-operator's per-supervisor
3335/// restart-intensity counter, the future M4
3336/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3337/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3338/// A pair of open-coded `5`s across two files that expressed no
3339/// compile-time link back to the shared OTP-canonical default — a
3340/// future rebrand of the default (a tightening to Elixir's
3341/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3342/// the operator pins through a future
3343/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3344/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3345/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3346/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3347/// per-child-cohort roadmap lands) would have had to be threaded
3348/// through both open-coded copies in lockstep or the wire-format
3349/// author-omitted arm and the view-construction author-omitted arm
3350/// would silently disagree on which restart-budget an omitted
3351/// `:max-restarts` resolves to (an author writing `:supervisor
3352/// (:max-restarts ())` would round-trip through serde with the new
3353/// default while `supervisor_view` silently continued to compose the
3354/// stale `5`, or vice versa), a two-consumer split at the composition
3355/// boundary far from the source `caixa.lisp` with no field naming the
3356/// default-drift root cause. Lifting the resolution rule to a typed
3357/// `pub const` on the substrate primitive means every downstream
3358/// consumer of the per-Supervisor default-restart-budget-count surface
3359/// reaches for exactly one substrate-primitive `u32` — the resolver's
3360/// accepted value migrates as a unit on any future axis change.
3361///
3362/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3363/// worker-supervisor default (the closest canonical OTP-shape
3364/// production reference the substrate carries, matching the sibling
3365/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3366/// this constant with on the paired sliding-window axis). Two orders of
3367/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3368/// (the upper bracket on the same axis, sibling of this lower default;
3369/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3370/// axis and now share one accessor discipline on the substrate) and
3371/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3372/// restart floor — the "one restart, then escalate" default is
3373/// deliberately loose enough to absorb a short burst of transient
3374/// child failures without escalating past the supervisor's parent
3375/// while remaining tight enough to trip the `MaxIntensity / Period`
3376/// ratio's escalation on a genuinely-stuck child within the sibling
3377/// `60s` sliding window.
3378///
3379/// Lifted as a typed `pub const` so the bound has exactly one source
3380/// of truth — the serde-side wire-format author-omitted arm at
3381/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3382/// struct-literal default field, and the caixa-core
3383/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3384/// arm all read from one place. Same shape every other typed default
3385/// in this crate carries (the sibling
3386/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3387/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3388/// sibling `:restart-window` axis, and the peer
3389/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3390/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3391/// axes).
3392pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3393
3394/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3395/// validated [`SupervisorSpec::max_restarts`] past
3396/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3397///
3398/// The typed field is `u32` (the zero-floor arm
3399/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3400/// so a programmatic struct literal
3401/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3402/// author-surface form (`:max-restarts 4294967295` or any
3403/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3404/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3405/// runtime substrate consuming the value (Erlang/OTP's
3406/// `MaxIntensity / Period` ratio, the future wasm-operator's
3407/// per-supervisor restart-intensity counter, the M4
3408/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3409/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3410/// escalation threshold is structurally so high that no realistic
3411/// restarts-per-`:restart-window` traffic shape can reach it, the
3412/// supervisor never escalates to its parent, and a bad child can loop
3413/// inside the window indefinitely with the parent supervisor structurally
3414/// never receiving the "this subtree has exceeded its restart budget"
3415/// signal the typed slot is meant to express — the canonical
3416/// "supervisor intensity declared, no escalation" footgun, exactly the
3417/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3418/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3419/// "trip the next-higher protection layer after N events in a rolling
3420/// window" counters with identical degenerate-at-the-high-end shape).
3421///
3422/// The `1000` ceiling matches the sibling
3423/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3424/// peer — same "events-per-window trip threshold" semantics, same `u32`
3425/// type, same no-op-at-the-high-end failure mode) so the M4
3426/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3427/// and the future wasm-operator's per-supervisor restart-intensity
3428/// counter reach for either field knowing the value is in `1..=1000`
3429/// without re-validating at the reconciler layer. The cap sits two
3430/// orders of magnitude above every documented Erlang/OTP production
3431/// playbook recommendation (Learn You Some Erlang's
3432/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3433/// `max_restarts: 3` default, OTP's `supervisor` callback module
3434/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3435/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3436/// default) and below the clearly-pathological "effectively no
3437/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3438/// author can plausibly want at hyperscale (a long-running supervisor
3439/// over a very-flaky pool tolerating thousands of transient restarts
3440/// before escalating), but a hard wall above which the typed policy is
3441/// structurally a no-op carried verbatim on every emitted child-restart
3442/// reconciliation contract.
3443///
3444/// Lifted as a typed `pub const` so the bound has exactly one source of
3445/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3446/// materializer's admission webhook and the wasm-operator-side
3447/// per-supervisor restart-intensity reconciler read from one place. Same
3448/// shape every other typed upper bound in this crate carries
3449/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3450/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3451/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3452/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3453/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3454/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3455pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3456
3457/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3458/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3459/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3460/// (inclusive on both ends, integer-millisecond magnitudes by the
3461/// canonical-form gate immediately preceding).
3462///
3463/// The typed field is `Option<Duration>` (the zero-floor arm
3464/// [`SupervisorError::RestartWindowZero`] already rejects
3465/// `Some(Duration::ZERO)`, and the canonical-form arm
3466/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3467/// sub-millisecond residue), so a programmatic struct literal
3468/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3469/// .. }` — 24h) and the equivalent author-surface form
3470/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3471/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3472/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3473/// A `:restart-window` value far above the documented Erlang/OTP
3474/// `MaxIntensity / Period` production-playbook band (Learn You Some
3475/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3476/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3477/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3478/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3479/// degenerates the supervisor's restart-intensity counter into a
3480/// lifetime counter: the rolling failure-counting window is structurally
3481/// so long that transient restarts are never forgotten, so the
3482/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3483/// supervisor when the child has exceeded its restart budget *within
3484/// the recent window*" to "trip the parent when the child has exceeded
3485/// its restart budget *over its lifetime*" — every transient restart
3486/// counts against the budget forever, the supervisor's reset semantic
3487/// never reaches the child, and the typed `:restart-window` slot
3488/// becomes a no-op rolling window carried on every emitted hierarchical
3489/// reconciliation contract. The canonical
3490/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3491/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3492/// `:politicas :circuit-breaker :window` axis with identical shape (both
3493/// are "rolling failure-counting window with a per-`Period` reset" Duration
3494/// axes whose lifetime-counter degenerate at the high end is the same
3495/// "the reset semantic never fires" CSE invariant violation).
3496///
3497/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3498/// the shared duration codec emits (`"<n>h"` for any integer-hour
3499/// magnitude) — every value in the canonical authoring form's
3500/// `<integer><unit>` grammar at or below this cap renders to a clean
3501/// canonical string — and matches the three sibling typed-`Duration`
3502/// caps already lifted to this surface
3503/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3504/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3505/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3506/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3507/// per-supervisor `:supervisor :restart-window` — now share a single
3508/// uniform top edge at the codec's largest emitted unit so the next
3509/// typed-slot wiring (the future wasm-operator's per-supervisor
3510/// `MaxIntensity / Period` reconciler, the M4
3511/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3512/// webhook, the `caixa-operator`'s hierarchical reconciliation
3513/// scheduler) reaches for any of the four knowing the value is in
3514/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3515/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3516/// Riak Core / RabbitMQ production-playbook recommendation band
3517/// (`5s..=300s`) and below the clearly-pathological "rolling window
3518/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3519/// a value the author can plausibly want for a very-low-traffic
3520/// long-tail failure-restart window over a hyperscale-flaky child pool,
3521/// but a hard wall above which the rolling-window contract is
3522/// structurally a lifetime-counter contract.
3523///
3524/// Lifted as a typed `pub const` so the bound has exactly one source
3525/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3526/// materializer's admission webhook, the wasm-operator-side
3527/// per-supervisor `MaxIntensity / Period` reconciler, and the
3528/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3529/// from one place. Same shape every other typed upper bound in this
3530/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3531/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3532/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3533/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3534/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3535/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3536/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3537/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3538/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3539pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3540
3541/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3542/// default for the `:supervisor :restart-window` axis — the canonical
3543/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3544/// worker-supervisor default, extracted as a typed `pub const` so every
3545/// substrate-side consumer that resolves "what
3546/// [`SupervisorSpec::restart_window`] value does an author-omitted
3547/// `:restart-window` slot degrade onto?" reaches for exactly one
3548/// substrate-primitive [`Duration`].
3549///
3550/// The `:restart-window` default axis has one production consumer on the
3551/// substrate side today: the [`Default for SupervisorSpec`] impl's
3552/// struct-literal `restart_window` field, which prior to this lift folded
3553/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3554/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3555/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3556/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3557/// *not* fall back to this default on the sibling `:restart-window` axis
3558/// — an author-omitted `:supervisor :restart-window` composes to
3559/// `restart_window: None` (the shared codec's soft-swallow shape),
3560/// keeping author-declared intent ("no reset — never escalate on rolling
3561/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3562/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3563/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3564/// default was split across two files with no compile-time link between
3565/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3566/// `MaxIntensity` half at the substrate primitive while the `Period`
3567/// half rode as an open-coded literal at the composition site, so a
3568/// future coherent rebrand of the paired canonical (a tightening to
3569/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3570/// per-cluster overlay the operator pins through a future
3571/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3572/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3573/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3574/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3575/// roadmap lands) would have had to migrate the `MaxIntensity` half
3576/// through the lifted constant and the `Period` half through a raw
3577/// literal in lockstep or the two halves of the same OTP-canonical
3578/// default would silently drift out of pairing. Lifting the resolution
3579/// rule to a typed `pub const` on the substrate primitive means the
3580/// paired OTP-canonical default migrates as one unit on any future
3581/// axis change.
3582///
3583/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3584/// worker-supervisor default (the closest canonical OTP-shape
3585/// production reference the substrate carries, matching the paired
3586/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3587/// constant is the `Period` denominator of on the same
3588/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3589/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3590/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3591/// this lower default; both are typed [`Duration`] const bounds on the
3592/// `:supervisor :restart-window` axis and now share one accessor
3593/// discipline on the substrate) and above the OTP-`supervisor`
3594/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3595/// rolling window" default is deliberately loose enough to absorb a
3596/// short burst of transient child failures without escalating past the
3597/// supervisor's parent while remaining tight enough for the paired
3598/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3599/// stuck child within a human-scale observation window.
3600///
3601/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3602/// exactly one source of truth on each half — the sibling
3603/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3604/// `Period` `60s` half now share the same substrate-primitive lift
3605/// discipline. Same shape every other typed default in this crate
3606/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3607/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3608/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3609/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3610/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3611/// caixa-flux / caixa-helm rendering axes).
3612pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3613
3614/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3615/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3616/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3617/// worker-supervisor default, extracted as a typed `pub const` so every
3618/// substrate-side consumer that resolves "what
3619/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3620/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3621/// primitive [`RestartStrategy`].
3622///
3623/// The `:estrategia` default axis has three production consumers on the
3624/// substrate side today: the [`Default for RestartStrategy`] impl's
3625/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3626/// `estrategia` field, and the
3627/// [`crate::manifest::Caixa::supervisor_view`] fold's
3628/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3629/// collapse arm — three entry points onto the same OTP-canonical
3630/// `one_for_one` value that prior to this lift folded onto a raw
3631/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3632/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3633/// with no compile-time link back to the paired
3634/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3635/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3636/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3637/// triple was split across three altitudes with no compile-time link
3638/// between the halves: the `MaxIntensity` half rode through the lifted
3639/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3640/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3641/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3642/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3643/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3644/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3645/// intensity/period; an OTP `rest_for_one` widening once the substrate
3646/// discovers startup-order-coupled child cohorts as the more common
3647/// worker-supervisor default; a per-cluster overlay the operator pins
3648/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3649/// §III.2 supervision-canary roadmap acknowledges) would have had to
3650/// migrate the `MaxIntensity` + `Period` halves through the lifted
3651/// constants and the `one_for_one` half through an open-coded arm in
3652/// lockstep or the three halves of the same OTP-canonical default would
3653/// silently drift out of pairing. Lifting the resolution rule to a typed
3654/// `pub const` on the substrate primitive means the paired OTP-canonical
3655/// worker-supervisor default migrates as one unit on any future axis
3656/// change.
3657///
3658/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3659/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3660/// closest canonical OTP-shape production reference the substrate
3661/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3662/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3663/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3664/// failed child, leaving siblings untouched — is the default for tree-of-
3665/// independent-workers use cases the substrate's [`RestartStrategy`]
3666/// discriminator's own docstring already carries as the default arm; it
3667/// composes with the `{5, 60}` restart-intensity ratio to name the same
3668/// substrate-canonical "canonical worker-supervisor" shape the paired
3669/// halves close on their respective axes.
3670///
3671/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3672/// exactly one source of truth on each of its three halves — the sibling
3673/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3674/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3675/// this `one_for_one` strategy half now share the same substrate-
3676/// primitive lift discipline. Same shape every other typed default in
3677/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3678/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3679/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3680/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3681/// upper caps on the paired sibling axes, and the peer
3682/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3683/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3684pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3685
3686/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3687/// default for the `:children :restart` axis — the OTP `permanent`
3688/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3689/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3690/// `pub const` so every substrate-side consumer that resolves "what
3691/// [`ChildSpec::restart`] variant does an author-omitted `:children
3692/// :restart` slot degrade onto?" reaches for exactly one substrate-
3693/// primitive [`RestartPolicy`].
3694///
3695/// Completes the OTP-shape supervisor-tree default set at the substrate
3696/// primitive. The per-`:supervisor` axis already carries all three of its
3697/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3698/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3699/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3700/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3701/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3702/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3703/// the M2 `:supervisor` slot family. The split mattered because the two
3704/// axes resolve *together* on every author-omitted supervisor: a
3705/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3706/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3707/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3708/// `permanent` through an open-coded enum arm, so a future coherent
3709/// rebrand of the OTP-shape default set (an Elixir-shaped
3710/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3711/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3712/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3713/// once the substrate discovers clean-completion-aware children as the
3714/// more common child shape) would have had to migrate three halves
3715/// through typed constants and the fourth through a raw enum arm in
3716/// lockstep or the supervisor-level and child-level defaults would
3717/// silently drift apart.
3718///
3719/// The `:children :restart` default axis has two production consumers on
3720/// the substrate side today: the [`Default for RestartPolicy`] impl's
3721/// return arm, and the serde-side `#[serde(default)]` on
3722/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3723/// :restart` slot through that same impl. Both now key off this one
3724/// substrate primitive, so the future wasm-operator's per-child post-exit
3725/// restart-decision branch, the future M4
3726/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3727/// admission webhook, and the `caixa-operator`'s hierarchical
3728/// reconciliation scheduler's per-child fan-out all reach for one typed
3729/// identifier when they resolve an omitted per-child restart posture.
3730///
3731/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3732/// worker-child restart type — always restart the child regardless of how
3733/// it died, the canonical posture for long-running services that must
3734/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3735/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3736/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3737/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3738/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3739/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3740/// one-shot / clean-completion-aware postures an author declares
3741/// explicitly, never a posture an omitted slot should silently assume.
3742pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3743
3744/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3745/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3746/// `pub const fn` constructor rather than a struct-literal cascade over
3747/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3748/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3749/// lifted consts — one source of truth for the Erlang/OTP-canonical
3750/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3751/// paths every downstream consumer already reaches through (the
3752/// hand-authored-until-now [`Default::default`] the
3753/// `..SupervisorSpec::default()` struct-update-syntax on every
3754/// one-axis-under-test fixture in this crate's test module rests on,
3755/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3756/// every `const`-context consumer reaches through).
3757///
3758/// Extends the [`Default`]-through-const-ctor fold discipline the
3759/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3760/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3761/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3762/// and [`crate::BehaviorSpec`]
3763/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3764/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3765/// typed-slot spec family — extended here onto the M2 supervisor-slot
3766/// [`SupervisorSpec`] whose canonical baseline is not "everything
3767/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3768/// supervisor triple. The `empty()` peer's naming did not fit
3769/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3770/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3771/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3772/// the sibling `Option`-only slots fold to), so this peer is named
3773/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3774/// existing per-arm pin tests
3775/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3776/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3777/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3778/// already reach for. Pinned load-bearing by
3779/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3780/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3781/// [`PartialEq`], sharpening the sibling
3782/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3783/// pins from a per-field lift into a whole-struct one-source-of-truth
3784/// pin — the derived-until-now [`Default::default`] and the
3785/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3786/// construction, not by coincidence).
3787impl Default for SupervisorSpec {
3788    #[inline]
3789    fn default() -> Self {
3790        Self::otp_canonical()
3791    }
3792}
3793
3794impl SupervisorSpec {
3795    /// `const`-context peer of the [`Default for SupervisorSpec`]
3796    /// impl (which routes through this constructor) — returns the
3797    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3798    /// baseline this crate reaches for in every fixture-builder
3799    /// `..SupervisorSpec::default()` struct-update expression and
3800    /// every downstream `SupervisorSpec::default()` seed.
3801    ///
3802    /// Each field routes through the same substrate-canonical
3803    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3804    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3805    /// per-arm pin tests
3806    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3807    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3808    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3809    /// already assert, so a future coherent rebrand of the OTP-canonical
3810    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3811    /// cluster overlay via a future `:restart-window-overrides` slot, a
3812    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3813    /// absorption roadmap acknowledges) migrates through three typed
3814    /// constants in lockstep, and the paired [`Default`] impl inherits
3815    /// every future extension by construction.
3816    ///
3817    /// `pub const fn` rather than the derived-style `Default::default`
3818    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3819    /// [`Default::default`] is not `const` on stable Rust, and
3820    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3821    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3822    /// discipline lets `const`-context callers construct the OTP-
3823    /// canonical baseline at compile time without runtime dispatch on
3824    /// the derived [`Default::default`], the same posture the sibling
3825    /// [`crate::LimitsSpec::empty`] (9739971) /
3826    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3827    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3828    /// spec `pub const fn` constructors carry on the sibling
3829    /// "everything `None`" baseline axis.
3830    ///
3831    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3832    /// of the derived-style [`Default`]" family — sibling of the
3833    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3834    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3835    /// baseline" trio, extended here onto the M2 supervisor-slot
3836    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3837    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3838    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3839    /// than `empty()` to name the actual invariant the return value
3840    /// pins — the same phrasing already used in the per-arm pin tests
3841    /// on this file. Pinned load-bearing by
3842    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3843    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3844    #[must_use]
3845    pub const fn otp_canonical() -> Self {
3846        Self {
3847            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3848            max_restarts: default_max_restarts(),
3849            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3850            children: Vec::new(),
3851        }
3852    }
3853
3854    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3855    /// sibling-restart-strategy scalar accessor every consumer that
3856    /// dispatches on the supervisor's per-sibling restart-decision shape
3857    /// keys off — returns the author-declared `:supervisor :estrategia`
3858    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3859    /// the typed slot's own [`RestartStrategy`] storage.
3860    ///
3861    /// The `:supervisor :estrategia` slot carries the closed-set
3862    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3863    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3864    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3865    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3866    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3867    /// every child started after it, the Erlang/OTP `rest_for_one`
3868    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3869    /// dynamic children of the same shape, the Erlang/OTP
3870    /// `simple_one_for_one` per-session default) that every downstream
3871    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3872    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3873    /// paired coherently with the sibling `:children` axis
3874    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3875    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3876    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3877    /// downstream consumer that reads the strategy keys off this scalar
3878    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3879    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3880    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3881    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3882    /// strategy print line, the future wasm-operator's per-supervisor
3883    /// sibling-restart-strategy branch, the future M4
3884    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3885    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3886    /// reconciliation scheduler's per-strategy fan-out).
3887    ///
3888    /// Prior to this lift the `.estrategia` field was accessed inline at
3889    /// two production sites in `caixa-core/src/supervisor.rs` — the
3890    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3891    /// `match self.estrategia { … }` partition dispatch, and the
3892    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3893    /// carrier at `estrategia: self.estrategia` — two open-coded
3894    /// field-accesses that expressed no compile-time link back to the
3895    /// typed slot. A future extension of the `:supervisor :estrategia`
3896    /// axis to a richer author surface (a per-cluster strategy override
3897    /// the operator pins through a future `:supervisor :estrategia-overrides`
3898    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3899    /// acknowledges, a per-tenant strategy-alias table the M4 CR
3900    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3901    /// derivation the future adaptive-supervision engine computes from
3902    /// child-failure-history topology, a per-child-cohort strategy split
3903    /// the future `RestForCohort` extension acknowledged by the
3904    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3905    /// would have had to be threaded through every open-coded copy in
3906    /// lockstep — one consumer reading the raw variant while a peer read
3907    /// the operator-resolved variant would silently split the
3908    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3909    /// the actual partition-dispatch input the empty-children refusal
3910    /// arm reached under, a two-consumer split at the validator far from
3911    /// the source `caixa.lisp` with no field naming the strategy-drift
3912    /// root cause. Lifting the resolution rule to a typed method on the
3913    /// substrate primitive means every downstream consumer of the
3914    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3915    /// reaches for exactly one typed dispatch — the resolver's accept-set
3916    /// migrates as a unit on any future axis addition.
3917    ///
3918    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3919    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3920    /// per-`:placement` distribution-strategy axis — same "one typed
3921    /// dispatch on the substrate primitive, thin projections at each
3922    /// consumer" discipline extended onto the M2 supervisor-slot
3923    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3924    /// scalar axis. The two typed axes (`Placement::estrategia` on the
3925    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3926    /// Supervisor side) now share one accessor discipline for the shared
3927    /// substrate concept "a `Copy`-projected closed-set enum-arm
3928    /// discriminator that partitions the downstream renderer's per-arm
3929    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3930    /// `SupervisorSpec` type — companion to the sibling per-`:children`
3931    /// [`crate::ChildSpec::nome`] (57c61d0) /
3932    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3933    /// scalar accessors on the sibling per-`:children` `String`-carry
3934    /// axes. Named `estrategia()` to match the storage field's name and
3935    /// the peer [`crate::Placement::estrategia`] method-name discipline
3936    /// verbatim; the accessor's identity name maps onto the canonical
3937    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3938    /// docstring already carries.
3939    ///
3940    /// Declared `pub const fn` to close the M2 supervisor-slot
3941    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3942    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3943    /// (converted in this commit) `Copy`-composite-enum accessor, peer
3944    /// of the sibling M2 per-`:supervisor`
3945    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3946    /// already lifted, and mirror of the peer M3 mesh-slot
3947    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3948    /// `Copy`-return `pub const fn` scalar accessor whose method-name
3949    /// discipline this accessor was authored to match. Every downstream
3950    /// substrate-side `const`-context consumer of the per-`:supervisor`
3951    /// sibling-restart-strategy scalar (a future module-scope `const
3952    /// _:() = assert!(matches!(sup.estrategia(),
3953    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3954    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3955    /// admission-webhook `const fn` per-supervisor strategy-arm floor
3956    /// over a typed [`SupervisorSpec`], any future `const fn`
3957    /// supervisor-tree composer over the substrate primitive that fans
3958    /// on the sibling-restart-strategy at compile time) now reaches
3959    /// through the same typed dispatch on the substrate primitive at
3960    /// const-eval time as at runtime. A future non-`Copy`-return
3961    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3962    /// migration once the substrate grows per-cluster strategy overlays
3963    /// the [`SupervisorSpec`] docstring already anticipates, a
3964    /// per-tenant strategy-alias table the M4 CR materializer resolves
3965    /// per-CR) that would drop the `const` qualifier fails the
3966    /// fail-before-pass-after pin
3967    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3968    /// caixa-core build time rather than surfacing as a downstream
3969    /// consumer regression.
3970    #[must_use]
3971    pub const fn estrategia(&self) -> RestartStrategy {
3972        self.estrategia
3973    }
3974
3975    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3976    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3977    /// reads the supervisor's per-`:restart-window` restart-budget count
3978    /// keys off — returns the author-declared `:supervisor :max-restarts`
3979    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3980    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3981    /// borrow of `&self` past the call). Non-optional (the `u32` field
3982    /// carries the restart-budget count as a required axis with a
3983    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3984    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3985    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3986    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3987    ///
3988    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3989    /// `MaxIntensity` restart-budget count that pairs with the sibling
3990    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3991    /// restart-intensity ratio the supervisor trips its own escalation on
3992    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3993    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3994    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3995    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3996    /// upper-cap bracket at
3997    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3998    /// wasm-operator's per-supervisor restart-intensity counter's
3999    /// budget-vs-count comparator, the future M4
4000    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4001    /// webhook, the `caixa-operator`'s hierarchical reconciliation
4002    /// scheduler's per-supervisor escalation-decision branch, every
4003    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
4004    /// offending count verbatim for `feira lint` rendering).
4005    ///
4006    /// Prior to this lift the `.max_restarts` field was accessed inline at
4007    /// one production site in `caixa-core/src/supervisor.rs` — the
4008    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
4009    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
4010    /// that expressed no compile-time link back to the typed slot. A
4011    /// future extension of the `:max-restarts` axis to a richer author
4012    /// surface (a per-cluster restart-budget override the operator pins
4013    /// through a future `:supervisor :max-restarts-overrides` slot the
4014    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
4015    /// a per-tenant restart-budget-alias table the M4 CR materializer
4016    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
4017    /// the future adaptive-supervision engine computes from child-failure-
4018    /// history topology, a promotion of the plain `u32` count to a richer
4019    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
4020    /// budget-partition slot comes into scope) would have had to be
4021    /// threaded through every open-coded copy in lockstep or the validate
4022    /// gate and the future M4 emit path would silently disagree on which
4023    /// restart-budget count a given supervisor resolves to — an author's
4024    /// `:max-restarts 5` would satisfy validate while the emit path
4025    /// silently read a drifted other value (a `:max-restarts 10000`
4026    /// no-op supervisor at the emit boundary would carry the author's
4027    /// declared `5` verbatim in `feira lint` output while the future
4028    /// wasm-operator's restart-intensity counter operated under the
4029    /// drifted count), a two-consumer split at the validator far from the
4030    /// source `caixa.lisp` with no field naming the restart-budget-drift
4031    /// root cause. Lifting the resolution rule to a typed method on the
4032    /// substrate primitive means every downstream consumer of the
4033    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
4034    /// for exactly one typed dispatch — the resolver's accept-set migrates
4035    /// as a unit on any future axis addition.
4036    ///
4037    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
4038    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
4039    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
4040    /// outlier-detection trip-threshold axis — same "one typed dispatch on
4041    /// the substrate primitive, thin projections at each consumer"
4042    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
4043    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
4044    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
4045    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
4046    /// one accessor discipline for the shared substrate concept "a
4047    /// `Copy`-projected required `u32` count that trips the next-higher
4048    /// protection layer after N events in a rolling window" — both are
4049    /// counters with identical degenerate-at-the-high-end shape and share
4050    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
4051    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
4052    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
4053    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
4054    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
4055    /// the storage field's name verbatim and the peer
4056    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
4057    /// accessor's identity maps onto the canonical OTP-shape supervision
4058    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
4059    /// already carries.
4060    #[must_use]
4061    pub const fn max_restarts(&self) -> u32 {
4062        self.max_restarts
4063    }
4064
4065    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
4066    /// `Period` sliding-window scalar accessor every consumer of the
4067    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
4068    /// keys off — returns the author-declared `:supervisor :restart-window`
4069    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
4070    /// the typed slot's own `Option<Duration>` storage (`Duration` is
4071    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
4072    /// value; no borrow of `&self` past the call). `None` when the slot is
4073    /// absent (the canonical "never reset — every restart across the
4074    /// supervisor's lifetime counts against the sibling `:max-restarts`
4075    /// budget" sentinel the field's own docstring names and the peer
4076    /// `validate_accepts_none_restart_window` pin locks in on the
4077    /// [`SupervisorSpec::validate`] entry-side).
4078    ///
4079    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
4080    /// `Period` sliding-observation-interval that pairs with the sibling
4081    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
4082    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
4083    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
4084    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
4085    /// default). The typed slot's `Option<Duration>` accept-set —
4086    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
4087    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
4088    /// `Period > 0`; a zero period either trips on the first failure or
4089    /// never trips depending on operator interpretation, neither of which
4090    /// is the author's intent — omit the slot to express "no reset";
4091    /// carry a positive duration to express the sliding window),
4092    /// integer-millisecond canonical form enforced through
4093    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
4094    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
4095    /// future wasm-operator's per-supervisor restart-intensity counter
4096    /// quantizes at milliseconds), upper-bounded by
4097    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
4098    /// supervisor rolling window any operationally-reachable supervisor
4099    /// can honor without spanning multiple scheduler epochs the
4100    /// hierarchical-reconciliation scheduler treats as independent) —
4101    /// maps onto the future wasm-operator (M3) per-supervisor
4102    /// restart-intensity counter's rolling-observation-interval, the
4103    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4104    /// per-`spec.restartWindow` admission webhook, and the sibling
4105    /// `duration_codec`-serialized wire scalar every downstream consumer
4106    /// of the supervisor's per-`:supervisor` restart-intensity denominator
4107    /// keys off.
4108    ///
4109    /// Prior to this lift the `.restart_window` field was accessed inline
4110    /// at one production site in `caixa-core/src/supervisor.rs` — the
4111    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
4112    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
4113    /// open-coded field-access that expressed no compile-time link back to
4114    /// the typed slot. A future extension of the `:restart-window` axis to
4115    /// a richer author surface (a per-cluster restart-window override the
4116    /// operator pins through a future `:supervisor :restart-window-overrides`
4117    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4118    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
4119    /// materializer resolves per-CR, a per-supervisor dynamic
4120    /// restart-window derivation the future adaptive-supervision engine
4121    /// computes from child-failure-history topology, a promotion of the
4122    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
4123    /// pair once Erlang/OTP's per-child-cohort observation-interval-
4124    /// partition slot comes into scope) would have had to be threaded
4125    /// through every open-coded copy in lockstep or the validate gate and
4126    /// the future M4 emit path would silently disagree on which
4127    /// restart-window a given supervisor resolves to — an author's
4128    /// `:restart-window "60s"` would satisfy validate while the emit path
4129    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
4130    /// authored slot at the emit boundary would carry the author's
4131    /// declared window verbatim in `feira lint` output while the future
4132    /// wasm-operator's restart-intensity counter operated under a
4133    /// drifted window, or vice versa: an author's `:restart-window ()`
4134    /// would carry the "never reset" sentinel through validate while the
4135    /// emit path silently substituted a default sliding window), a
4136    /// two-consumer split at the validator far from the source
4137    /// `caixa.lisp` with no field naming the restart-window-drift root
4138    /// cause. Lifting the resolution rule to a typed method on the
4139    /// substrate primitive means every downstream consumer of the
4140    /// Supervisor's per-`:supervisor` restart-intensity-denominator
4141    /// surface reaches for exactly one typed dispatch — the resolver's
4142    /// accept-set migrates as a unit on any future axis addition.
4143    ///
4144    /// Third `Copy`-return accessor on the M2 supervisor-slot
4145    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
4146    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
4147    /// payload rather than a `Copy`-scalar, and the per-`:children`
4148    /// [`crate::ChildSpec::nome`] (57c61d0) /
4149    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4150    /// scalar accessors already close the per-element `String`-carry
4151    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
4152    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
4153    /// per-outermost-call wall-clock-deadline axis and the peer M3
4154    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
4155    /// accessor on the `:politicas` slot's per-call-deadline axis — all
4156    /// three share the shared substrate concept "a `Copy`-projected
4157    /// optional `Duration` that carries a positive integer-millisecond
4158    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
4159    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
4160    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
4161    /// bracket-helper the three axes each route through. Named
4162    /// `restart_window()` to match the storage field's name verbatim and
4163    /// the peer [`crate::LimitsSpec::wall_clock`] /
4164    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
4165    /// accessor's identity maps onto the canonical OTP-shape supervision
4166    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
4167    /// already carries.
4168    #[must_use]
4169    pub const fn restart_window(&self) -> Option<Duration> {
4170        self.restart_window
4171    }
4172
4173    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
4174    /// static-child-list slice accessor every consumer that walks the
4175    /// supervisor's declared child set keys off — returns the author-
4176    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
4177    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
4178    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
4179    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4180    /// through). Non-optional: an empty slice is the load-bearing
4181    /// "author declared `:children ()`" sentinel every consumer of the
4182    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
4183    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
4184    /// three strategies require a non-empty slice — the paired
4185    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
4186    /// [`SupervisorError::NoChildren`] refusal cascade pins the
4187    /// partition on both arms).
4188    ///
4189    /// The `:supervisor :children` slot carries the OTP-shaped static
4190    /// child list the supervisor materializes one ComputeUnit per
4191    /// entry from — the Erlang/OTP `supervisor:init/1`'s
4192    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
4193    /// through the tatara-lisp `:children` author surface onto a typed
4194    /// `Vec<ChildSpec>` whose per-element `(nome(),
4195    /// versao_requirement(), restart)` triple the per-child
4196    /// [`SupervisorSpec::validate`] loop already gates through the
4197    /// lifted [`ChildSpec::nome`] (57c61d0) /
4198    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
4199    /// Every downstream consumer that fans on the static child list
4200    /// keys off this slice (the [`SupervisorSpec::validate`]
4201    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
4202    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
4203    /// per-child DNS-1123 / semver-requirement / duplicate-detection
4204    /// fan-out loop, every future wasm-operator (M3) per-supervisor
4205    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
4206    /// materialization loop, the future M4
4207    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4208    /// admission-webhook fan-out, the future `feira app graph`
4209    /// per-supervisor tree-print traversal).
4210    ///
4211    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
4212    /// inline at three production sites in `caixa-core/src/supervisor.rs`
4213    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
4214    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
4215    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
4216    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
4217    /// validate loop's `for child in &self.children` traversal head —
4218    /// three open-coded field-accesses that expressed no compile-time
4219    /// link back to the typed slot. A future extension of the
4220    /// `:supervisor :children` axis to a richer author surface (a
4221    /// per-cluster child-set overlay the operator pins through a future
4222    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
4223    /// supervision-canary roadmap acknowledges, a per-tenant
4224    /// child-set-alias table the M4 CR materializer resolves per-CR,
4225    /// a per-supervisor dynamic-child derivation the future adaptive-
4226    /// supervision engine computes from child-failure-history topology,
4227    /// a promotion of the plain `Vec<ChildSpec>` to a richer
4228    /// `{static, dynamic}` partition once Erlang/OTP's
4229    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
4230    /// would have had to be threaded through all three open-coded copies
4231    /// in lockstep or one consumer would silently disagree with the
4232    /// peers on which child-set a given supervisor resolves to — the
4233    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
4234    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
4235    /// would silently split the partition-dispatch's two-arm coherence
4236    /// (a supervisor that satisfies neither arm's precondition, or that
4237    /// satisfies both, at the cost of the paired
4238    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
4239    /// silently drifting from the per-child validate loop's actual
4240    /// traversal input), a three-consumer split at the validator far
4241    /// from the source `caixa.lisp` with no field naming the
4242    /// child-set-drift root cause. Lifting the resolution rule to a
4243    /// typed method on the substrate primitive means every downstream
4244    /// consumer of the Supervisor's per-`:supervisor` static-child-list
4245    /// surface reaches for exactly one typed dispatch — the resolver's
4246    /// accept-set migrates as a unit on any future axis addition.
4247    ///
4248    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4249    /// — the seed for the same "one typed dispatch on the substrate
4250    /// primitive, thin projections at each consumer" discipline the
4251    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
4252    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
4253    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
4254    /// onto the first `Vec`-carry axis on the substrate. The four peer
4255    /// `Vec`-carry axes still unlifted at the time of this seed —
4256    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
4257    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
4258    /// (`Vec<Membro>` per-Aplicacao member list),
4259    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
4260    /// per-Aplicacao WIT-typed edge list),
4261    /// [`crate::UpgradeFromEntry::instructions`]
4262    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4263    /// — inherit this accessor's discipline as future compounding runs
4264    /// migrate their consumers onto the shared slice-return shape.
4265    /// Fourth (and final) accessor on the M2 supervisor-slot
4266    /// `SupervisorSpec` type, sibling to the three `Copy`-return
4267    /// [`SupervisorSpec::estrategia`] (eafb619) /
4268    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
4269    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
4270    /// the last unlifted per-`:supervisor` field axis (the
4271    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
4272    /// per-`:supervisor` reader now routes through a typed dispatch on
4273    /// the substrate primitive. Named `children()` to match the storage
4274    /// field's name verbatim and the tatara-lisp author-surface term
4275    /// (`:children`) the field's own docstring already carries; the
4276    /// accessor's identity maps onto the canonical OTP-shape
4277    /// supervision vocabulary the [`SupervisorSpec::children`] field's
4278    /// docstring already reaches for ("Static children ..."). Returns
4279    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
4280    /// consumer of the child list treats it as a read-only sequence —
4281    /// the slice-view is the narrowest borrow that supports every
4282    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
4283    /// index, `.len()`) without leaking the backing `Vec`'s
4284    /// grow/push/reserve surface that no consumer of the typed view
4285    /// reaches for (the storage-side `Vec` remains reachable through
4286    /// the `pub children` field for the mutation-carrying
4287    /// `Caixa::supervisor_view` fold-in path in
4288    /// `manifest.rs:supervisor_view`).
4289    #[must_use]
4290    pub const fn children(&self) -> &[ChildSpec] {
4291        self.children.as_slice()
4292    }
4293
4294    /// Validate the supervisor's typed shape — strategy ↔ children
4295    /// invariants, max_restarts > 0, restart_window > 0 when set,
4296    /// per-child non-empty + duplicate-free names.
4297    ///
4298    /// Mirrors the value-shape discipline applied to every other
4299    /// typed slot:
4300    ///
4301    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
4302    ///     same "0 means the opposite of what you think" footgun
4303    ///     closed for `:politicas :timeout` (Envoy interprets a zero
4304    ///     timeout as `infinite`), `:politicas :circuit-breaker
4305    ///     :window`, and `:limits :wall-clock`. The
4306    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
4307    ///     `supervisor` requires `Period > 0`; a zero period either
4308    ///     trips on the first failure or never trips depending on
4309    ///     operator interpretation, neither of which is the
4310    ///     author's intent. Omit `:restart-window` to express "no
4311    ///     reset"; carry a positive duration to express the window.
4312    ///   - duplicate `:children` `:caixa` names are the same
4313    ///     graph-node-set / multiset distinction closed for
4314    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
4315    ///     and `:entrada :paths` (eb3456d). Two children with the
4316    ///     same `:caixa` materialize as two ComputeUnits with the
4317    ///     same name in the cluster's HelmRelease values, one
4318    ///     silently overwriting the other. Erlang/OTP's
4319    ///     `child_spec.id` is required-unique per supervisor;
4320    ///     pleme-io enforces the same set-not-multiset shape on
4321    ///     `:caixa` (the load-bearing identity in our renderer).
4322    pub fn validate(&self) -> Result<(), SupervisorError> {
4323        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
4324        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4325        // error carrier's `estrategia:` field through the lifted
4326        // [`SupervisorSpec::estrategia`] accessor rather than the raw
4327        // `self.estrategia` field access — the two production consumers
4328        // of the per-`:supervisor` sibling-restart-strategy scalar now
4329        // key off exactly one typed dispatch on the substrate primitive,
4330        // so any future rebrand on the axis (a per-cluster strategy
4331        // override the operator pins through a future `:supervisor
4332        // :estrategia-overrides` slot, a per-tenant strategy-alias table
4333        // the M4 CR materializer resolves per-CR) migrates as a single
4334        // caixa-core edit rather than a coordinated rewrite of the two
4335        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4336        // (921fe1b) four-consumer migration on the per-`:placement`
4337        // distribution-strategy axis.
4338        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4339        // dispatch's paired `.is_empty()` cross-slot refusal probes
4340        // (the `SimpleOneForOne`-arm
4341        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4342        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4343        // refusal) through the lifted [`SupervisorSpec::children`]
4344        // slice-return accessor rather than the raw `self.children`
4345        // field access — the two paired production consumers of the
4346        // per-`:supervisor` static-child-list scalar-shape now key off
4347        // exactly one typed dispatch on the substrate primitive, so any
4348        // future rebrand on the axis (a per-cluster child-set overlay
4349        // the operator pins through a future `:supervisor
4350        // :children-overrides` slot, a per-tenant child-set-alias table
4351        // the M4 CR materializer resolves per-CR) migrates as a single
4352        // caixa-core edit rather than a coordinated rewrite of the
4353        // paired arms — first slice-return migration on any typed slot,
4354        // seed for the peer per-`:placement :clusters`,
4355        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4356        // :instructions` `Vec`-carry axes.
4357        match self.estrategia() {
4358            RestartStrategy::SimpleOneForOne => {
4359                // SimpleOneForOne: children added at runtime. Static
4360                // list must be empty (one shape declared elsewhere).
4361                if !self.children().is_empty() {
4362                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4363                }
4364            }
4365            _ => {
4366                if self.children().is_empty() {
4367                    return Err(SupervisorError::no_children(self.estrategia()));
4368                }
4369            }
4370        }
4371        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4372        // axis. See [`crate::render::require_positive_bounded_u32`] for
4373        // the ordering discipline (zero-floor arm strictly precedes cap
4374        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4375        // diagnostic with its counter-axis remediation directly named,
4376        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4377        // cap-arm miss). Until this bracket landed the top edge ran all
4378        // the way to `u32::MAX` and a struct-literal
4379        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4380        // equivalent author-surface `:max-restarts 100000` /
4381        // `:max-restarts 4294967295` typo landing in the slot) silently
4382        // passed validate. The runtime substrate consuming the value
4383        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4384        // wasm-operator's per-supervisor restart-intensity counter, the
4385        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4386        // admission webhook) then turned a typed `:max-restarts`
4387        // policy into a no-op supervisor: the escalation threshold is
4388        // structurally so high that no realistic
4389        // restarts-per-`:restart-window` traffic shape can reach it,
4390        // the supervisor never escalates to its parent, and a bad
4391        // child can loop inside the window indefinitely with the
4392        // parent supervisor structurally never receiving the "this
4393        // subtree has exceeded its restart budget" signal the typed
4394        // slot is meant to express. The bracket set is
4395        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4396        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4397        // the sibling `:politicas :circuit-breaker :max-failures` axis:
4398        // both are "trip the next-higher protection layer after N
4399        // events in a rolling window" counters with identical
4400        // degenerate-at-the-high-end shape and now share one canonical
4401        // bracket helper. The bracket precedes the sibling
4402        // `:restart-window` zero-floor / canonical-millisecond arms so
4403        // an over-cap `max_restarts` paired with a structurally invalid
4404        // window surfaces the bracket diagnostic first, mirroring the
4405        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4406        // ordering on the peer `:politicas :circuit-breaker` slot.
4407        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4408        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4409        // accessor rather than the raw `self.max_restarts` field access —
4410        // the one production consumer of the per-`:supervisor`
4411        // restart-budget-count scalar now keys off exactly one typed
4412        // dispatch on the substrate primitive, so any future rebrand on
4413        // the axis (a per-cluster restart-budget override the operator
4414        // pins through a future `:supervisor :max-restarts-overrides`
4415        // slot, a per-tenant restart-budget-alias table the M4 CR
4416        // materializer resolves per-CR) migrates as a single caixa-core
4417        // edit rather than a coordinated rewrite — sibling of the peer M3
4418        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4419        // the per-`:politicas :circuit-breaker :max-failures` axis.
4420        crate::render::require_positive_bounded_u32(
4421            self.max_restarts(),
4422            SUPERVISOR_MAX_RESTARTS_MAX,
4423            || SupervisorError::ZeroMaxRestarts,
4424            SupervisorError::max_restarts_exceeds_cap,
4425        )?;
4426        // Route the [`SupervisorSpec::validate`] `:restart-window`
4427        // zero-floor + integer-millisecond canonical-form + upper-cap
4428        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4429        // accessor rather than the raw `self.restart_window` field access —
4430        // the one production consumer of the per-`:supervisor`
4431        // restart-intensity-denominator scalar now keys off exactly one
4432        // typed dispatch on the substrate primitive, so any future rebrand
4433        // on the axis (a per-cluster restart-window override the operator
4434        // pins through a future `:supervisor :restart-window-overrides`
4435        // slot, a per-tenant restart-window-alias table the M4 CR
4436        // materializer resolves per-CR) migrates as a single caixa-core
4437        // edit rather than a coordinated rewrite — sibling of the peer M2
4438        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4439        // on the per-`:limits :wall-clock` axis and the peer M3
4440        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4441        // per-`:politicas :timeout` axis.
4442        if let Some(w) = self.restart_window() {
4443            // Zero-floor + integer-millisecond canonical-form +
4444            // upper-cap bracket on the typed `:restart-window` axis.
4445            // See
4446            // [`crate::render::require_positive_canonical_bounded_duration`]
4447            // for the full three-arm ordering discipline (zero-floor
4448            // strictly precedes canonical-form so `Duration::ZERO`
4449            // surfaces the self-locating `RestartWindowZero`
4450            // diagnostic; canonical-form strictly precedes the cap arm
4451            // so a sub-millisecond above-cap value surfaces the more
4452            // fundamental round-trip-shape diagnostic first) and the
4453            // three peer typed-`Duration` sites that share this
4454            // canonical bracket ([`crate::MeshPolicy::timeout`],
4455            // [`crate::CircuitBreaker::window`],
4456            // [`crate::LimitsSpec::wall_clock`]). Every validated
4457            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4458            // (1ms..=1h), integer-millisecond granularity.
4459            crate::render::require_positive_canonical_bounded_duration(
4460                w,
4461                SUPERVISOR_RESTART_WINDOW_MAX,
4462                || SupervisorError::RestartWindowZero,
4463                SupervisorError::restart_window_not_canonical,
4464                SupervisorError::restart_window_exceeds_cap,
4465            )?;
4466        }
4467        // Route the per-child DNS-1123 / semver-requirement / duplicate-
4468        // detection fan-out loop through the lifted named per-slot gate
4469        // [`SupervisorSpec::validate_children`] rather than an inline
4470        // three-per-child cascade — every future consumer that wants to
4471        // re-check only the `:children` slot's per-entry axes (the M4
4472        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4473        // admission webhook re-validating one added/renamed child, the
4474        // future wasm-operator's per-child dynamic-add re-validator on
4475        // the `SimpleOneForOne` runtime-add path once dynamic-children
4476        // graduate to a typed slot, a future partial re-validator on a
4477        // per-`:children`-entry patch) reaches every per-entry axis
4478        // through one dispatch rather than re-inlining the three-arm
4479        // cascade in lockstep with `validate` or paying the peer
4480        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4481        // reach one entry check. Sibling of the peer M3 mesh-slot
4482        // per-slot gate family (`validate_membros` — the exact peer on
4483        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4484        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4485        // `validate_placement`; `validate_politicas` routing through
4486        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4487        // per-slot gate discipline now spans both the M3 mesh-slot
4488        // family and the M2 `:children` per-child-cascade axis on one
4489        // shape: one named per-slot gate per typed per-entry loop.
4490        self.validate_children()?;
4491        Ok(())
4492    }
4493
4494    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4495    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4496    /// gate, and duplicate-`:caixa` dedup arm into one call every
4497    /// consumer that wants to re-validate one `:children` entry (or the
4498    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4499    /// admits reaches through.
4500    ///
4501    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4502    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4503    /// three-per-entry shape (DNS-1123 name + semver-requirement +
4504    /// duplicate-`:caixa` dedup), lifted to one named substrate
4505    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4506    /// materializer's admission webhook re-checking one added or renamed
4507    /// child, the future wasm-operator's per-child dynamic-add
4508    /// re-validator on the `SimpleOneForOne` runtime-add path once
4509    /// dynamic-children graduate to a typed slot, a future partial
4510    /// re-validator on a per-`:children`-entry patch — each reaches the
4511    /// three per-entry axes through this one dispatch rather than
4512    /// re-inlining the three-arm cascade in lockstep with `validate`
4513    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4514    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4515    /// reach one entry check.
4516    ///
4517    /// Self-contained on `&self` — resolves its own dedup `HashSet`
4518    /// through [`SupervisorSpec::children`] rather than borrowing one
4519    /// threaded down from `validate`, the same posture the peer M3
4520    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4521    /// [`crate::AplicacaoSpec::validate_contratos`],
4522    /// [`crate::AplicacaoSpec::validate_entrada`],
4523    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4524    /// consumer that reaches this gate directly (without first calling
4525    /// `validate`) still runs the full per-child cascade — pinned by
4526    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4527    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4528    /// + `validate_children_is_self_contained_on_children_slot`.
4529    ///
4530    /// The three per-entry arms run in the same canonical order the
4531    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4532    /// the diagnostic every author-declared per-`:children` entry surfaces
4533    /// through `validate` is byte-equal to the diagnostic this gate
4534    /// surfaces when called directly — the equivalence-pin pair
4535    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4536    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4537    /// asserts the two altitudes discriminate the same set on every
4538    /// per-entry-covered input.
4539    pub fn validate_children(&self) -> Result<(), SupervisorError> {
4540        let mut seen = std::collections::HashSet::new();
4541        for child in self.children() {
4542            // Every emitted cluster artifact's `metadata.name` for a
4543            // supervised child derives from this `:children :caixa` value
4544            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4545            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4546            // label value on every child's pod identity, and the per-
4547            // child K8s [`Service`][svc] `metadata.name` the future
4548            // wasm-operator (M3) provisions for inter-child supervision
4549            // tree wiring. Each apiserver-side schema on each landing
4550            // site enforces the DNS-1123 label rule on admission; a
4551            // structurally invalid child name (`"Worker"`, `"my_worker"`,
4552            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4553            // UUID-shaped mistaken-identity slug) silently passes the
4554            // prior empty-/duplicate-only gate and the failure surfaces
4555            // at `kubectl apply` time as a `metadata.name: Invalid value`
4556            // rejection, far from the source caixa.lisp, with no field
4557            // naming the offending `:children` entry. Lifting the gate
4558            // to caixa-build time mirrors the `:membros :caixa` value-
4559            // shape trajectory (3f9d7a0) and the `:placement :clusters`
4560            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4561            // identifier axis — the supervisor tree's child names —
4562            // through the lifted
4563            // [`crate::render::require_valid_dns_1123_label`] gate the
4564            // seven peer name axes (`:membros :caixa`, `:placement
4565            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4566            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4567            // route through, so drift between the eight axes' accepted
4568            // DNS-1123-label sets is structurally impossible.
4569            //
4570            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4571            crate::render::require_valid_dns_1123_label(
4572                child.nome(),
4573                || SupervisorError::EmptyChildName,
4574                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4575            )?;
4576            // The author surface for `:children :versao` is the same
4577            // Cargo-shaped semver requirement string `:deps :versao` and
4578            // `:membros :versao` carry — and the lacre pipeline resolves
4579            // all three axes through the same
4580            // [`crate::version::parse_requirement`] entry-point. The
4581            // shared [`crate::render::require_valid_versao_requirement`]
4582            // helper brackets the empty-first + parse cascade both peer
4583            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4584            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4585            // :versao`) route through, so drift between the three axes'
4586            // accepted requirement sets is structurally impossible and
4587            // the parse-side no-op the empty-first arm closes (semver's
4588            // empty parse yields an implicit `*`) lives in exactly one
4589            // predicate. Every `ChildSpec::versao` past validate is
4590            // round-trippable through [`crate::parse_requirement`]
4591            // without re-checking at the resolver layer, and the three
4592            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4593            // are now structurally equivalent by construction.
4594            crate::render::require_valid_versao_requirement(
4595                child.versao_requirement(),
4596                || SupervisorError::empty_child_version(child.nome()),
4597                |reason| {
4598                    SupervisorError::child_versao_invalid(
4599                        child.nome(),
4600                        child.versao_requirement(),
4601                        reason,
4602                    )
4603                },
4604            )?;
4605            crate::render::insert_first_seen(&mut seen, child.nome(), || {
4606                SupervisorError::duplicate_child_caixa(child.nome())
4607            })?;
4608        }
4609        Ok(())
4610    }
4611}
4612
4613/// Cross-slot coherence gate on the supervision tree: no
4614/// `:children :caixa` entry may name the supervisor's own `:nome`.
4615///
4616/// A supervisor that lists itself as a child is a degenerate self-parent
4617/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4618/// specs reference *distinct* child processes; a supervisor is never its
4619/// own child), and the wasm-operator's hierarchical reconciliation would
4620/// otherwise be handed a node that is its own parent: a one-node cycle it
4621/// either rejects far from the source `caixa.lisp` or recurses on. Because
4622/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4623/// lacre closure root), a child whose `:caixa` equals the supervisor's
4624/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4625///
4626/// Lives outside [`SupervisorSpec::validate`] because the typed view
4627/// carries the children but not the parent `:nome`; mirrors the
4628/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4629/// (which likewise reads one slot against another at the
4630/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4631/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4632/// node to itself is structurally not a tree/mesh edge" discipline, here
4633/// on the supervision-tree axis.
4634pub fn validate_no_self_supervision(
4635    children: &[ChildSpec],
4636    parent_nome: &str,
4637) -> Result<(), SupervisorError> {
4638    for child in children {
4639        if child.nome() == parent_nome {
4640            return Err(SupervisorError::child_supervises_self(parent_nome));
4641        }
4642    }
4643    Ok(())
4644}
4645
4646#[derive(Debug, Error, PartialEq, Eq)]
4647pub enum SupervisorError {
4648    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4649    NoChildren { estrategia: RestartStrategy },
4650    #[error(
4651        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4652    )]
4653    SimpleOneForOneWithStaticChildren,
4654    #[error(":max-restarts must be > 0")]
4655    ZeroMaxRestarts,
4656    #[error(
4657        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4658         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4659         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4660         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4661         can reach it, so the supervisor never escalates to its parent and a bad child can \
4662         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4663         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4664         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4665         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4666         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4667         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4668         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4669         band) or restructure the supervision tree (split the flaky child into its own \
4670         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4671    )]
4672    MaxRestartsExceedsCap { max_restarts: u32 },
4673    #[error(
4674        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4675         requires Period > 0; a zero window either trips on the first failure or \
4676         never trips depending on operator interpretation. Omit :restart-window to \
4677         express `never reset`; carry a positive duration to express the window."
4678    )]
4679    RestartWindowZero,
4680    #[error(
4681        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4682         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4683         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4684         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4685         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4686    )]
4687    RestartWindowNotCanonical { window: Duration },
4688    #[error(
4689        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4690         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4691         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4692         failure-counting window is structurally so long that transient restarts are never \
4693         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4694         when the child has exceeded its restart budget within the recent window` to `trip the \
4695         parent when the child has exceeded its restart budget over its lifetime`, and the \
4696         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4697         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4698         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4699         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4700         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4701         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4702         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4703         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4704         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4705         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4706         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4707         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4708         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4709         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4710         hiding it behind a rolling-window declaration the cap arm rejects)"
4711    )]
4712    RestartWindowExceedsCap { window: Duration },
4713    #[error("child entry has empty :caixa name")]
4714    EmptyChildName,
4715    #[error(
4716        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4717         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4718         name / label value the child name lands in — the per-child \
4719         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4720         label value, and the future wasm-operator per-child Service `metadata.name` \
4721         — each apiserver-side schema rejects names that don't match; use a \
4722         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4723    )]
4724    ChildCaixaInvalid { caixa: String, reason: String },
4725    #[error("child {caixa:?} has empty :versao constraint")]
4726    EmptyChildVersion { caixa: String },
4727    #[error(
4728        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4729         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4730         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4731         `:membros :versao` carry; the lacre pipeline resolves all three \
4732         through the same parser)"
4733    )]
4734    ChildVersaoInvalid {
4735        caixa: String,
4736        versao: String,
4737        reason: String,
4738    },
4739    #[error(
4740        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4741         child_spec.id per supervisor; duplicate children materialize as duplicate \
4742         ComputeUnits in the rendered chart, one silently overwriting the other)"
4743    )]
4744    DuplicateChildCaixa { caixa: String },
4745    #[error(
4746        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4747         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4748         OTP child specs reference distinct child processes). Since every :nome is a \
4749         globally-unique substrate identity, a child naming the supervisor's own :nome \
4750         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4751         self-referential :children entry or rename it to the actual child caixa."
4752    )]
4753    ChildSupervisesSelf { caixa: String },
4754}
4755
4756// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4757// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4758// and [`validate_no_self_supervision`] onto one substrate primitive per
4759// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4760// `LayoutError`-envelope constructor families the peer
4761// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4762// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4763// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4764// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4765// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4766// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4767// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4768// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4769// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4770// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4771// variants on `{ de, para }`) already at that discipline on the peer
4772// `AplicacaoError` envelopes.
4773//
4774// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4775// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4776// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4777// self-supervision arm) opened the identical
4778// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4779// the exact "same block re-inlined at every consumer" shape the PRIME
4780// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4781// `AplicacaoError` families each closed on their sibling envelopes. The
4782// three variants share one `{ caixa: String }` shape, so the fold routes
4783// each wire-up site through one dispatch per typed variant.
4784//
4785// The macro below generates one static constructor per variant of shape
4786// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4787// collapses onto one dispatch:
4788// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4789// struct-literal on the same `&str` fixture. The uniform one-field
4790// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4791// macro — rather than at every wire-up site. Every constructor is
4792// `#[must_use]` so a caller who mistakenly discards the constructed error
4793// trips a compile warning at the wire-up site.
4794//
4795// Every future consumer that wants to construct one of these three
4796// variants outside `SupervisorSpec::validate_children` /
4797// `validate_no_self_supervision` — a deferred
4798// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4799// webhook re-checking one added/renamed child, a future
4800// `feira validate --supervisor` per-caixa admission verb, a per-child
4801// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4802// once dynamic-children graduate to a typed slot, a per-Supervisor
4803// overlay resolver rejecting a duplicate/self-supervising child against
4804// a cluster-local snapshot — now reaches each variant through one call
4805// rather than re-inlining the three-line struct-literal in lockstep
4806// with the three in-crate wire-up sites.
4807macro_rules! supervisor_caixa_only_ctors {
4808    ($($ctor:ident => $variant:ident),* $(,)?) => {
4809        impl SupervisorError {
4810            $(
4811                #[doc = concat!(
4812                    "Construct a [`SupervisorError::",
4813                    stringify!($variant),
4814                    "`] naming the offending `:children :caixa` (or ",
4815                    "supervisor `:nome`, on the self-supervision arm). ",
4816                    "Folds the uniform `Self::",
4817                    stringify!($variant),
4818                    " { caixa: caixa.to_string() }` one-field ",
4819                    "struct-literal onto one substrate primitive so ",
4820                    "every [`SupervisorSpec::validate_children`] / ",
4821                    "[`validate_no_self_supervision`] wire-up on this ",
4822                    "variant reads through one dispatch rather than the ",
4823                    "pre-lift open-coded struct-literal block."
4824                )]
4825                #[must_use]
4826                pub fn $ctor(caixa: &str) -> Self {
4827                    Self::$variant { caixa: caixa.to_string() }
4828                }
4829            )*
4830        }
4831    };
4832}
4833
4834supervisor_caixa_only_ctors! {
4835    empty_child_version => EmptyChildVersion,
4836    duplicate_child_caixa => DuplicateChildCaixa,
4837    child_supervises_self => ChildSupervisesSelf,
4838}
4839
4840// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4841// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4842// one substrate primitive per typed variant — the M2 supervisor-side siblings
4843// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4844// already lifted through the sibling
4845// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4846// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4847// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4848// String }` two-slot shape the peer seven-variant
4849// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4850// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4851// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4852// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4853// variant carries the `{ caixa: String, versao: String, reason: String }`
4854// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4855// carries on the same `:versao` value-shape.
4856//
4857// Each of the two wire-up sites opened the same closure-shaped
4858// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4859// [versao: child.versao_requirement().to_string(),] reason }` block inside
4860// the paired [`crate::render::require_valid_dns_1123_label`] and
4861// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4862// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4863// as a bug, on the same altitude the peer `AplicacaoError` /
4864// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4865// families already closed on their sibling envelopes.
4866//
4867// The two `#[must_use]` inherent constructors below fold each wire-up onto
4868// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4869// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4870// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4871// The uniform per-field `.to_string()` / `.into()` construction is spelled
4872// once — inside each ctor body — rather than at every wire-up site. The
4873// `reason: impl Into<String>` bound accepts both `&str` literals and
4874// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4875// diagnostic shape at the lift, matching the peer
4876// [`aplicacao_field_reason_ctors!`] and
4877// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4878// sibling envelopes.
4879//
4880// Every future consumer that wants to construct one of these two variants
4881// outside `SupervisorSpec::validate_children` — a deferred
4882// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4883// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4884// `feira validate --supervisor` per-caixa admission verb, a per-child
4885// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4886// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4887// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4888// cluster-local snapshot — now reaches each variant through one call rather
4889// than re-inlining the per-shape struct-literal block in lockstep with the
4890// two in-crate wire-up sites.
4891impl SupervisorError {
4892    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4893    /// offending `:children :caixa` value under the given `reason`. Folds
4894    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4895    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4896    /// primitive so every wire-up on this variant reads through one
4897    /// dispatch, matching the peer
4898    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4899    /// sibling `AplicacaoError { caixa: String, reason: String }`
4900    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4901    /// outputs through the `impl Into<String>` bound.
4902    #[must_use]
4903    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4904        Self::ChildCaixaInvalid {
4905            caixa: caixa.to_string(),
4906            reason: reason.into(),
4907        }
4908    }
4909
4910    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4911    /// offending `:children :caixa` and its `:versao` requirement under
4912    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4913    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4914    /// reason.into() }` three-slot struct-literal onto one substrate
4915    /// primitive so every wire-up on this variant reads through one
4916    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4917    /// { caixa, versao, reason }` three-slot axis on the peer
4918    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4919    /// and `format!(…)` outputs through the `impl Into<String>` bound.
4920    #[must_use]
4921    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4922        Self::ChildVersaoInvalid {
4923            caixa: caixa.to_string(),
4924            versao: versao.to_string(),
4925            reason: reason.into(),
4926        }
4927    }
4928}
4929
4930// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4931// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4932// three bracket-arms — one struct-literal at the `:children`-empty
4933// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4934// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4935// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4936// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4937// [`crate::render::require_positive_canonical_bounded_duration`]
4938// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4939// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4940// primitive per typed variant, matching the sibling
4941// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4942// variants on the same `{ <field>: Duration | u32 }` shape) at that
4943// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4944// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4945// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4946// wire-up site through one dispatch per typed variant without a runtime-
4947// work delta.
4948//
4949// Each of the four wire-up sites opened the identical
4950// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4951// exact "same block re-inlined at every consumer" shape the PRIME
4952// DIRECTIVE names as a bug, on the same altitude the peer
4953// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4954// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4955// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4956// the fold routes each wire-up site through one dispatch per typed
4957// variant.
4958//
4959// The macro below generates one static constructor per variant of shape
4960// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4961// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4962// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4963// fixture — as a direct call at the [`SupervisorSpec::validate`]
4964// `:children`-empty refusal, or as a bare function pointer in the
4965// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4966// [`crate::render::require_positive_bounded_u32`] /
4967// [`crate::render::require_positive_canonical_bounded_duration`] gate
4968// carries — rather than the pre-lift open-coded one-line closure over
4969// the same one-field struct-literal. `const fn` preserves the `Copy`-
4970// pass-through's zero-runtime-work property verbatim. Every constructor
4971// is `#[must_use]` so a caller who mistakenly discards the constructed
4972// error trips a compile warning at the wire-up site.
4973//
4974// Every future consumer that wants to construct one of these four
4975// variants outside `SupervisorSpec::validate` — a deferred
4976// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4977// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4978// `:restart-window` slot against the cap + canonical-form cascade, a
4979// future `feira validate --supervisor` per-caixa admission verb re-
4980// running the shape gates on demand, a per-Supervisor overlay resolver
4981// rejecting an author-supplied slot against a cluster-local snapshot —
4982// now reaches each variant through one call rather than re-inlining the
4983// per-shape struct-literal block in lockstep with the four in-crate
4984// wire-up sites.
4985macro_rules! supervisor_scalar_ctors {
4986    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4987        impl SupervisorError {
4988            $(
4989                #[doc = concat!(
4990                    "Construct a [`SupervisorError::",
4991                    stringify!($variant),
4992                    "`] naming the offending per-`:supervisor` `",
4993                    stringify!($field),
4994                    "` scalar. Folds the uniform `Self::",
4995                    stringify!($variant),
4996                    " { ",
4997                    stringify!($field),
4998                    " }` one-field `Copy`-pass-through struct-literal onto ",
4999                    "one substrate primitive so every per-axis wire-up on ",
5000                    "this variant reads through one dispatch — as a direct ",
5001                    "call (`SupervisorError::",
5002                    stringify!($ctor),
5003                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
5004                    "the same `Copy`-`",
5005                    stringify!($ty),
5006                    "` fixture) or as a bare function pointer in the ",
5007                    "`impl FnOnce(",
5008                    stringify!($ty),
5009                    ") -> SupervisorError` bracket-closure slot every ",
5010                    "`crate::render::require_positive_bounded_*` / ",
5011                    "`crate::render::require_positive_canonical_bounded_*` ",
5012                    "gate carries — rather than the pre-lift open-coded ",
5013                    "one-line closure over the same one-field struct-",
5014                    "literal. `const fn` preserves the `Copy`-pass-through's ",
5015                    "zero-runtime-work property verbatim."
5016                )]
5017                #[must_use]
5018                pub const fn $ctor($field: $ty) -> Self {
5019                    Self::$variant { $field }
5020                }
5021            )*
5022        }
5023    };
5024}
5025
5026supervisor_scalar_ctors! {
5027    no_children => NoChildren { estrategia: RestartStrategy },
5028    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
5029    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
5030    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
5031}
5032
5033/// Shared duration string codec for the typed slots that take a
5034/// duration (`restart_window`, `MeshPolicy::timeout`,
5035/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
5036/// reuse it without duplicating the parser.
5037pub mod duration_codec {
5038    use super::Duration;
5039    use serde::{Deserializer, Serializer};
5040
5041    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
5042        // Route through the canonical [`crate::render::serialize_option_via_str`]
5043        // — the substrate-side single-owner primitive for the forward
5044        // arm of the typed-magnitude codec family. See its docstring
5045        // for the full sibling roster.
5046        crate::render::serialize_option_via_str(v, s, render)
5047    }
5048
5049    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
5050        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5051        // — the substrate-side single-owner primitive for the reverse
5052        // arm of the typed-magnitude codec family. See its docstring
5053        // for the full sibling roster.
5054        crate::render::deserialize_option_via_str(d, parse)
5055    }
5056
5057    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
5058        // Paired whitespace-rejection arm — same canonical-form
5059        // render-determinism discipline as the peer
5060        // `limits::parse_byte_size` / `limits::parse_duration` /
5061        // `limits::parse_millicores` /
5062        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
5063        // byte-scan closes the WhatWG-conformant whitespace bytes
5064        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5065        // `char::is_whitespace` scan closes the strictly-complementary
5066        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5067        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5068        // codepoints) that `str::trim` at parse entry silently strips.
5069        // Either drift class would round-trip through `render` to a
5070        // *different* canonical form on next emit — breaking the
5071        // THEORY.md Part V render-determinism contract on three typed-
5072        // duration slots at once (`:supervisor :restart-window`,
5073        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
5074        // via the shared codec.
5075        //
5076        // Routed through the lifted [`crate::render::reject_whitespace`]
5077        // primitive — the substrate-side single-owner paired-arm gate
5078        // every typed-magnitude codec in caixa-core shares.
5079        crate::render::reject_whitespace::<String, _, _>(
5080            s,
5081            |b| {
5082                format!(
5083                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5084                 authoring form for the typed duration slots routed through this shared codec \
5085                 (`:supervisor :restart-window`, `:politicas :timeout`, \
5086                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5087                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
5088                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
5089                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
5090                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
5091                 Part V render-determinism contract every typed slot carries. Strip every \
5092                 whitespace byte (write `\"30s\"` verbatim)"
5093                )
5094            },
5095            |ch| {
5096                format!(
5097                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
5098                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
5099                 duration slots routed through this shared codec (`:supervisor \
5100                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
5101                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
5102                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
5103                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
5104                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
5105                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
5106                 `White_Space` property, strictly wider than the ASCII byte set) silently \
5107                 strips it at parse entry, and the value round-trips through `render` to \
5108                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
5109                 the THEORY.md Part V render-determinism contract every typed slot \
5110                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
5111                 verbatim with only ASCII bytes)",
5112                    cp = ch as u32
5113                )
5114            },
5115        )?;
5116        let s = s.trim();
5117        // Routed through the lifted
5118        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
5119        // the single-owner split every ASCII-alphabetic-unit typed-
5120        // magnitude codec in caixa-core (`limits::parse_byte_size` /
5121        // `limits::parse_duration` / this shared duration codec) shares.
5122        // See its docstring for the full sibling roster on the same
5123        // primitive altitude.
5124        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
5125        let num_trim = num_part.trim();
5126        // The canonical authoring form for every typed slot routed
5127        // through this shared codec — `:supervisor :restart-window`,
5128        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
5129        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
5130        // non-negative integer with no decimal point and no leading
5131        // sign, so the parser's accepted set must match for
5132        // serialize/deserialize to round-trip without canonical-form
5133        // drift. Until this gate landed the parser accepted any
5134        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
5135        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
5136        // tripped the value to a *different* canonical string on the
5137        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
5138        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
5139        // — breaking the THEORY.md Part V render-determinism contract
5140        // on three typed slots at once. Same canonical-form discipline
5141        // `crate::limits::parse_duration` (818dd38, the immediate
5142        // predecessor on the peer `:limits :wall-clock` codec) applies;
5143        // this gate lifts the discipline onto the shared codec that
5144        // backs the remaining three typed-duration slots in caixa-core.
5145        //
5146        // Strict canonical form: every byte of the magnitude is an
5147        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5148        // inputs the gate distinguishes "non-canonical-but-numeric"
5149        // (parses as f64 or i64 — surfaced with a self-locating
5150        // diagnostic naming the canonical authoring form, the
5151        // round-trip drift each rejected shape would produce on first
5152        // serialize, and the canonical-form remediation) from
5153        // "garbage" (parses as neither — surfaced with the existing
5154        // narrower "bad duration magnitude" wording so its diagnostic
5155        // shape remains stable for the parser-shape footgun case).
5156        // The pre-existing `num < 0.0` arm is now unreachable — the
5157        // digit-only gate strictly precedes magnitude parsing, and a
5158        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
5159        // non-canonical-but-numeric branch with the `-30` named
5160        // verbatim in the diagnostic rather than the prior
5161        // value-laundered "negative duration in \"-30s\"" wording.
5162        //
5163        // Routed through the lifted
5164        // [`crate::render::is_digit_only_magnitude`] predicate — the
5165        // same source of truth the four peer typed-magnitude codec
5166        // sites share.
5167        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
5168        if !digit_only {
5169            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
5170            if numeric {
5171                return Err(format!(
5172                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
5173                     canonical authoring form for the typed duration slots routed through \
5174                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5175                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5176                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
5177                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
5178                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
5179                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
5180                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
5181                     THEORY.md Part V render-determinism contract every typed slot carries. \
5182                     Pick an integer magnitude in the unit that divides cleanly (write \
5183                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
5184                ));
5185            }
5186            return Err(format!("bad duration magnitude in {s:?}"));
5187        }
5188        // Leading-zero arm — peer with the `rate_limit_codec` leading-
5189        // zero arm (4f46830) on the same canonical-form render-
5190        // determinism axis. The digit-only gate accepts `"030s"`,
5191        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
5192        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
5193        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
5194        // *different* canonical string on the next emit, breaking the
5195        // THEORY.md Part V render-determinism contract the same way
5196        // `"+30s"` did before the leading-`+` arm landed. The single-
5197        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
5198        // losslessly through `render` (`render(Duration::ZERO)` emits
5199        // `"0s"`) — the downstream semantic-zero gates (e.g.
5200        // `SupervisorError::ZeroRestartWindow` on
5201        // `:supervisor :restart-window`,
5202        // `AplicacaoError::PolicyTimeoutZero` /
5203        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
5204        // duration slots) refuse zero-magnitude authoring at the typed-
5205        // validate layer above, so the single-byte `"0"` stays in the
5206        // accepted set at this codec layer and the diagnostic
5207        // partitioning between canonical-form drift (this arm) and
5208        // semantic-zero (the downstream gates) remains stable.
5209        // Peer with the future leading-zero arms on the two remaining
5210        // typed-magnitude codecs the trajectory acknowledges:
5211        // `limits::parse_duration` backing `:limits :wall-clock`,
5212        // `limits::parse_byte_size` backing `:limits :memory` — each
5213        // carries the same canonical-form-drift class today; this
5214        // gate lands the discipline on the shared duration codec
5215        // first because the `rate_limit_codec` predecessor on the
5216        // same canonical-form-drift axis is the closest peer on the
5217        // trajectory.
5218        //
5219        // Routed through the lifted
5220        // [`crate::render::is_leading_zero_padded_magnitude`]
5221        // predicate — the same source of truth the four peer
5222        // typed-magnitude codec sites share.
5223        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
5224            return Err(format!(
5225                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
5226                 canonical authoring form for the typed duration slots routed through \
5227                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5228                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5229                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
5230                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
5231                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
5232                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
5233                 serialize — breaking the THEORY.md Part V render-determinism contract \
5234                 every typed slot carries. Strip the leading zeros (write \
5235                 `\"30s\"` instead of `\"030s\"`)"
5236            ));
5237        }
5238        // The digit-only gate guarantees every byte is `[0-9]`, and
5239        // the leading-zero arm above guarantees the magnitude is
5240        // either the single byte `"0"` or starts with `[1-9]`, so
5241        // the only way `u64::from_str` can fail here is overflow (the
5242        // magnitude exceeds `u64::MAX`). Surface that with an
5243        // overflow-shaped wording so the diagnostic names the offending
5244        // magnitude verbatim rather than collapsing onto the
5245        // non-canonical arm. The codec now operates on `u64` end-to-end
5246        // — every accepted magnitude is integer-exact; no f64 mantissa
5247        // drift between author-supplied magnitude and the consumer's
5248        // `Duration` value. Same shape `crate::limits::parse_duration`
5249        // (818dd38) carries on the peer `:limits :wall-clock` axis.
5250        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
5251            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
5252        })?;
5253        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
5254        // unit-arm dispatch through the canonical
5255        // [`crate::render::duration_from_integer_magnitude_and_unit`]
5256        // primitive — the substrate-side single-owner unit-dispatch
5257        // table every typed-duration codec in caixa-core routes
5258        // through (peer: `crate::limits::parse_duration` backing
5259        // `:limits :wall-clock`). Every unit conversion is integer-
5260        // exact for an integer magnitude; overflow surfaces via the
5261        // typed `DurationUnitError::Overflow { multiplier }`
5262        // discriminant so this arm reconstructs the pre-lift
5263        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
5264        // wording verbatim from `num` / `unit_trim` / the returned
5265        // `multiplier`, and the unknown-unit arm reconstructs the
5266        // pre-lift `"unknown duration unit \"<other>\""` wording from
5267        // the caller-scoped `unit_trim`. Load-bearing pinned by
5268        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
5269        let unit_trim = unit.trim();
5270        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
5271            |e| match e {
5272                crate::render::DurationUnitError::Overflow { multiplier } => format!(
5273                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
5274                ),
5275                crate::render::DurationUnitError::UnknownUnit => {
5276                    format!("unknown duration unit {unit_trim:?}")
5277                }
5278            },
5279        )?;
5280        Ok(dur)
5281    }
5282
5283    /// Render a [`Duration`] in the canonical pleme-io duration string
5284    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
5285    /// caixa typed-duration slot serializes to and the same form K8s
5286    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
5287    /// EnvoyConfig per-route timeouts both expect (an integer
5288    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
5289    /// `+`). Lifted to `pub` so caixa-side renderers
5290    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
5291    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
5292    /// emitter, the future caixa-otel collector pipeline emitter) can
5293    /// consume the same canonical formatter without re-inlining the
5294    /// magnitude/unit decision tree (and inheriting the same drift
5295    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
5296    /// downstream apply-time parsing in non-obvious ways).
5297    pub fn render(d: Duration) -> String {
5298        let total_ms = d.as_millis();
5299        if total_ms == 0 {
5300            return "0s".into();
5301        }
5302        if total_ms.is_multiple_of(3600 * 1000) {
5303            return format!("{}h", total_ms / (3600 * 1000));
5304        }
5305        if total_ms.is_multiple_of(60 * 1000) {
5306            return format!("{}m", total_ms / (60 * 1000));
5307        }
5308        if total_ms.is_multiple_of(1000) {
5309            return format!("{}s", total_ms / 1000);
5310        }
5311        format!("{total_ms}ms")
5312    }
5313
5314    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
5315    ///
5316    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
5317    /// largest divisor unit, so any sub-millisecond residue
5318    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
5319    /// §V.2.7 render-determinism contract:
5320    ///
5321    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
5322    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
5323    ///     `1_000_000` ns ≠ original `1_500_000` ns;
5324    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
5325    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
5326    ///     on every typed-`Duration` slot then rejects on re-validate.
5327    ///
5328    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
5329    /// the codec's round-trippable accepted set lives in exactly one place —
5330    /// every typed-`Duration` slot that routes through this shared codec
5331    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
5332    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
5333    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
5334    /// every typed-`Duration` slot whose own codec shares the same
5335    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5336    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5337    /// pair) calls this predicate from its `validate()` to bracket the
5338    /// accepted set against the codec's accepted set, structurally. Drift
5339    /// between the codec's granularity and any typed slot's accepted set is
5340    /// then a single-source-of-truth edit at this predicate rather than a
5341    /// silent round-trip break the next consumer discovers at apply time.
5342    ///
5343    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5344    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5345    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5346    /// family — same "typed-slot's valid set matches its codec's accepted
5347    /// set, structurally" discipline carried at the codec layer.
5348    #[must_use]
5349    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5350        d.subsec_nanos().is_multiple_of(1_000_000)
5351    }
5352}
5353
5354/// Required-Duration variant for fields that aren't Option<Duration>.
5355pub mod duration_codec_required {
5356    use super::Duration;
5357    use serde::{Deserialize, Deserializer, Serializer};
5358
5359    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5360        s.serialize_str(&super::duration_codec::render(*v))
5361    }
5362
5363    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5364        let s = String::deserialize(d)?;
5365        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5366    }
5367}
5368
5369#[cfg(test)]
5370mod tests {
5371    use super::*;
5372
5373    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5374        ChildSpec {
5375            caixa: name.into(),
5376            versao: ver.into(),
5377            restart,
5378        }
5379    }
5380
5381    #[test]
5382    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5383        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5384        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5385        // posture. Each accessor projects the per-`:children :caixa`
5386        // / per-`:children :versao` [`String`] storage through the
5387        // `pub const fn` [`String::as_str`] (const-stable since Rust
5388        // 1.87, well within the workspace MSRV) — any future
5389        // accidental downgrade to non-`const` fails the corresponding
5390        // `<name>_via_const_fn` wrapper at caixa-core build time with
5391        // E0015 (`cannot call non-const method`), strictly stronger
5392        // than a runtime `assert!`. Sibling of the peer
5393        // per-M2/M3/universal-axis `String → &str` scalar-accessor
5394        // family pins on the sibling `const`-eval-surface passes
5395        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5396        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5397        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5398        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5399        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5400        // [`crate::aplicacao::Entrada::destination`] at the M3
5401        // ingress axis,
5402        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5403        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5404        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5405        // axis, and the per-`:contratos`
5406        // [`crate::aplicacao::WitContract::source`] /
5407        // [`crate::aplicacao::WitContract::destination`] /
5408        // [`crate::aplicacao::WitContract::world_ref`] trio the
5409        // sibling pin at 279823b already anchors).
5410        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5411            c.nome()
5412        }
5413        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5414            c.versao_requirement()
5415        }
5416        for (caixa, versao) in [
5417            ("worker-a", "^0.1"),
5418            ("worker-b", "~0.2.3"),
5419            ("collector", "*"),
5420        ] {
5421            let c = child(caixa, versao, RestartPolicy::Permanent);
5422            assert_eq!(nome_via_const_fn(&c), c.nome());
5423            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5424            assert_eq!(c.nome(), caixa);
5425            assert_eq!(c.versao_requirement(), versao);
5426        }
5427    }
5428
5429    #[test]
5430    fn supervisor_children_slice_return_accessor_is_const_fn() {
5431        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5432        // `const`-eval-surface posture. The accessor destructures the
5433        // per-`:children` `Vec<ChildSpec>` storage through the
5434        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5435        // 1.66, well within the workspace MSRV) — any future
5436        // accidental downgrade to non-`const` fails
5437        // `children_via_const_fn` at caixa-core build time with E0015
5438        // (`cannot call non-const method`), strictly stronger than a
5439        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5440        // `Vec → &[T]` slice-return accessor family pin
5441        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5442        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5443        // per-`:membros` / per-`:contratos` slice-return axes, and of
5444        // the peer M2 upgrade-appup axis pin
5445        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5446        // on the per-`:upgrade-from :instructions` slice-return axis.
5447        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5448            s.children()
5449        }
5450        // Sweep both the empty-children (leaf-supervisor with no
5451        // static children — the `SimpleOneForOne` dynamic-child
5452        // arm's canonical shape) and the populated-children
5453        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5454        // arm's canonical shape) axes so the accessor carries a
5455        // const-dispatch pin on both arms.
5456        let s_empty = SupervisorSpec {
5457            estrategia: RestartStrategy::SimpleOneForOne,
5458            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5459            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5460            children: vec![],
5461        };
5462        assert!(children_via_const_fn(&s_empty).is_empty());
5463        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5464        let s_full = SupervisorSpec {
5465            estrategia: RestartStrategy::OneForOne,
5466            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5467            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5468            children: vec![
5469                child("worker-a", "^0.1", RestartPolicy::Permanent),
5470                child("worker-b", "~0.2.3", RestartPolicy::Transient),
5471                child("collector", "*", RestartPolicy::Temporary),
5472            ],
5473        };
5474        assert_eq!(children_via_const_fn(&s_full).len(), 3);
5475        assert_eq!(children_via_const_fn(&s_full), s_full.children());
5476    }
5477
5478    #[test]
5479    fn default_has_one_for_one_and_5_restarts_in_60s() {
5480        let s = SupervisorSpec::default();
5481        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5482        assert_eq!(s.max_restarts, 5);
5483        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5484        assert!(s.children.is_empty());
5485    }
5486
5487    #[test]
5488    fn validate_one_for_one_requires_children() {
5489        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5490        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5491        // struct-update to name the axis under test at construction, and this shape matches
5492        // it. Also keeps the "empty children is the axis under test" intent visible at the
5493        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5494        let mut s = SupervisorSpec {
5495            children: vec![],
5496            ..SupervisorSpec::default()
5497        };
5498        assert!(matches!(
5499            s.validate().unwrap_err(),
5500            SupervisorError::NoChildren { .. }
5501        ));
5502        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5503        s.validate().unwrap();
5504    }
5505
5506    #[test]
5507    fn validate_simple_one_for_one_forbids_static_children() {
5508        let mut s = SupervisorSpec {
5509            estrategia: RestartStrategy::SimpleOneForOne,
5510            ..SupervisorSpec::default()
5511        };
5512        s.children
5513            .push(child("w", "^0.1", RestartPolicy::Permanent));
5514        assert_eq!(
5515            s.validate().unwrap_err(),
5516            SupervisorError::SimpleOneForOneWithStaticChildren
5517        );
5518        s.children.clear();
5519        s.validate().unwrap();
5520    }
5521
5522    #[test]
5523    fn validate_rejects_zero_max_restarts() {
5524        let s = SupervisorSpec {
5525            max_restarts: 0,
5526            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5527            ..SupervisorSpec::default()
5528        };
5529        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5530    }
5531
5532    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5533    //
5534    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5535    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5536    // `:supervisor :max-restarts` axis — both fields are "trip the
5537    // next-higher protection layer after N events in a rolling window"
5538    // counters with identical degenerate-at-the-high-end shape, so the
5539    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5540    // exactly as it lies in `1..=1000` on the breaker side.
5541
5542    #[test]
5543    fn validate_rejects_max_restarts_above_cap() {
5544        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5545        // 1` is structurally one past the cap and silently passed
5546        // validate on every pre-gate codebase because the typed slot's
5547        // only check was the zero-floor arm. The no-op-supervisor vector
5548        // only surfaced at the runtime substrate (Erlang/OTP
5549        // MaxIntensity/Period ratio, the future wasm-operator's
5550        // per-supervisor restart-intensity counter) far from the source
5551        // caixa.lisp with no field naming the offending supervisor.
5552        let s = SupervisorSpec {
5553            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5554            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5555            ..SupervisorSpec::default()
5556        };
5557        assert_eq!(
5558            s.validate().unwrap_err(),
5559            SupervisorError::MaxRestartsExceedsCap {
5560                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5561            }
5562        );
5563    }
5564
5565    #[test]
5566    fn validate_rejects_max_restarts_far_above_cap() {
5567        // The `u32::MAX` worst case — the four-billion-restart
5568        // threshold a typo (`:max-restarts 4294967295`) or a
5569        // struct-literal copy-paste lands in the slot. Pin the cap
5570        // arm's coverage explicitly across the full `u32` overflow so
5571        // a future relaxation that drops the upper bound surfaces
5572        // here. Same shape every other typed-cap arm on this surface
5573        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5574        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5575        let s = SupervisorSpec {
5576            max_restarts: u32::MAX,
5577            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5578            ..SupervisorSpec::default()
5579        };
5580        assert_eq!(
5581            s.validate().unwrap_err(),
5582            SupervisorError::MaxRestartsExceedsCap {
5583                max_restarts: u32::MAX,
5584            }
5585        );
5586    }
5587
5588    #[test]
5589    fn validate_accepts_max_restarts_at_cap() {
5590        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5591        // must validate. The cap is inclusive on the top edge,
5592        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5593        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5594        // discipline on the sibling capped axes. Pin the boundary
5595        // explicitly so a future off-by-one tightening
5596        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5597        // here as a test failure rather than a silent contract
5598        // narrowing.
5599        let s = SupervisorSpec {
5600            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5601            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5602            ..SupervisorSpec::default()
5603        };
5604        s.validate()
5605            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5606    }
5607
5608    #[test]
5609    fn validate_accepts_max_restarts_typical_values() {
5610        // The documented production-playbook band positive-control
5611        // sweep — every value Erlang/OTP / Elixir / Riak Core /
5612        // RabbitMQ recommend (1..=100) must pass, plus a sweep
5613        // through the hyperscale band (200, 500, 1000) the cap
5614        // accepts. Pin the inclusive validated set explicitly so a
5615        // future tightening of the ceiling surfaces here.
5616        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5617            let s = SupervisorSpec {
5618                max_restarts: n,
5619                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5620                ..SupervisorSpec::default()
5621            };
5622            s.validate()
5623                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5624        }
5625    }
5626
5627    #[test]
5628    fn zero_max_restarts_takes_precedence_over_cap() {
5629        // The cross-arm ordering pin: `0` is structurally outside
5630        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5631        // (cap), but the zero-floor diagnostic is the more
5632        // self-locating one (it directly names the counter-axis
5633        // remediation), so the validate gate must fire on zero first.
5634        // Same shape every other zero-then-shape ordering on this
5635        // surface uses (PolicyRetriesZero then
5636        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5637        // PolicyBreakerMaxFailuresExceedsCap).
5638        let s = SupervisorSpec {
5639            max_restarts: 0,
5640            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5641            ..SupervisorSpec::default()
5642        };
5643        assert_eq!(
5644            s.validate().unwrap_err(),
5645            SupervisorError::ZeroMaxRestarts,
5646            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5647        );
5648    }
5649
5650    #[test]
5651    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5652        // The cross-arm ordering pin between the cap and the sibling
5653        // `:restart-window` gates (zero-window, canonical-window). A
5654        // supervisor carrying both an over-cap `max_restarts` AND a
5655        // structurally invalid window (zero, sub-ms) must surface the
5656        // cap diagnostic first — the cap arm is wired immediately
5657        // after the zero-restart arm and strictly before the window
5658        // arms, so the offending value the diagnostic names matches
5659        // the order the author would discover the gates by reading
5660        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5661        // order so a future refactor that reorders the arms surfaces
5662        // here as a test failure rather than a silent diagnostic
5663        // regression. Peer of
5664        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5665        // on the sibling `:politicas :circuit-breaker` slot.
5666        let s = SupervisorSpec {
5667            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5668            restart_window: Some(Duration::ZERO),
5669            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5670            ..SupervisorSpec::default()
5671        };
5672        assert_eq!(
5673            s.validate().unwrap_err(),
5674            SupervisorError::MaxRestartsExceedsCap {
5675                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5676            },
5677            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5678        );
5679    }
5680
5681    #[test]
5682    fn max_restarts_cap_diagnostic_carries_offending_value() {
5683        // The diagnostic-shape pin: the offending `u32` is carried
5684        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5685        // variant so the surfaced error message names the value the
5686        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5687        // supervisor-policy ceiling …"`), not just the cap. Same
5688        // self-locating diagnostic shape every other typed-cap arm on
5689        // this surface carries
5690        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5691        // the offending failure count verbatim,
5692        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5693        // retries count verbatim).
5694        let s = SupervisorSpec {
5695            max_restarts: 50_000,
5696            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5697            ..SupervisorSpec::default()
5698        };
5699        let err = s.validate().unwrap_err();
5700        assert!(
5701            matches!(
5702                err,
5703                SupervisorError::MaxRestartsExceedsCap {
5704                    max_restarts: 50_000
5705                }
5706            ),
5707            "got {err:?}"
5708        );
5709        let msg = err.to_string();
5710        assert!(
5711            msg.contains("50000"),
5712            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5713        );
5714    }
5715
5716    #[test]
5717    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5718        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5719        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5720        // half of Learn You Some Erlang's worker-supervisor default,
5721        // sibling of the `60s` `Period` half that the paired
5722        // [`Default for SupervisorSpec`] impl already pins on the
5723        // sibling `restart_window` axis. Pinning the literal here
5724        // surfaces a future rebrand (a tightening to Elixir's `3`,
5725        // a widening to a per-cluster overlay the operator pins
5726        // through a future `:max-restarts-overrides` slot) as a
5727        // deliberate test edit, not a silent contract migration.
5728        // Peer of the sibling
5729        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5730        // upper-bracket pin on the same axis.
5731        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5732    }
5733
5734    #[test]
5735    fn default_max_restarts_helper_routes_through_lifted_default() {
5736        // Composition pin: the private `default_max_restarts()`
5737        // serde-`#[serde(default = "…")]` helper on
5738        // [`SupervisorSpec::max_restarts`] must route through the
5739        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5740        // typed `pub const` rather than a raw `5` literal. Prior to
5741        // the lift the helper carried an inline `5` with no compile-
5742        // time link back to the shared default, so the wire-format
5743        // author-omitted arm and the caixa-core
5744        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5745        // arm could silently split on any future default rebrand.
5746        // Byte-parity against the lifted constant closes the split.
5747        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5748    }
5749
5750    #[test]
5751    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5752        // Composition pin: the [`Default for SupervisorSpec`] impl's
5753        // struct-literal `max_restarts` field must route through the
5754        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5755        // typed `pub const` (via the private helper this test's
5756        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5757        // already pins onto the constant). Structurally: every
5758        // `SupervisorSpec::default()` call must yield a
5759        // `max_restarts` field byte-equal to the lifted constant
5760        // (the two paired defaults — the serde-side wire-format arm
5761        // and the struct-literal default arm — cannot silently split
5762        // on any future default rebrand). Peer of the sibling
5763        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5764        // — this pin closes the byte-parity arm on the two paired
5765        // altitude entry points onto the shared substrate constant.
5766        assert_eq!(
5767            SupervisorSpec::default().max_restarts(),
5768            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5769        );
5770    }
5771
5772    #[test]
5773    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5774        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5775        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5776        // Learn You Some Erlang's worker-supervisor default, paired
5777        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5778        // `MaxIntensity` half this constant is the sliding-window
5779        // denominator of on the same `MaxIntensity / Period`
5780        // restart-intensity ratio. Pinning the literal here surfaces a
5781        // future coherent rebrand of the paired default (Elixir's
5782        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5783        // the operator pins through a future
5784        // `:restart-window-overrides` slot) as a deliberate test edit,
5785        // not a silent contract migration. Peer of the sibling
5786        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5787        // paired-half pin on the same OTP-canonical default and the
5788        // [`supervisor_restart_window_cap_pins_canonical_value`]
5789        // upper-bracket pin on the same axis.
5790        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5791    }
5792
5793    #[test]
5794    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5795        // Composition pin: the [`Default for SupervisorSpec`] impl's
5796        // struct-literal `restart_window` field must route through the
5797        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5798        // typed `pub const` rather than a raw
5799        // `Duration::from_secs(60)` literal. Prior to this lift the
5800        // paired `{intensity, 5, 60}` OTP-canonical default was split
5801        // across two altitudes with no compile-time link between the
5802        // halves — the `MaxIntensity` half rode through the lifted
5803        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5804        // `Period` half rode as an open-coded literal at the
5805        // composition site, so a future coherent rebrand of the paired
5806        // canonical would have had to migrate one half through the
5807        // constant and the other through a raw literal in lockstep.
5808        // Byte-parity against the lifted constant on the `Period` half
5809        // closes the split — the paired OTP-canonical default now
5810        // migrates as one unit on any future axis change. Peer of the
5811        // sibling
5812        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5813        // byte-parity pin on the paired `MaxIntensity` half.
5814        assert_eq!(
5815            SupervisorSpec::default().restart_window(),
5816            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5817        );
5818    }
5819
5820    #[test]
5821    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5822        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5823        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5824        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5825        // canonical default, paired with the sibling
5826        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5827        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5828        // this constant is the strategy discriminator of on the same
5829        // OTP-canonical worker-supervisor default. Pinning the arm here
5830        // surfaces a future coherent rebrand of the paired triple (Elixir's
5831        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5832        // intensity/period axes leaving this strategy arm untouched, an OTP
5833        // `rest_for_one` widening once the substrate discovers startup-
5834        // order-coupled child cohorts as the more common worker-supervisor
5835        // shape, a per-cluster overlay the operator pins through a future
5836        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5837        // supervision-canary roadmap acknowledges) as a deliberate test
5838        // edit, not a silent contract migration. Peer of the sibling
5839        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5840        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5841        // paired-half pins on the same OTP-canonical default.
5842        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5843    }
5844
5845    #[test]
5846    fn restart_strategy_default_routes_through_lifted_default() {
5847        // Composition pin: the [`Default for RestartStrategy`] impl's
5848        // return arm must route through the substrate-canonical
5849        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5850        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5851        // an inline `Self::OneForOne` with no compile-time link back to
5852        // the shared OTP-canonical `one_for_one` strategy the paired
5853        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5854        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5855        // `.unwrap_or_default()` (now
5856        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5857        // so a future rebrand of the OTP-canonical strategy default (an
5858        // OTP `rest_for_one` widening once the substrate discovers
5859        // startup-order-coupled child cohorts as the more common worker-
5860        // supervisor shape, a per-cluster overlay the operator pins
5861        // through a future `:estrategia-overrides` slot) would have had to
5862        // be threaded through the `Default` impl and the two peer routes
5863        // in lockstep or the three consumers would silently split. Byte-
5864        // parity against the lifted constant closes the split. Peer of
5865        // the sibling
5866        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5867        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5868        // composition pins on the paired `MaxIntensity` + `Period` halves.
5869        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5870    }
5871
5872    #[test]
5873    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5874        // Composition pin: the [`Default for SupervisorSpec`] impl's
5875        // struct-literal `estrategia` field must route through the
5876        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5877        // `pub const` (either directly, or via the
5878        // [`RestartStrategy::default`] impl that the sibling
5879        // `restart_strategy_default_routes_through_lifted_default` pin
5880        // already routes onto the constant). Structurally: every
5881        // `SupervisorSpec::default()` call must yield an `estrategia`
5882        // field byte-equal to the lifted constant (the three paired
5883        // defaults — the [`Default for RestartStrategy`] impl arm, the
5884        // struct-literal default arm here, and the
5885        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5886        // silently split on any future default rebrand). Peer of the
5887        // sibling
5888        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5889        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5890        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5891        // of the same `SupervisorSpec::default()` composed altitude.
5892        assert_eq!(
5893            SupervisorSpec::default().estrategia(),
5894            SUPERVISOR_ESTRATEGIA_DEFAULT,
5895        );
5896    }
5897
5898    #[test]
5899    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5900        // Composition pin: the [`Default for SupervisorSpec`] impl must
5901        // route through the substrate-canonical
5902        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5903        // rather than a re-hand-authored struct-literal cascade. Sharpens
5904        // the sibling per-arm
5905        // `supervisor_spec_default_*_routes_through_lifted_default` pins
5906        // from a per-field lift into a whole-struct one-source-of-truth
5907        // pin — the derived-until-now [`Default::default`] and the
5908        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5909        // construction, not by coincidence.
5910        //
5911        // A future extension of the OTP-canonical baseline (a fifth
5912        // `restart_intensity` field the Erlang/OTP `#supervisor` record
5913        // grows, a per-child-cohort split of the `restart_window` /
5914        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5915        // CR materializer's admission-time overlay pass) reaches both
5916        // paths through exactly one edit on
5917        // [`SupervisorSpec::otp_canonical`] — the derived path could
5918        // silently disagree with the constructor's shape on any new
5919        // field whose [`Default::default`] resolves to a different arm
5920        // than the OTP-canonical baseline the constructor names, while
5921        // this delegated impl reaches the constructor directly and
5922        // picks up every future extension by construction.
5923        //
5924        // Fourth peer on the M2 / M3 typed-slot-spec
5925        // [`Default`]-through-const-ctor fold family — sibling of the
5926        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5927        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5928        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5929        // (91641a4), and [`crate::BehaviorSpec`]
5930        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5931        // per-`Option`-only-typed-slot folds — extended here onto the
5932        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5933        // is not "everything `None`" but the Erlang/OTP-canonical
5934        // `{one_for_one, 5, 60}` worker-supervisor triple.
5935        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5936    }
5937
5938    #[test]
5939    fn supervisor_spec_otp_canonical_byte_equals_default() {
5940        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5941        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5942        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5943        // pin already asserts against the [`Default::default`] path.
5944        // Sharpens the pair-invariant into a per-constructor pin so a
5945        // future extension of [`SupervisorSpec`] with a fifth field
5946        // whose OTP-canonical shape is non-`Default::default`-equivalent
5947        // trips at caixa-core test time rather than at a downstream
5948        // consumer that composed [`SupervisorSpec::otp_canonical`] with
5949        // [`SupervisorSpec::validate`] as its "canonical baseline
5950        // seed".
5951        let canonical = SupervisorSpec::otp_canonical();
5952        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5953        assert_eq!(canonical.max_restarts, 5);
5954        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5955        assert!(canonical.children.is_empty());
5956    }
5957
5958    #[test]
5959    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5960        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5961        // remain callable from a `const`-bound position so downstream
5962        // `const`-context callers wanting a canonical OTP-baseline seed
5963        // can construct one at compile time without runtime dispatch on
5964        // the derived [`Default::default`]. Peer of the sibling
5965        // `pub const fn` [`crate::LimitsSpec::empty`] /
5966        // [`crate::aplicacao::MeshPolicy::empty`] /
5967        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5968        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5969        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5970        // (a non-`const` field-default helper, a non-`const`-stable
5971        // container type promotion), this evaluation fails at
5972        // build time on this file rather than at a downstream
5973        // `const`-context call site.
5974        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5975        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5976        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5977        assert_eq!(
5978            CANONICAL.restart_window,
5979            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5980        );
5981        assert!(CANONICAL.children.is_empty());
5982    }
5983
5984    #[test]
5985    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5986        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5987        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5988        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5989        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5990        // half of the same OTP-shape supervisor-tree default set whose
5991        // per-`:supervisor` halves the sibling
5992        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5993        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5994        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5995        // arm here surfaces a future rebrand of the per-child default (an
5996        // OTP-`transient` widening once the substrate discovers clean-
5997        // completion-aware children as the more common child shape, a
5998        // per-cluster overlay the operator pins through a future
5999        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
6000        // supervision-canary roadmap acknowledges) as a deliberate test
6001        // edit, not a silent contract migration. Peer of the sibling
6002        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
6003        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
6004        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6005        // value pins on the per-`:supervisor` halves.
6006        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
6007    }
6008
6009    #[test]
6010    fn restart_policy_default_routes_through_lifted_default() {
6011        // Composition pin: the [`Default for RestartPolicy`] impl's return
6012        // arm must route through the substrate-canonical
6013        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
6014        // than a raw `Self::Permanent` arm. Prior to the lift the impl
6015        // carried an inline `Self::Permanent` with no compile-time link
6016        // back to the OTP-shape supervisor-tree default set whose three
6017        // per-`:supervisor` halves already rode through lifted constants
6018        // — so a future coherent rebrand of the set would have had to
6019        // migrate three halves through typed constants and this fourth
6020        // through a raw enum arm in lockstep or the supervisor-level and
6021        // child-level defaults would silently drift apart. Byte-parity
6022        // against the lifted constant closes the split. Peer of the
6023        // sibling
6024        // [`restart_strategy_default_routes_through_lifted_default`]
6025        // composition pin on the per-`:supervisor` `:estrategia` axis.
6026        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
6027    }
6028
6029    #[test]
6030    fn child_spec_serde_default_restart_routes_through_lifted_default() {
6031        // Composition pin: the serde-side `#[serde(default)]` on
6032        // [`ChildSpec::restart`] — the wire-format author-omitted
6033        // `:children :restart` arm — must resolve onto the substrate-
6034        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
6035        // (via the [`Default for RestartPolicy`] impl the sibling
6036        // `restart_policy_default_routes_through_lifted_default` pin
6037        // already routes onto the constant). Structurally: a `ChildSpec`
6038        // deserialized from a payload that omits the `restart` key must
6039        // yield a `restart` field byte-equal to the lifted constant, so
6040        // the wire-format author-omitted arm and the
6041        // [`RestartPolicy::default`] impl arm cannot silently split on any
6042        // future default rebrand. Peer of the sibling
6043        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
6044        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6045        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6046        // byte-parity pins on the per-`:supervisor` halves of the same
6047        // author-omitted-slot resolution surface.
6048        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
6049            .expect("ChildSpec must deserialize with the restart key omitted");
6050        assert_eq!(
6051            omitted.restart(),
6052            SUPERVISOR_CHILD_RESTART_DEFAULT,
6053            "an author-omitted :children :restart slot must degrade onto \
6054             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
6055             {:?}, expected {:?})",
6056            omitted.restart(),
6057            SUPERVISOR_CHILD_RESTART_DEFAULT,
6058        );
6059    }
6060
6061    #[test]
6062    fn supervisor_max_restarts_cap_pins_canonical_value() {
6063        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
6064        // 1000 — the same ceiling the peer
6065        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
6066        // `:politicas :circuit-breaker :max-failures` axis (both are
6067        // "trip the next-higher protection layer after N events in a
6068        // rolling window" counters with identical
6069        // degenerate-at-the-high-end shape; uniform top edge so the
6070        // M4 CR materializers and the wasm-operator reconciler reach
6071        // for either field knowing the value is in `1..=1000`). Two
6072        // orders of magnitude above every documented Erlang/OTP /
6073        // Elixir / Riak Core / RabbitMQ production-playbook
6074        // recommendation band and below the clearly-pathological
6075        // "effectively no escalation" floor (10_000, 100_000,
6076        // u32::MAX). Pinning the literal value here surfaces a future
6077        // drift (a relaxation to 10_000, a tightening to 100) as a
6078        // deliberate test edit, not a silent contract narrowing.
6079        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
6080    }
6081
6082    #[test]
6083    fn validate_rejects_empty_child_name() {
6084        let s = SupervisorSpec {
6085            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6086            ..SupervisorSpec::default()
6087        };
6088        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
6089    }
6090
6091    #[test]
6092    fn validate_rejects_empty_child_version() {
6093        let s = SupervisorSpec {
6094            children: vec![child("w", "", RestartPolicy::Permanent)],
6095            ..SupervisorSpec::default()
6096        };
6097        assert!(matches!(
6098            s.validate().unwrap_err(),
6099            SupervisorError::EmptyChildVersion { .. }
6100        ));
6101    }
6102
6103    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
6104
6105    #[test]
6106    fn validate_rejects_invalid_child_versao_requirement() {
6107        // The fail-before-pass-after pin: a non-empty but malformed
6108        // semver requirement (`"^bad-version"`) silently passed
6109        // `validate()` on every pre-gate codebase because the prior
6110        // shape only refused the empty string. The parse failure
6111        // surfaced far downstream at lacre-resolve time with a
6112        // `semver::Error` that didn't name which `:children` entry
6113        // carried the typo. The new gate moves the check to caixa-build
6114        // time at the source caixa.lisp — the third `:versao` typed
6115        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
6116        // structural parity.
6117        let s = SupervisorSpec {
6118            children: vec![
6119                child("worker", "^0.1", RestartPolicy::Permanent),
6120                child("cache", "^bad-version", RestartPolicy::Transient),
6121            ],
6122            ..SupervisorSpec::default()
6123        };
6124        let err = s.validate().unwrap_err();
6125        assert!(
6126            matches!(
6127                err,
6128                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6129                    if caixa == "cache" && versao == "^bad-version"
6130            ),
6131            "got {err:?}"
6132        );
6133    }
6134
6135    #[test]
6136    fn validate_rejects_child_versao_with_double_caret_typo() {
6137        // `"^^0.1"` is the canonical doubled-caret typo — looks
6138        // Cargo-shaped on first glance but fails the parser because
6139        // semver doesn't accept stacked operators. Pin this
6140        // adjacent-shape footgun explicitly so a future relaxation that
6141        // accepts "looks-canonical-but-isn't" forms surfaces here.
6142        let s = SupervisorSpec {
6143            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
6144            ..SupervisorSpec::default()
6145        };
6146        let err = s.validate().unwrap_err();
6147        assert!(
6148            matches!(
6149                err,
6150                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6151                    if caixa == "worker" && versao == "^^0.1"
6152            ),
6153            "got {err:?}"
6154        );
6155    }
6156
6157    #[test]
6158    fn validate_rejects_child_versao_with_v_prefixed_tag() {
6159        // `"v0.1"` is the canonical "git-tag-shape leaking into the
6160        // semver requirement slot" typo — an author copies the
6161        // publish-side git-tag string verbatim into `:versao`, but
6162        // Cargo's semver parser rejects the leading `v`. Same
6163        // adjacent-shape footgun pinned for `:membros :versao`
6164        // (9888b13).
6165        let s = SupervisorSpec {
6166            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
6167            ..SupervisorSpec::default()
6168        };
6169        let err = s.validate().unwrap_err();
6170        assert!(
6171            matches!(
6172                err,
6173                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6174                    if caixa == "worker" && versao == "v0.1"
6175            ),
6176            "got {err:?}"
6177        );
6178    }
6179
6180    #[test]
6181    fn validate_accepts_canonical_child_versao_forms() {
6182        // The Cargo-shaped requirement forms `:deps :versao` and
6183        // `:membros :versao` already accept via
6184        // `crate::parse_requirement` must pass the children gate
6185        // without re-validating at the resolver layer. Pin every leg so
6186        // a future tightening of the canonical set surfaces here as a
6187        // test failure.
6188        for form in [
6189            "^0.1",      // caret — minor-range pin (the most common shape)
6190            "~0.1.2",    // tilde — patch-range pin
6191            "0.1.0",     // exact — single-version pin
6192            "*",         // wildcard — any version (semver::VersionReq::STAR)
6193            ">=0.1, <2", // multi-range — comma-separated comparators
6194        ] {
6195            let s = SupervisorSpec {
6196                children: vec![child("worker", form, RestartPolicy::Permanent)],
6197                ..SupervisorSpec::default()
6198            };
6199            s.validate()
6200                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6201        }
6202    }
6203
6204    #[test]
6205    fn child_versao_empty_takes_precedence_over_invalid() {
6206        // Order pin: the existing `EmptyChildVersion` diagnostic (which
6207        // doesn't try to parse) fires before the new
6208        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
6209        // `:versao` keeps its narrower error message —
6210        // `parse_requirement` would also reject `""`, but the
6211        // empty-string arm is the more self-locating diagnostic for the
6212        // author. Same ordering discipline as
6213        // `membro_versao_empty_takes_precedence_over_invalid` in
6214        // aplicacao.rs.
6215        let s = SupervisorSpec {
6216            children: vec![child("worker", "", RestartPolicy::Permanent)],
6217            ..SupervisorSpec::default()
6218        };
6219        let err = s.validate().unwrap_err();
6220        assert!(
6221            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
6222            "got {err:?}"
6223        );
6224    }
6225
6226    #[test]
6227    fn child_versao_invalid_fires_before_duplicate_check() {
6228        // Order pin: a malformed requirement on a non-duplicate entry
6229        // surfaces *its own* diagnostic (which names the offending
6230        // `:versao` string), even when a later entry would otherwise
6231        // collapse onto an earlier name. The per-entry shape gate runs
6232        // inline before the duplicate-key insert — parallel to
6233        // `membro_versao_invalid_fires_before_duplicate_check` in
6234        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
6235        let s = SupervisorSpec {
6236            children: vec![
6237                child("worker", "^bad", RestartPolicy::Permanent),
6238                child("cache", "^0.1", RestartPolicy::Transient),
6239                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6240            ],
6241            ..SupervisorSpec::default()
6242        };
6243        let err = s.validate().unwrap_err();
6244        assert!(
6245            matches!(
6246                err,
6247                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
6248            ),
6249            "got {err:?}"
6250        );
6251    }
6252
6253    #[test]
6254    fn child_versao_invalid_diagnostic_carries_offending_versao() {
6255        // The diagnostic-shape pin: the error names the offending
6256        // `:versao` value verbatim so the author can grep their
6257        // caixa.lisp without re-running the build, and carries a
6258        // non-empty `reason` from `semver::VersionReq::parse` so the
6259        // parser's own wording flows through to the diagnostic.
6260        let s = SupervisorSpec {
6261            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
6262            ..SupervisorSpec::default()
6263        };
6264        let err = s.validate().unwrap_err();
6265        let SupervisorError::ChildVersaoInvalid {
6266            caixa,
6267            versao,
6268            reason,
6269        } = err
6270        else {
6271            panic!("expected ChildVersaoInvalid, got other variant");
6272        };
6273        assert_eq!(caixa, "worker");
6274        assert_eq!(versao, "not-a-req");
6275        assert!(
6276            !reason.is_empty(),
6277            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
6278        );
6279    }
6280
6281    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
6282
6283    #[test]
6284    fn validate_rejects_child_caixa_with_uppercase() {
6285        // The canonical "I copied the Servico's display name verbatim"
6286        // typo — child caixa names are lowercase per K8s DNS-1123 label
6287        // rule. The diagnostic names the offending name and suggests the
6288        // lower-cased fix in one edit, mirroring the
6289        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
6290        let s = SupervisorSpec {
6291            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
6292            ..SupervisorSpec::default()
6293        };
6294        let err = s.validate().unwrap_err();
6295        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6296            panic!("expected ChildCaixaInvalid, got other variant");
6297        };
6298        assert_eq!(caixa, "Worker");
6299        assert!(
6300            reason.contains("uppercase"),
6301            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
6302        );
6303        assert!(
6304            reason.contains("\"worker\""),
6305            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
6306        );
6307    }
6308
6309    #[test]
6310    fn validate_rejects_child_caixa_with_underscore() {
6311        // The canonical "I'm thinking of a Python module / Postgres
6312        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
6313        // label schema. K8s rejects `metadata.name: my_worker` at
6314        // admission time with an opaque `field is invalid` (no source-
6315        // citing diagnostic). The gate moves it to caixa-build time.
6316        let s = SupervisorSpec {
6317            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
6318            ..SupervisorSpec::default()
6319        };
6320        let err = s.validate().unwrap_err();
6321        assert!(
6322            matches!(
6323                err,
6324                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6325                    if caixa == "my_worker" && reason.contains('_')
6326            ),
6327            "got {err:?}"
6328        );
6329    }
6330
6331    #[test]
6332    fn validate_rejects_child_caixa_with_dot() {
6333        // A `:children :caixa` entry is a single DNS-1123 label, not a
6334        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6335        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6336        // (3f9d7a0) on the peer name axis.
6337        let s = SupervisorSpec {
6338            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6339            ..SupervisorSpec::default()
6340        };
6341        let err = s.validate().unwrap_err();
6342        assert!(
6343            matches!(
6344                err,
6345                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6346                    if caixa == "team.worker" && reason.contains('.')
6347            ),
6348            "got {err:?}"
6349        );
6350    }
6351
6352    #[test]
6353    fn validate_rejects_child_caixa_with_leading_hyphen() {
6354        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6355        // with an alphanumeric. The K8s apiserver rejects `-worker`
6356        // outright; the renderer would emit a `metadata.name: "-worker"`
6357        // that fails admission far from the source caixa.lisp.
6358        let s = SupervisorSpec {
6359            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6360            ..SupervisorSpec::default()
6361        };
6362        let err = s.validate().unwrap_err();
6363        assert!(
6364            matches!(
6365                err,
6366                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6367                    if caixa == "-worker" && reason.contains("start and end")
6368            ),
6369            "got {err:?}"
6370        );
6371    }
6372
6373    #[test]
6374    fn validate_rejects_child_caixa_with_trailing_hyphen() {
6375        // The symmetric arm of the boundary rule. Pin separately so
6376        // both ends of the label are covered against a future relaxation
6377        // that only checks one boundary.
6378        let s = SupervisorSpec {
6379            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6380            ..SupervisorSpec::default()
6381        };
6382        let err = s.validate().unwrap_err();
6383        assert!(
6384            matches!(
6385                err,
6386                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6387                    if caixa == "worker-"
6388            ),
6389            "got {err:?}"
6390        );
6391    }
6392
6393    #[test]
6394    fn validate_rejects_child_caixa_with_unicode() {
6395        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6396        // (`xn--…`) by the author before it reaches K8s. The byte-by-
6397        // byte ASCII validity check rejects multi-byte UTF-8 sequences
6398        // by the first byte that fails the `[a-z0-9-]` predicate.
6399        let s = SupervisorSpec {
6400            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6401            ..SupervisorSpec::default()
6402        };
6403        let err = s.validate().unwrap_err();
6404        assert!(
6405            matches!(
6406                err,
6407                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6408                    if caixa == "café"
6409            ),
6410            "got {err:?}"
6411        );
6412    }
6413
6414    #[test]
6415    fn validate_rejects_child_caixa_with_whitespace() {
6416        // Whitespace is the canonical "I pasted from a sketch / doc"
6417        // footgun. The apiserver rejects every `metadata.name` value
6418        // carrying whitespace; pin the gate fires at the right boundary.
6419        let s = SupervisorSpec {
6420            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6421            ..SupervisorSpec::default()
6422        };
6423        let err = s.validate().unwrap_err();
6424        assert!(
6425            matches!(
6426                err,
6427                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6428                    if caixa == "my worker"
6429            ),
6430            "got {err:?}"
6431        );
6432    }
6433
6434    #[test]
6435    fn validate_rejects_child_caixa_too_long() {
6436        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6437        // 63 bytes; the K8s apiserver rejects every `metadata.name`
6438        // axis over the limit at admission time. The diagnostic names
6439        // both the cap and the actual length so the author can shorten
6440        // in one edit, mirroring `rejects_membro_caixa_too_long`
6441        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6442        let too_long = "a".repeat(64);
6443        let s = SupervisorSpec {
6444            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6445            ..SupervisorSpec::default()
6446        };
6447        let err = s.validate().unwrap_err();
6448        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6449            panic!("expected ChildCaixaInvalid, got other variant");
6450        };
6451        assert_eq!(caixa, too_long);
6452        assert!(
6453            reason.contains("63"),
6454            "diagnostic must name the 63-byte cap (got: {reason:?})"
6455        );
6456        assert!(
6457            reason.contains("64"),
6458            "diagnostic must name the actual length (got: {reason:?})"
6459        );
6460    }
6461
6462    #[test]
6463    fn child_caixa_max_length_validates() {
6464        // The 63-byte boundary control pin — exactly-at-the-cap is
6465        // accepted, mirroring `membro_caixa_max_length_validates`
6466        // (3f9d7a0) and `placement_cluster_max_length_validates`
6467        // (6cbb900). Pinned separately so a future off-by-one tightening
6468        // surfaces here.
6469        let max_label = "a".repeat(63);
6470        let s = SupervisorSpec {
6471            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6472            ..SupervisorSpec::default()
6473        };
6474        s.validate().unwrap();
6475    }
6476
6477    #[test]
6478    fn validate_accepts_canonical_child_caixa_forms() {
6479        // The realistic shapes a supervised child's `:caixa` carries —
6480        // single-word `worker`, version-suffixed `cache-v2`, single-char
6481        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6482        // `payment-retry`, all-digit `0`. Pin every leg so a future
6483        // tightening (e.g. requiring a leading lowercase letter) surfaces
6484        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6485        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6486        // (6cbb900).
6487        for form in [
6488            "worker",
6489            "cache-v2",
6490            "a",
6491            "db",
6492            "2-pool",
6493            "payment-retry",
6494            "0",
6495        ] {
6496            let s = SupervisorSpec {
6497                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6498                ..SupervisorSpec::default()
6499            };
6500            s.validate()
6501                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6502        }
6503    }
6504
6505    #[test]
6506    fn child_caixa_empty_takes_precedence_over_invalid() {
6507        // Order pin: the existing `EmptyChildName` diagnostic (which
6508        // doesn't try to parse the DNS-1123 shape) fires before the new
6509        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6510        // its narrower error message — `is_dns_1123_label` would reject
6511        // the empty string too (boundary check on the first byte), but
6512        // the empty-string arm is the more self-locating diagnostic for
6513        // the author. Same ordering discipline as
6514        // `membro_caixa_empty_takes_precedence_over_invalid` in
6515        // aplicacao.rs.
6516        let s = SupervisorSpec {
6517            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6518            ..SupervisorSpec::default()
6519        };
6520        let err = s.validate().unwrap_err();
6521        assert_eq!(err, SupervisorError::EmptyChildName);
6522    }
6523
6524    #[test]
6525    fn child_caixa_invalid_fires_before_versao_check() {
6526        // Order pin: the per-axis shape gate runs inline before the
6527        // per-entry versao check, so a malformed `:caixa` on an entry
6528        // whose `:versao` would also fail surfaces the more self-
6529        // locating name-axis diagnostic first. Parallel to
6530        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6531        // and `placement_cluster_invalid_fires_before_duplicate_check`
6532        // (6cbb900).
6533        let s = SupervisorSpec {
6534            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6535            ..SupervisorSpec::default()
6536        };
6537        let err = s.validate().unwrap_err();
6538        assert!(
6539            matches!(
6540                err,
6541                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6542            ),
6543            "got {err:?}"
6544        );
6545    }
6546
6547    #[test]
6548    fn child_caixa_invalid_fires_before_duplicate_check() {
6549        // Order pin: a malformed name on a non-duplicate entry surfaces
6550        // its own diagnostic, even when a later entry would otherwise
6551        // collapse onto an earlier name. The per-entry shape gate runs
6552        // inline before the duplicate-key HashSet insert, mirroring
6553        // `placement_cluster_invalid_fires_before_duplicate_check`
6554        // (6cbb900).
6555        let s = SupervisorSpec {
6556            children: vec![
6557                child("Worker", "^0.1", RestartPolicy::Permanent),
6558                child("cache", "^0.1", RestartPolicy::Transient),
6559                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6560            ],
6561            ..SupervisorSpec::default()
6562        };
6563        let err = s.validate().unwrap_err();
6564        assert!(
6565            matches!(
6566                err,
6567                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6568            ),
6569            "got {err:?}"
6570        );
6571    }
6572
6573    #[test]
6574    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6575        // The diagnostic-shape pin: the error names the offending
6576        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6577        // the author can grep their caixa.lisp without re-running the
6578        // build. Mirrors the diagnostic-shape sweep on every prior
6579        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6580        let s = SupervisorSpec {
6581            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6582            ..SupervisorSpec::default()
6583        };
6584        let err = s.validate().unwrap_err();
6585        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6586            panic!("expected ChildCaixaInvalid, got other variant");
6587        };
6588        assert_eq!(caixa, "My_Worker");
6589        assert!(
6590            !reason.is_empty(),
6591            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6592        );
6593    }
6594
6595    // ── value-shape: zero restart_window + duplicate child names ──────────
6596
6597    #[test]
6598    fn validate_accepts_none_restart_window() {
6599        // Omitted `:restart-window` is the "never reset" sentinel —
6600        // valid by design. Mirrors :limits axes where None = unbounded.
6601        let s = SupervisorSpec {
6602            restart_window: None,
6603            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6604            ..SupervisorSpec::default()
6605        };
6606        s.validate().unwrap();
6607    }
6608
6609    #[test]
6610    fn validate_rejects_zero_restart_window() {
6611        // Same "0 means the opposite of what you think" footgun closed
6612        // for :politicas :timeout (Envoy treats 0s as infinite) and
6613        // :limits :wall-clock (wasmtime traps before the call starts).
6614        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6615        let s = SupervisorSpec {
6616            restart_window: Some(Duration::ZERO),
6617            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6618            ..SupervisorSpec::default()
6619        };
6620        assert_eq!(
6621            s.validate().unwrap_err(),
6622            SupervisorError::RestartWindowZero
6623        );
6624    }
6625
6626    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6627    //
6628    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6629    // the integer-millisecond canonical-form gate — peer with
6630    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6631    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6632    // path is already gated at the shared codec layer (see
6633    // `restart_window_serde_rejects_fractional_seconds`); this arm
6634    // closes the programmatic-struct-literal path the codec gate can't
6635    // see.
6636
6637    #[test]
6638    fn validate_rejects_sub_millisecond_restart_window() {
6639        // The fail-before-pass-after pin: a programmatic
6640        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6641        // `validate` on every pre-gate codebase, then truncated to
6642        // `as_millis() == 1` on first serialize — the shared codec
6643        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6644        // 1_000_000 ns, the typed `restart_window` no longer matches
6645        // its rendered form.
6646        let s = SupervisorSpec {
6647            restart_window: Some(Duration::from_micros(1500)),
6648            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6649            ..SupervisorSpec::default()
6650        };
6651        match s.validate().unwrap_err() {
6652            SupervisorError::RestartWindowNotCanonical { window } => {
6653                assert_eq!(window, Duration::from_micros(1500));
6654            }
6655            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6656        }
6657    }
6658
6659    #[test]
6660    fn validate_rejects_one_nanosecond_restart_window() {
6661        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6662        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6663        // so the shared codec emits the literal `"0s"` — the next
6664        // serde round-trip would parse back to `Duration::ZERO`, which
6665        // the `RestartWindowZero` arm then rejects on re-validate. The
6666        // canonical-form gate at this layer surfaces a self-locating
6667        // diagnostic naming the offending Duration verbatim rather
6668        // than a downstream `RestartWindowZero` whose remediation
6669        // points at omitting the slot.
6670        let s = SupervisorSpec {
6671            restart_window: Some(Duration::from_nanos(1)),
6672            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6673            ..SupervisorSpec::default()
6674        };
6675        match s.validate().unwrap_err() {
6676            SupervisorError::RestartWindowNotCanonical { window } => {
6677                assert_eq!(window, Duration::from_nanos(1));
6678            }
6679            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6680        }
6681    }
6682
6683    #[test]
6684    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6685        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6686        // 1_000_001 ns is structurally past the integer-ms granularity
6687        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6688        // trip would truncate to `1ms` and the consumer would observe
6689        // a 1-ns drift on every emit. Same boundary the peer
6690        // `validate_rejects_nanosecond_past_canonical_boundary` test
6691        // in limits.rs pins for the `:limits :wall-clock` axis.
6692        let w = Duration::from_nanos(1_000_001);
6693        let s = SupervisorSpec {
6694            restart_window: Some(w),
6695            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6696            ..SupervisorSpec::default()
6697        };
6698        assert_eq!(
6699            s.validate().unwrap_err(),
6700            SupervisorError::RestartWindowNotCanonical { window: w }
6701        );
6702    }
6703
6704    #[test]
6705    fn validate_accepts_integer_millisecond_restart_window_values() {
6706        // The positive-control sweep: every `Duration` the shared
6707        // codec can round-trip losslessly — the canonical
6708        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6709        // pair emits and accepts — passes `validate` without
6710        // surfacing the new canonical-form arm. Mirrors
6711        // `validate_accepts_integer_millisecond_wall_clock_values` on
6712        // the sibling `:limits :wall-clock` axis.
6713        for w in [
6714            Duration::from_millis(1),
6715            Duration::from_millis(500),
6716            Duration::from_millis(1500),
6717            Duration::from_secs(1),
6718            Duration::from_secs(30),
6719            Duration::from_secs(60),
6720            Duration::from_secs(120),
6721            Duration::from_secs(3600),
6722        ] {
6723            let s = SupervisorSpec {
6724                restart_window: Some(w),
6725                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6726                ..SupervisorSpec::default()
6727            };
6728            s.validate()
6729                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6730        }
6731    }
6732
6733    #[test]
6734    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6735        // Cross-arm ordering pin: `Duration::ZERO` has
6736        // `subsec_nanos() == 0` and would otherwise pass the
6737        // canonical-form arm — the zero-floor arm must fire first so
6738        // the more self-locating `RestartWindowZero` diagnostic (with
6739        // its omit-axis remediation directly named) leads. Same
6740        // posture every peer zero-then-shape gate uses
6741        // (`WallClockZero` → `WallClockNotCanonical`,
6742        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6743        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6744        let s = SupervisorSpec {
6745            restart_window: Some(Duration::ZERO),
6746            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6747            ..SupervisorSpec::default()
6748        };
6749        assert_eq!(
6750            s.validate().unwrap_err(),
6751            SupervisorError::RestartWindowZero
6752        );
6753    }
6754
6755    #[test]
6756    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6757        // Diagnostic-shape pin: the canonical-form arm names the
6758        // offending `Duration` verbatim so the author's grep lands on
6759        // the field's value, not a generic "duration not canonical"
6760        // message. Same shape every other typed-canonical-form arm
6761        // on this surface carries (`WallClockNotCanonical` carries
6762        // the offending `Duration` verbatim,
6763        // `PolicyTimeoutNotCanonical` carries the offending
6764        // `Duration` verbatim).
6765        let w = Duration::from_micros(500);
6766        let s = SupervisorSpec {
6767            restart_window: Some(w),
6768            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6769            ..SupervisorSpec::default()
6770        };
6771        let err = s.validate().unwrap_err();
6772        let msg = err.to_string();
6773        assert!(
6774            msg.contains("500"),
6775            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6776        );
6777        assert!(
6778            msg.contains("sub-millisecond"),
6779            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6780        );
6781    }
6782
6783    #[test]
6784    fn restart_window_validated_value_round_trips_through_codec() {
6785        // The structural property the canonical-ms gate enforces:
6786        // every `SupervisorSpec::restart_window` past
6787        // `SupervisorSpec::validate` round-trips losslessly through
6788        // the shared duration codec (serialize → string →
6789        // deserialize → equal value). Pin this end-to-end so a future
6790        // change to either side (the validate gate's accepted
6791        // granularity, the codec's parse/render unit set) that breaks
6792        // the alignment surfaces here. Peer of
6793        // `wall_clock_validated_value_round_trips_through_codec` on
6794        // the sibling `:limits :wall-clock` axis.
6795        for w in [
6796            Duration::from_millis(1),
6797            Duration::from_millis(1500),
6798            Duration::from_secs(30),
6799            Duration::from_secs(3600),
6800        ] {
6801            let s = SupervisorSpec {
6802                restart_window: Some(w),
6803                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6804                ..SupervisorSpec::default()
6805            };
6806            s.validate().unwrap();
6807            let json = serde_json::to_string(&s).unwrap();
6808            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6809            assert_eq!(back.restart_window, Some(w));
6810        }
6811    }
6812
6813    // ── value-shape: upper cap on :restart-window ─────────────────────────
6814    //
6815    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6816    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6817    // `:politicas :timeout` (2e8ee7e), and `:politicas
6818    // :circuit-breaker :window` (379a814). Brackets the typed
6819    // `:restart-window` axis structurally: every validated value lies
6820    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6821    // granularity, closing the
6822    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6823    // zero-floor-and-canonical-form-only checks left open.
6824
6825    #[test]
6826    fn validate_rejects_restart_window_above_cap() {
6827        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6828        // structurally one canonical-tick past the
6829        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6830        // integer-millisecond magnitude the canonical-form arm above
6831        // accepts cleanly, that the shared duration codec round-trips
6832        // losslessly as `"3601s"`, and that silently passed validate on
6833        // every pre-gate codebase because the typed slot's only checks
6834        // were the zero-floor and canonical-form arms. The runtime
6835        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6836        // Period reconciler, the future wasm-operator's per-supervisor
6837        // restart-intensity counter) reaches for a `Duration` so long
6838        // no realistic restart-recovery pattern resets the counter,
6839        // far from the source caixa.lisp.
6840        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6841        let s = SupervisorSpec {
6842            restart_window: Some(w),
6843            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6844            ..SupervisorSpec::default()
6845        };
6846        assert_eq!(
6847            s.validate().unwrap_err(),
6848            SupervisorError::RestartWindowExceedsCap { window: w }
6849        );
6850    }
6851
6852    #[test]
6853    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6854        // Boundary case: exactly 1ms past the cap (the granularity the
6855        // canonical-form gate enforces). Catches a future "strictly
6856        // less than" half-measure and pins the diagnostic to name the
6857        // offending `Duration` verbatim. Peer of
6858        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6859        // `rejects_policy_timeout_one_millisecond_above_cap` /
6860        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6861        // on the sibling typed-`Duration` axes' top edges.
6862        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6863        let s = SupervisorSpec {
6864            restart_window: Some(w),
6865            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6866            ..SupervisorSpec::default()
6867        };
6868        assert_eq!(
6869            s.validate().unwrap_err(),
6870            SupervisorError::RestartWindowExceedsCap { window: w }
6871        );
6872    }
6873
6874    #[test]
6875    fn validate_rejects_restart_window_far_above_cap() {
6876        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6877        // `(:restart-window "7d")`, or any "I want a lifetime counter
6878        // but wrote a `<integer>h` magnitude anyway" typo — values the
6879        // canonical-form arm accepts as integer-millisecond magnitudes,
6880        // the codec round-trips losslessly through serde, but the
6881        // operator's `MaxIntensity / Period` reconciler cannot honor
6882        // as a meaningful rolling window. Until this gate landed
6883        // validate accepted them. Pin the common above-cap values (24h,
6884        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6885        // surfaces here.
6886        for w in [
6887            Duration::from_secs(86_400),    // 24h
6888            Duration::from_secs(604_800),   // 7d
6889            Duration::from_secs(1_000_000), // ~11.5 days
6890        ] {
6891            let s = SupervisorSpec {
6892                restart_window: Some(w),
6893                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6894                ..SupervisorSpec::default()
6895            };
6896            assert_eq!(
6897                s.validate().unwrap_err(),
6898                SupervisorError::RestartWindowExceedsCap { window: w }
6899            );
6900        }
6901    }
6902
6903    #[test]
6904    fn validate_accepts_restart_window_at_cap() {
6905        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6906        // (1h) — must validate. The cap is inclusive on the top edge,
6907        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6908        // [`crate::POLICY_TIMEOUT_MAX`] /
6909        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6910        // capped axes. Pin the boundary explicitly so a future
6911        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6912        // instead of `>`) surfaces here as a test failure rather than a
6913        // silent contract narrowing.
6914        let s = SupervisorSpec {
6915            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6916            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6917            ..SupervisorSpec::default()
6918        };
6919        s.validate()
6920            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6921    }
6922
6923    #[test]
6924    fn validate_accepts_restart_window_typical_values() {
6925        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6926        // per-supervisor production-playbook band positive-control
6927        // sweep — every value Learn You Some Erlang's `{intensity, 5,
6928        // 60}` worker-supervisor `Period = 60s` default, Elixir's
6929        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6930        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6931        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6932        // default recommend (5s..=300s) must pass, plus a sweep
6933        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6934        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6935        // on the sibling `:limits :wall-clock` axis.
6936        for w in [
6937            Duration::from_millis(1),
6938            Duration::from_millis(500),
6939            Duration::from_secs(1),
6940            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
6941            Duration::from_secs(10), // Riak Core lower
6942            Duration::from_secs(30),
6943            Duration::from_secs(60),  // Learn You Some Erlang default
6944            Duration::from_secs(120), // OTP supervisor MaxT typical
6945            Duration::from_secs(300), // Riak Core upper
6946            Duration::from_secs(900), // 15m
6947            Duration::from_secs(1800),
6948            Duration::from_secs(3600), // exactly 1h, the cap
6949        ] {
6950            let s = SupervisorSpec {
6951                restart_window: Some(w),
6952                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6953                ..SupervisorSpec::default()
6954            };
6955            s.validate()
6956                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6957        }
6958    }
6959
6960    #[test]
6961    fn restart_window_zero_takes_precedence_over_cap() {
6962        // The cross-arm ordering pin: `Duration::ZERO` is structurally
6963        // outside both `>= 1ms` (zero-floor) and `<=
6964        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6965        // diagnostic is the more self-locating one (it directly names
6966        // the omit-axis remediation), so the validate gate must fire
6967        // on zero first. Same shape every other zero-then-cap ordering
6968        // on this surface uses (`WallClockZero` then
6969        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6970        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6971        // `PolicyBreakerWindowExceedsCap`).
6972        let s = SupervisorSpec {
6973            restart_window: Some(Duration::ZERO),
6974            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6975            ..SupervisorSpec::default()
6976        };
6977        assert_eq!(
6978            s.validate().unwrap_err(),
6979            SupervisorError::RestartWindowZero,
6980            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6981        );
6982    }
6983
6984    #[test]
6985    fn restart_window_canonical_takes_precedence_over_cap() {
6986        // The cross-arm ordering pin: a `Duration` that is *both*
6987        // sub-millisecond (non-canonical-form) and structurally above
6988        // the cap surfaces the canonical-form diagnostic first,
6989        // because the round-trip-shape break is the more fundamental
6990        // issue (the value can't even round-trip through the codec,
6991        // so the cap diagnostic naming `1ms..=1h` would be misleading
6992        // — there's no integer-ms form of the offending value). Pin
6993        // the order so a future refactor that reorders the arms
6994        // surfaces here as a test failure rather than a silent
6995        // diagnostic regression. Peer of
6996        // `wall_clock_canonical_takes_precedence_over_cap` /
6997        // `policy_timeout_canonical_takes_precedence_over_cap`.
6998        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6999        let s = SupervisorSpec {
7000            restart_window: Some(w),
7001            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7002            ..SupervisorSpec::default()
7003        };
7004        assert_eq!(
7005            s.validate().unwrap_err(),
7006            SupervisorError::RestartWindowNotCanonical { window: w },
7007            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
7008        );
7009    }
7010
7011    #[test]
7012    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
7013        // The cross-arm ordering pin between the `:max-restarts` cap
7014        // and the sibling `:restart-window` cap. A supervisor carrying
7015        // both an over-cap `max_restarts` AND an over-cap window must
7016        // surface the `MaxRestartsExceedsCap` diagnostic first — the
7017        // cap arm is wired immediately after the zero-restart arm and
7018        // strictly before every window-axis arm (zero / canonical /
7019        // cap), so the offending value the diagnostic names matches
7020        // the order the author would discover the gates by reading
7021        // top-to-bottom through `SupervisorSpec::validate`. Pin the
7022        // order so a future refactor that reorders the arms surfaces
7023        // here as a test failure rather than a silent diagnostic
7024        // regression. Peer of
7025        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
7026        // on the sibling zero / canonical window arms.
7027        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
7028        let s = SupervisorSpec {
7029            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7030            restart_window: Some(w),
7031            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7032            ..SupervisorSpec::default()
7033        };
7034        assert_eq!(
7035            s.validate().unwrap_err(),
7036            SupervisorError::MaxRestartsExceedsCap {
7037                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7038            },
7039            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
7040        );
7041    }
7042
7043    #[test]
7044    fn restart_window_cap_diagnostic_carries_offending_value() {
7045        // The diagnostic-shape pin: the offending `Duration` is
7046        // carried verbatim into the
7047        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
7048        // surfaced error message names the value the author wrote,
7049        // not just the cap. Same self-locating diagnostic shape every
7050        // other typed-cap arm on this surface carries
7051        // (`WallClockExceedsCap` carries the offending `Duration`
7052        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
7053        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
7054        // the offending `Duration` verbatim).
7055        let w = Duration::from_secs(7200); // 2h
7056        let s = SupervisorSpec {
7057            restart_window: Some(w),
7058            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7059            ..SupervisorSpec::default()
7060        };
7061        let err = s.validate().unwrap_err();
7062        assert!(
7063            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
7064            "got {err:?}"
7065        );
7066        let msg = err.to_string();
7067        assert!(
7068            msg.contains("7200"),
7069            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
7070        );
7071    }
7072
7073    #[test]
7074    fn supervisor_restart_window_cap_pins_canonical_value() {
7075        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
7076        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
7077        // shared duration codec emits as a clean canonical string
7078        // (`"<n>h"`). Pinning the literal value here surfaces a future
7079        // drift (a relaxation to 24h, a tightening to 5m) as a
7080        // deliberate test edit, not a silent contract narrowing.
7081        //
7082        // The four typed-`Duration` caps on the validation surface
7083        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
7084        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
7085        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
7086        // single uniform top edge at the codec's largest emitted unit
7087        // — a structural-property invariant the equality assertions
7088        // here enshrine, so a future drift on any of the four
7089        // surfaces as a deliberate test edit. Same shape every other
7090        // typed-cap value pin uses
7091        // (`wall_clock_cap_pins_canonical_value`,
7092        // `policy_timeout_cap_pins_canonical_value`,
7093        // `circuit_breaker_window_cap_pins_canonical_value`).
7094        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
7095        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
7096        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
7097        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
7098        assert_eq!(
7099            SUPERVISOR_RESTART_WINDOW_MAX,
7100            crate::POLICY_BREAKER_WINDOW_MAX
7101        );
7102    }
7103
7104    #[test]
7105    fn restart_window_cap_value_round_trips_through_codec() {
7106        // The codec round-trip property the cap arm preserves: the
7107        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
7108        // through the shared duration codec — every value at the cap
7109        // serializes to the canonical `"1h"` form and parses back
7110        // identically. Pin the round-trip so a future change to the
7111        // codec's unit set or to the cap's magnitude that breaks the
7112        // round-trip property surfaces here. Peer of
7113        // `wall_clock_cap_value_round_trips_through_codec` on the
7114        // sibling `:limits :wall-clock` axis.
7115        let s = SupervisorSpec {
7116            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7117            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7118            ..SupervisorSpec::default()
7119        };
7120        s.validate().unwrap();
7121        let json = serde_json::to_string(&s).unwrap();
7122        assert!(
7123            json.contains("\"1h\""),
7124            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
7125        );
7126        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7127        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
7128    }
7129
7130    #[test]
7131    fn validate_rejects_duplicate_child_caixa() {
7132        // Two children with the same :caixa render to two ComputeUnits
7133        // with the same name in the cluster's HelmRelease values —
7134        // one silently overwrites the other. Erlang/OTP's child_spec.id
7135        // is required-unique per supervisor; same set-not-multiset
7136        // discipline applied here as for :membros / :placement
7137        // :clusters / :entrada :paths.
7138        let s = SupervisorSpec {
7139            children: vec![
7140                child("worker", "^0.1", RestartPolicy::Permanent),
7141                child("cache", "^0.1", RestartPolicy::Transient),
7142                child("worker", "^0.2", RestartPolicy::Permanent),
7143            ],
7144            ..SupervisorSpec::default()
7145        };
7146        let err = s.validate().unwrap_err();
7147        assert!(
7148            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
7149            "got {err:?}"
7150        );
7151    }
7152
7153    #[test]
7154    fn validate_duplicate_child_diagnostic_names_first_collision() {
7155        // Iteration walks the :children list in declaration order —
7156        // the diagnostic names the first repeat, deterministically,
7157        // even when multiple names duplicate.
7158        let s = SupervisorSpec {
7159            children: vec![
7160                child("a", "^0.1", RestartPolicy::Permanent),
7161                child("b", "^0.1", RestartPolicy::Permanent),
7162                child("a", "^0.1", RestartPolicy::Permanent),
7163                child("b", "^0.1", RestartPolicy::Permanent),
7164            ],
7165            ..SupervisorSpec::default()
7166        };
7167        let err = s.validate().unwrap_err();
7168        assert!(
7169            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
7170            "got {err:?}"
7171        );
7172    }
7173
7174    // ── self-supervision cross-slot gate ──────────────────────────
7175
7176    #[test]
7177    fn validate_no_self_supervision_rejects_self_referential_child() {
7178        // A supervisor whose `:children` lists its own `:nome` is a
7179        // one-node reconciliation cycle — rejected, naming the parent.
7180        let children = vec![
7181            child("worker", "^0.1", RestartPolicy::Permanent),
7182            child("orquestra", "^0.1", RestartPolicy::Permanent),
7183        ];
7184        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
7185        assert!(
7186            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
7187            "got {err:?}"
7188        );
7189    }
7190
7191    #[test]
7192    fn validate_no_self_supervision_accepts_distinct_children() {
7193        // Positive control: distinct child names (including a child that
7194        // is itself a supervisor — nested trees are valid OTP) pass.
7195        let children = vec![
7196            child("worker", "^0.1", RestartPolicy::Permanent),
7197            child("sub-tree", "^0.1", RestartPolicy::Permanent),
7198        ];
7199        validate_no_self_supervision(&children, "orquestra").unwrap();
7200    }
7201
7202    #[test]
7203    fn validate_no_self_supervision_empty_children_is_ok() {
7204        // SimpleOneForOne / no-static-children supervisors have nothing
7205        // to self-reference — the gate is vacuously satisfied.
7206        validate_no_self_supervision(&[], "orquestra").unwrap();
7207    }
7208
7209    #[test]
7210    fn validate_simple_one_for_one_skips_uniqueness_check() {
7211        // SimpleOneForOne supervisors carry no static children — the
7212        // duplicate-child loop never runs. A zero-window declaration
7213        // on a SimpleOneForOne supervisor still trips the window check
7214        // (window applies to dynamic children too).
7215        let s = SupervisorSpec {
7216            estrategia: RestartStrategy::SimpleOneForOne,
7217            restart_window: None,
7218            children: vec![],
7219            ..SupervisorSpec::default()
7220        };
7221        s.validate().unwrap();
7222        let s_zero = SupervisorSpec {
7223            estrategia: RestartStrategy::SimpleOneForOne,
7224            restart_window: Some(Duration::ZERO),
7225            children: vec![],
7226            ..SupervisorSpec::default()
7227        };
7228        assert_eq!(
7229            s_zero.validate().unwrap_err(),
7230            SupervisorError::RestartWindowZero
7231        );
7232    }
7233
7234    #[test]
7235    fn validate_zero_window_runs_after_max_restarts_check() {
7236        // Pin the order: max_restarts == 0 fires before
7237        // restart_window == 0s, so an author with both wrong sees the
7238        // counter-axis diagnostic first (matches the order in the
7239        // struct and in the doc comment).
7240        let s = SupervisorSpec {
7241            max_restarts: 0,
7242            restart_window: Some(Duration::ZERO),
7243            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7244            ..SupervisorSpec::default()
7245        };
7246        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
7247    }
7248
7249    #[test]
7250    fn round_trip_all_strategies() {
7251        for &strat in RestartStrategy::ALL {
7252            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7253            // shape partition through the [`gen_platform::IsVariant`]
7254            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
7255            // predicate rather than the raw
7256            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
7257            // open-coded pattern-match — same closed-set-typed-enum
7258            // arm-discriminator dispatch discipline the sibling
7259            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
7260            // (915a934) extended onto its two paired positive / negated
7261            // `matches!` filter sites, and the sibling
7262            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7263            // predicate convergence (766ec63) extended onto the M3 mesh-
7264            // slot per-`:placement` distribution-strategy `matches!`
7265            // discriminator axis. See the sibling
7266            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7267            // fixture and the peer `manifest::tests::
7268            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7269            // fixture — all three sites (the last unlifted
7270            // `matches!`-based arm-discriminator axis on the OTP-shape
7271            // supervisor sibling-restart-strategy closed-set typed enum,
7272            // acknowledged in 915a934's Prior-commits footnote as the
7273            // outstanding follow-up) now consult one typed dispatch on
7274            // the substrate primitive.
7275            let s = SupervisorSpec {
7276                estrategia: strat,
7277                children: if strat.is_simple_one_for_one() {
7278                    vec![]
7279                } else {
7280                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
7281                },
7282                ..SupervisorSpec::default()
7283            };
7284            let json = serde_json::to_string(&s).unwrap();
7285            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7286            assert_eq!(s, back);
7287        }
7288    }
7289
7290    #[test]
7291    fn round_trip_all_restart_policies() {
7292        for policy in [
7293            RestartPolicy::Permanent,
7294            RestartPolicy::Temporary,
7295            RestartPolicy::Transient,
7296        ] {
7297            let c = child("w", "^0.1", policy);
7298            let json = serde_json::to_string(&c).unwrap();
7299            let back: ChildSpec = serde_json::from_str(&json).unwrap();
7300            assert_eq!(c, back);
7301        }
7302    }
7303
7304    #[test]
7305    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
7306        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
7307        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
7308        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
7309        // is the only variant that satisfies `.is_simple_one_for_one()`;
7310        // every static-children-bearing arm (`OneForOne` / `OneForAll`
7311        // / `RestForOne`) returns `false`. This pin makes the partition
7312        // invariant load-bearing at caixa-core test time so a future
7313        // derive regression (a hole that returns `false` for
7314        // `SimpleOneForOne` too, or a byte-collision that flips a second
7315        // variant to `true`) trips here rather than laundering the arm
7316        // at the three test-fixture builder sites (a hole flips the
7317        // `SimpleOneForOne` fixture to carry a non-empty children list
7318        // and the subsequent `SupervisorSpec::validate` would refuse the
7319        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
7320        // a collision flips a peer strategy's fixture to carry an empty
7321        // children list and the subsequent `validate` would refuse with
7322        // [`SupervisorError::NoChildren`] — either way, the pin fires
7323        // here, at the derive site, rather than at the fixture-refusal
7324        // site far away). Peer of the sibling
7325        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
7326        // (915a934) pin on the M2 OTP-appup axis and the sibling
7327        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
7328        // pin on the M0 `:kind` axis.
7329        let cases: &[(RestartStrategy, bool)] = &[
7330            (RestartStrategy::OneForOne, false),
7331            (RestartStrategy::OneForAll, false),
7332            (RestartStrategy::RestForOne, false),
7333            (RestartStrategy::SimpleOneForOne, true),
7334        ];
7335        for (variant, expected) in cases {
7336            assert_eq!(
7337                variant.is_simple_one_for_one(),
7338                *expected,
7339                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7340                 return {expected} (partition invariant on the \
7341                 IsVariant-derived arm-discriminator predicate — every \
7342                 test-fixture site that partitions the `:children` slot \
7343                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7344                 off this typed dispatch, so a derive regression must \
7345                 surface here rather than at the fixture-refusal site)"
7346            );
7347        }
7348    }
7349
7350    #[test]
7351    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7352        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7353        // fixture-shape partition against the pre-lift
7354        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7355        // pattern-match every test-fixture builder site previously
7356        // coupled to inline. Asserts the two projections agree byte-for-
7357        // byte on every arm of the enum, so a future derive regression
7358        // that flipped either predicate's arm-set would surface here at
7359        // caixa-core test time rather than at the three fixture-builder
7360        // sites (`supervisor::tests::round_trip_all_strategies`,
7361        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7362        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7363        // far from the derive site. Same peer-shape byte-identity pin
7364        // every sibling `IsVariant`-derive-routed convergence carries on
7365        // the substrate's closed-set typed-enum surface (peer of
7366        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7367        // on the M2 OTP-appup axis).
7368        for &strat in RestartStrategy::ALL {
7369            let via_predicate = strat.is_simple_one_for_one();
7370            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7371            assert_eq!(
7372                via_predicate, via_matches,
7373                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7374                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7375                 the pre-lift open-coded pattern and the \
7376                 IsVariant-derived predicate are the same axis, \
7377                 one typed dispatch"
7378            );
7379        }
7380    }
7381
7382    #[test]
7383    fn duration_codec_round_trip_canonical_units() {
7384        // Note the canonical-form rule: durations serialize to the
7385        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7386        // "60s" — but the round-trip preserves the underlying Duration.
7387        let cases = [
7388            ("30s", Duration::from_secs(30)),
7389            ("5m", Duration::from_secs(300)),
7390            ("1h", Duration::from_secs(3600)),
7391            ("500ms", Duration::from_millis(500)),
7392        ];
7393        for (lit, dur) in cases {
7394            let s = SupervisorSpec {
7395                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7396                restart_window: Some(dur),
7397                ..SupervisorSpec::default()
7398            };
7399            let json = serde_json::to_string(&s).unwrap();
7400            assert!(
7401                json.contains(&format!("\"{lit}\"")),
7402                "expected \"{lit}\" in {json}"
7403            );
7404            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7405            assert_eq!(back.restart_window, Some(dur));
7406        }
7407    }
7408
7409    #[test]
7410    fn duration_canonicalizes_to_largest_unit() {
7411        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7412        // typed Duration still equals 60s on the way back.
7413        let s = SupervisorSpec {
7414            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7415            restart_window: Some(Duration::from_secs(60)),
7416            ..SupervisorSpec::default()
7417        };
7418        let json = serde_json::to_string(&s).unwrap();
7419        assert!(json.contains("\"1m\""), "{json}");
7420        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7421        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7422    }
7423
7424    #[test]
7425    fn three_child_one_for_one_validates() {
7426        let s = SupervisorSpec {
7427            estrategia: RestartStrategy::OneForOne,
7428            max_restarts: 5,
7429            restart_window: Some(Duration::from_secs(60)),
7430            children: vec![
7431                child("worker", "^0.1", RestartPolicy::Permanent),
7432                child("cache", "^0.1", RestartPolicy::Transient),
7433                child("scratch", "^0.1", RestartPolicy::Temporary),
7434            ],
7435        };
7436        s.validate().unwrap();
7437    }
7438
7439    #[test]
7440    fn json_uses_pascal_case_for_strategy_and_policy() {
7441        // Variant names are PascalCase by default in serde, matching
7442        // tatara-lisp's enum convention (`:estrategia OneForOne`).
7443        let c = child("w", "^0.1", RestartPolicy::Permanent);
7444        let json = serde_json::to_string(&c).unwrap();
7445        assert!(json.contains("\"Permanent\""));
7446        assert!(!json.contains("\"permanent\""));
7447
7448        let s = SupervisorSpec {
7449            estrategia: RestartStrategy::OneForOne,
7450            children: vec![c],
7451            ..SupervisorSpec::default()
7452        };
7453        let json = serde_json::to_string(&s).unwrap();
7454        assert!(json.contains("\"estrategia\":\"OneForOne\""));
7455    }
7456
7457    // ── shared duration codec: integer-magnitude canonical-form gate ──
7458    //
7459    // The gate lifts the discipline `crate::limits::parse_duration`
7460    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7461    // the shared codec backing the remaining three typed-duration
7462    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7463    // `:politicas :circuit-breaker :window`. Every magnitude `render`
7464    // emits is a non-negative integer with no decimal point and no
7465    // leading sign, so the codec's accepted set must match for
7466    // serialize/deserialize to round-trip without canonical-form
7467    // drift.
7468
7469    #[test]
7470    fn parse_accepts_integer_canonical_units() {
7471        // Pin the happy-path: every canonical author shape `render`
7472        // ever emits parses to the same `Duration` value, so the
7473        // codec's accepted set is at least a superset of its emitted
7474        // set on the canonical-unit axis.
7475        for (lit, dur) in [
7476            ("30s", Duration::from_secs(30)),
7477            ("500ms", Duration::from_millis(500)),
7478            ("2m", Duration::from_secs(120)),
7479            ("1h", Duration::from_secs(3600)),
7480            ("0s", Duration::ZERO),
7481        ] {
7482            assert_eq!(
7483                duration_codec::parse(lit).unwrap(),
7484                dur,
7485                "parse({lit:?}) should be {dur:?}"
7486            );
7487        }
7488    }
7489
7490    #[test]
7491    fn parse_accepts_bare_integer_as_seconds() {
7492        // The `"s" | ""` arm: a bare integer with no unit is read as
7493        // seconds. Pin this so the unit-empty form keeps parsing (it
7494        // renders to `"<n>s"` on serialize — that's a unit-choice
7495        // drift the integer-magnitude gate does NOT close, matching
7496        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7497        // the peer `:limits :memory` codec).
7498        assert_eq!(
7499            duration_codec::parse("30").unwrap(),
7500            Duration::from_secs(30)
7501        );
7502    }
7503
7504    #[test]
7505    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7506        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7507        // on first serialize — DRIFT. The integer-magnitude gate names
7508        // the offending `"1.5"` verbatim and points at the canonical
7509        // remediation `"1500ms"`.
7510        let err = duration_codec::parse("1.5s").unwrap_err();
7511        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7512        assert!(
7513            err.contains("not a non-negative integer"),
7514            "missing canonical-form reason in {err:?}"
7515        );
7516        assert!(
7517            err.contains("\"1500ms\""),
7518            "missing canonical-form remediation in {err:?}"
7519        );
7520    }
7521
7522    #[test]
7523    fn parse_rejects_decimal_shaped_integer_seconds() {
7524        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7525        // `1s` exactly, so the round-trip looks correct — but the
7526        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7527        // decimal-shape-with-integer-value form so author intent is
7528        // never silently rewritten.
7529        let err = duration_codec::parse("1.0s").unwrap_err();
7530        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7531        assert!(
7532            err.contains("not a non-negative integer"),
7533            "missing canonical-form reason in {err:?}"
7534        );
7535    }
7536
7537    #[test]
7538    fn parse_rejects_half_unit_minute() {
7539        // `"0.5m"` is the unit-fraction footgun — author writes a
7540        // human-readable half-minute, serde silently rewrites to
7541        // `"30s"` on next emit. The gate names the offending
7542        // magnitude `"0.5"` and points at the integer-in-smaller-unit
7543        // form.
7544        let err = duration_codec::parse("0.5m").unwrap_err();
7545        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7546        assert!(
7547            err.contains("\"30s\""),
7548            "missing canonical-form remediation in {err:?}"
7549        );
7550    }
7551
7552    #[test]
7553    fn parse_rejects_leading_plus_sign() {
7554        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7555        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7556        // cleanly to 30s and round-tripped to `"30s"` on next emit
7557        // (DRIFT). The digit-only gate closes the leading-sign class
7558        // first; the diagnostic names `"+30"` verbatim.
7559        let err = duration_codec::parse("+30s").unwrap_err();
7560        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7561        assert!(
7562            err.contains("not a non-negative integer"),
7563            "missing canonical-form reason in {err:?}"
7564        );
7565    }
7566
7567    #[test]
7568    fn parse_rejects_leading_minus_sign() {
7569        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7570        // rejected with `"negative duration in \"-30s\""`. Under the
7571        // integer-magnitude gate the diagnostic is unified — `-30` is
7572        // non-digit-only, f64-numeric, and surfaces with the canonical-
7573        // form reason (no leading `+` / `-` sign) naming the offending
7574        // `"-30"` verbatim. Same diagnostic shape as every other
7575        // rejected non-integer magnitude.
7576        let err = duration_codec::parse("-30s").unwrap_err();
7577        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7578        assert!(
7579            err.contains("not a non-negative integer"),
7580            "missing canonical-form reason in {err:?}"
7581        );
7582    }
7583
7584    #[test]
7585    fn parse_garbage_still_falls_through_to_bad_magnitude() {
7586        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7587        // through to the narrower "bad duration magnitude" arm — the
7588        // canonical-form diagnostic is reserved for the parser-shape
7589        // footgun case, not the "not a number at all" case. Same
7590        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7591        // the peer `:limits :memory` codec.
7592        let err = duration_codec::parse("--1s").unwrap_err();
7593        assert!(
7594            err.contains("bad duration magnitude"),
7595            "expected bad-magnitude wording in {err:?}"
7596        );
7597    }
7598
7599    #[test]
7600    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7601        // The accepted set is now closed under `u64`-exact integer
7602        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7603        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7604        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7605        // possible. Pin the integer-exact arms across the four unit
7606        // suffixes so a future refactor that reaches back for f64
7607        // (`from_secs_f64`, `mul_f64`) surfaces here.
7608        assert_eq!(
7609            duration_codec::parse("3600s").unwrap(),
7610            Duration::from_secs(3600)
7611        );
7612        assert_eq!(
7613            duration_codec::parse("60m").unwrap(),
7614            Duration::from_secs(3600)
7615        );
7616        assert_eq!(
7617            duration_codec::parse("1h").unwrap(),
7618            Duration::from_secs(3600)
7619        );
7620        assert_eq!(
7621            duration_codec::parse("999ms").unwrap(),
7622            Duration::from_millis(999)
7623        );
7624    }
7625
7626    #[test]
7627    fn restart_window_serde_rejects_fractional_seconds() {
7628        // The shared codec backs `SupervisorSpec::restart_window`
7629        // (`with = "duration_codec"`) — so the gate applies on serde
7630        // deserialize for the typed Supervisor slot. A
7631        // `{"restartWindow":"1.5s"}` payload that previously round-
7632        // tripped to a different canonical string on next serialize
7633        // is now refused at deserialize with the integer-magnitude
7634        // diagnostic.
7635        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7636            "restartWindow":"1.5s",
7637            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7638        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7639        let msg = err.to_string();
7640        assert!(
7641            msg.contains("not a non-negative integer"),
7642            "expected integer-magnitude diagnostic in {msg:?}"
7643        );
7644        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7645    }
7646
7647    #[test]
7648    fn restart_window_serde_rejects_leading_plus() {
7649        // The `u64::from_str` leading-`+` permissiveness gap that
7650        // motivated the digit-only gate (the `f64`-side accepted
7651        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7652        // is now closed on the shared codec — surfaces as a structured
7653        // diagnostic at the serde layer for every typed-duration slot.
7654        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7655            "restartWindow":"+30s",
7656            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7657        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7658        let msg = err.to_string();
7659        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7660        assert!(
7661            msg.contains("not a non-negative integer"),
7662            "missing canonical-form reason in {msg:?}"
7663        );
7664    }
7665
7666    #[test]
7667    fn parse_rejects_leading_zero_magnitude() {
7668        // `"030s"` is digit-only, so the existing non-digit-only / sign
7669        // / fractional arm doesn't catch it — `u64::from_str("030")`
7670        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7671        // `Duration::from_secs(30)` and round-tripped through `render`
7672        // to `"30s"` — a *different* canonical string on the next emit,
7673        // breaking the THEORY.md Part V render-determinism contract
7674        // exactly the way `"+30s"` did before the leading-`+` arm
7675        // landed. Peer with the `rate_limit_codec` leading-zero arm
7676        // (4f46830) on the same canonical-form-drift axis.
7677        let err = duration_codec::parse("030s").unwrap_err();
7678        assert!(
7679            err.contains("non-canonical leading zero"),
7680            "expected leading-zero diagnostic in {err:?}"
7681        );
7682        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7683        assert!(
7684            err.contains("\"30s\""),
7685            "missing canonical-form remediation in {err:?}"
7686        );
7687        assert!(
7688            err.contains("THEORY.md"),
7689            "missing render-determinism citation in {err:?}"
7690        );
7691    }
7692
7693    #[test]
7694    fn parse_rejects_multi_digit_zero_magnitude() {
7695        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7696        // digit-only, parse losslessly to `Duration::ZERO`, but render
7697        // back to `"0s"` (the single-byte canonical form) on the next
7698        // emit. The leading-zero arm refuses the drift class at the
7699        // codec layer; the semantic-zero gate downstream
7700        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7701        // the single-byte canonical form `"0s"` separately on the
7702        // typed-validate layer.
7703        let err = duration_codec::parse("00s").unwrap_err();
7704        assert!(
7705            err.contains("non-canonical leading zero"),
7706            "expected leading-zero diagnostic in {err:?}"
7707        );
7708        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7709    }
7710
7711    #[test]
7712    fn parse_rejects_leading_zero_per_hour_window() {
7713        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7714        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7715        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7716        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7717        // `h` / bare-integer-as-seconds) inherits the same gate.
7718        let err = duration_codec::parse("01h").unwrap_err();
7719        assert!(
7720            err.contains("non-canonical leading zero"),
7721            "expected leading-zero diagnostic in {err:?}"
7722        );
7723        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7724    }
7725
7726    #[test]
7727    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7728        // The `parse_accepts_bare_integer_as_seconds` happy-path
7729        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7730        // multi-byte starts-with-`0`, parses losslessly to
7731        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7732        // bare-integer surface accepts permissive unit-empty
7733        // shorthand but still must reject leading-zero padding.
7734        let err = duration_codec::parse("030").unwrap_err();
7735        assert!(
7736            err.contains("non-canonical leading zero"),
7737            "expected leading-zero diagnostic in {err:?}"
7738        );
7739        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7740    }
7741
7742    #[test]
7743    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7744        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7745        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7746        // each round-trips losslessly through `render`
7747        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7748        // accepts them. The downstream semantic-zero gates
7749        // (`SupervisorError::ZeroRestartWindow`,
7750        // `AplicacaoError::PolicyTimeoutZero`,
7751        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7752        // zero-magnitude authoring at the typed-validate layer above,
7753        // peer with the `rate_limit_codec` codec-layer / typed-
7754        // validate-layer partition for `"0/s"`.
7755        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7756        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7757        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7758    }
7759
7760    #[test]
7761    fn parse_accepts_canonical_magnitude_with_leading_one() {
7762        // The complementary boundary: a future tightening cannot
7763        // drift into rejecting valid canonical magnitudes that
7764        // happen to start with `1` (or any digit `[1-9]`). Pin
7765        // every canonical-unit suffix so the leading-zero arm
7766        // remains strictly narrower than the digit-only arm.
7767        assert_eq!(
7768            duration_codec::parse("100ms").unwrap(),
7769            Duration::from_millis(100)
7770        );
7771        assert_eq!(
7772            duration_codec::parse("100s").unwrap(),
7773            Duration::from_secs(100)
7774        );
7775        assert_eq!(
7776            duration_codec::parse("10m").unwrap(),
7777            Duration::from_secs(600)
7778        );
7779        assert_eq!(
7780            duration_codec::parse("10h").unwrap(),
7781            Duration::from_secs(36_000)
7782        );
7783    }
7784
7785    #[test]
7786    fn restart_window_serde_rejects_leading_zero() {
7787        // The shared codec backs `SupervisorSpec::restart_window`
7788        // (`with = "duration_codec"`) — so the leading-zero arm
7789        // applies on serde deserialize for the typed Supervisor slot.
7790        // A `{"restartWindow":"030s"}` payload that previously round-
7791        // tripped to a different canonical string on next serialize
7792        // is now refused at deserialize with the leading-zero
7793        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7794        // / `restart_window_serde_rejects_fractional_seconds` on the
7795        // same canonical-form-drift axis.
7796        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7797            "restartWindow":"030s",
7798            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7799        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7800        let msg = err.to_string();
7801        assert!(
7802            msg.contains("non-canonical leading zero"),
7803            "expected leading-zero diagnostic in {msg:?}"
7804        );
7805        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7806    }
7807
7808    #[test]
7809    fn parse_rejects_leading_whitespace() {
7810        // `" 30s"` — the canonical paste-from-aligned-doc /
7811        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7812        // gate the top-level `s.trim()` at parse entry silently ate
7813        // the leading space and parsed the value to
7814        // `Duration::from_secs(30)`, which then round-tripped through
7815        // `render` to `"30s"` (a *different* canonical string on the
7816        // next emit) — the exact canonical-form-drift class the
7817        // leading-`+` / leading-zero arms already close, extended
7818        // to the whitespace-byte class. Peer with the sibling
7819        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7820        // the M3 `:politicas` axis.
7821        let err = duration_codec::parse(" 30s").unwrap_err();
7822        assert!(
7823            err.contains("contains whitespace byte"),
7824            "expected whitespace diagnostic in {err:?}"
7825        );
7826        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7827        assert!(
7828            err.contains("THEORY.md"),
7829            "missing render-determinism contract citation in {err:?}"
7830        );
7831    }
7832
7833    #[test]
7834    fn parse_rejects_trailing_whitespace() {
7835        // `"30s "` — the canonical shell-history / trailing-space
7836        // paste footgun. Before this gate the top-level `s.trim()`
7837        // silently ate the trailing space and parsed to
7838        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7839        // next emit — same canonical-form drift as the leading-space
7840        // sibling, closed on the same whitespace-byte arm.
7841        let err = duration_codec::parse("30s ").unwrap_err();
7842        assert!(
7843            err.contains("contains whitespace byte"),
7844            "expected whitespace diagnostic in {err:?}"
7845        );
7846        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7847    }
7848
7849    #[test]
7850    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7851        // `"30 s"` — the canonical typographically-spaced author
7852        // shape (the same idiom every prose reference to a duration
7853        // renders as, mistakenly retained when the value is pasted
7854        // into a codec-shaped slot). Before this gate the per-part
7855        // `num_part.trim()` / `unit.trim()` calls silently ate the
7856        // whitespace between the magnitude and the unit and parsed
7857        // the value to `Duration::from_secs(30)`, round-tripping to
7858        // `"30s"` — the codec's *internal* whitespace-tolerance
7859        // vector, orthogonal to the leading / trailing surface but
7860        // the same canonical-form-drift class. Pins the arm as
7861        // strictly stronger than the pre-existing top-level
7862        // `s.trim()` behavior: it fires on whitespace anywhere in
7863        // the value, not just at the string boundary.
7864        let err = duration_codec::parse("30 s").unwrap_err();
7865        assert!(
7866            err.contains("contains whitespace byte"),
7867            "expected whitespace diagnostic in {err:?}"
7868        );
7869        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7870    }
7871
7872    #[test]
7873    fn parse_rejects_tab_byte() {
7874        // `"\t30s"` — the canonical paste-from-indented-doc /
7875        // paste-from-YAML-block-scalar footgun where a tab byte leads
7876        // the magnitude. Pins that the gate covers tab (`0x09`) as
7877        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7878        // members and both would be silently swallowed by `s.trim()`
7879        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7880        // space alone to the full ASCII-whitespace set (space `0x20`,
7881        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7882        // the tab arm as a representative of the non-space members.
7883        let err = duration_codec::parse("\t30s").unwrap_err();
7884        assert!(
7885            err.contains("contains whitespace byte"),
7886            "expected whitespace diagnostic in {err:?}"
7887        );
7888        assert!(
7889            err.contains("0x09"),
7890            "missing offending tab byte in {err:?}"
7891        );
7892    }
7893
7894    #[test]
7895    fn restart_window_serde_rejects_whitespace() {
7896        // The shared codec backs `SupervisorSpec::restart_window`
7897        // (`with = "duration_codec"`) — so the whitespace arm
7898        // applies on serde deserialize for the typed Supervisor slot.
7899        // A `{"restartWindow":" 30s"}` payload that previously round-
7900        // tripped to a different canonical string on next serialize
7901        // is now refused at deserialize with the whitespace-byte
7902        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7903        // / `restart_window_serde_rejects_leading_plus` /
7904        // `restart_window_serde_rejects_fractional_seconds` on the
7905        // same canonical-form-drift axis.
7906        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7907            "restartWindow":" 30s",
7908            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7909        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7910        let msg = err.to_string();
7911        assert!(
7912            msg.contains("contains whitespace byte"),
7913            "expected whitespace diagnostic in {msg:?}"
7914        );
7915        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7916    }
7917
7918    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7919    //
7920    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7921    // duration codec — closes the strictly-complementary class the
7922    // byte-scan cannot see, through the lifted
7923    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7924    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7925    // and `:politicas :circuit-breaker :window` simultaneously via
7926    // this shared codec.
7927
7928    #[test]
7929    fn duration_codec_parse_rejects_leading_nbsp() {
7930        // NBSP prefix — the strictly-complementary drift class the
7931        // ASCII byte-scan cannot see. `str::trim` strips it silently
7932        // and the value drifts to `"30s"` on next serialize.
7933        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7934        assert!(
7935            err.contains("non-ASCII Unicode whitespace character"),
7936            "expected non-ASCII whitespace diagnostic in {err:?}"
7937        );
7938        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7939    }
7940
7941    #[test]
7942    fn duration_codec_parse_rejects_trailing_line_separator() {
7943        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7944        // footgun.
7945        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7946        assert!(
7947            err.contains("non-ASCII Unicode whitespace character"),
7948            "expected non-ASCII whitespace diagnostic in {err:?}"
7949        );
7950        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7951    }
7952
7953    #[test]
7954    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7955        // Positive-control pin: every ASCII-only canonical form the
7956        // renderer emits stays accepted through the new arm.
7957        assert_eq!(
7958            duration_codec::parse("30s").unwrap(),
7959            Duration::from_secs(30)
7960        );
7961        assert_eq!(
7962            duration_codec::parse("500ms").unwrap(),
7963            Duration::from_millis(500)
7964        );
7965        assert_eq!(
7966            duration_codec::parse("1h").unwrap(),
7967            Duration::from_secs(3600)
7968        );
7969    }
7970
7971    #[test]
7972    fn restart_window_serde_rejects_non_ascii_whitespace() {
7973        // The shared codec backs `SupervisorSpec::restart_window` — so
7974        // the new non-ASCII Unicode whitespace arm applies on serde
7975        // deserialize for the typed Supervisor slot. A
7976        // `{"restartWindow":" 30s"}` payload that previously
7977        // survived the ASCII byte-scan (only ASCII whitespace was
7978        // refused) is now refused at deserialize with the
7979        // non-ASCII-whitespace-and-codepoint diagnostic.
7980        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7981            \"restartWindow\":\"\u{00A0}30s\",\
7982            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7983        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7984        let msg = err.to_string();
7985        assert!(
7986            msg.contains("non-ASCII Unicode whitespace character"),
7987            "expected non-ASCII whitespace diagnostic in {msg:?}"
7988        );
7989        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7990    }
7991
7992    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7993
7994    #[test]
7995    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7996        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7997        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7998        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7999        // name the exact camelCase JSON keys the
8000        // `#[serde(rename_all = "camelCase")]` attribute on
8001        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
8002        // field carries `Some(_)` / non-empty) and pin that each canonical
8003        // byte-sequence appears verbatim in the JSON — a future accidental
8004        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
8005        // name flip at the derive attribute (any of which would silently
8006        // break every downstream JSON consumer that reaches for one of the
8007        // four consts via `Value::get(...)`) surfaces here as a build-time
8008        // test failure at `supervisor.rs`, not as an apply-time
8009        // `.get(<stale-canonical-const>)` returning `None` far from the
8010        // derive-attr drift's commit. Peer with the sibling
8011        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
8012        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
8013        // M2 typed-slot family established, extended here to close the
8014        // top-level Supervisor axis.
8015        let spec = SupervisorSpec {
8016            estrategia: RestartStrategy::OneForOne,
8017            max_restarts: 5,
8018            restart_window: Some(Duration::from_secs(60)),
8019            children: vec![ChildSpec {
8020                caixa: "w".into(),
8021                versao: "^0.1".into(),
8022                restart: RestartPolicy::Permanent,
8023            }],
8024        };
8025        let json = serde_json::to_string(&spec).unwrap();
8026        for key in [
8027            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8028            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8029            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8030            crate::render::SUPERVISOR_KEY_CHILDREN,
8031        ] {
8032            let quoted = format!("\"{key}\"");
8033            assert!(
8034                json.contains(&quoted),
8035                "serialized SupervisorSpec must carry the lifted \
8036                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
8037                 the JSON emission (got: {json})",
8038            );
8039        }
8040    }
8041
8042    #[test]
8043    fn supervisor_key_consts_are_pairwise_distinct() {
8044        // Cross-axis drift-detection pin: a future collapse of two
8045        // canonical top-level byte-strings onto the same value (e.g. an
8046        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
8047        // also read `"estrategia"`) would silently reroute every
8048        // downstream probe on one axis onto the sibling axis's overlay
8049        // entry and pass every propagation-probe test that expected only
8050        // the stale axis's value. Peer of the sibling four-way distinct
8051        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
8052        let all = [
8053            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8054            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8055            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8056            crate::render::SUPERVISOR_KEY_CHILDREN,
8057        ];
8058        for (i, a) in all.iter().enumerate() {
8059            for b in all.iter().skip(i + 1) {
8060                assert_ne!(
8061                    a, b,
8062                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
8063                     canonical byte-sequences — got `{a}` == `{b}`",
8064                );
8065            }
8066        }
8067    }
8068
8069    #[test]
8070    fn supervisor_key_consts_are_lower_camel_case_shape() {
8071        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
8072        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8073        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8074        // capital, no whitespace / dots) — the canonical shape the
8075        // `#[serde(rename_all = "camelCase")]` derive produces on
8076        // `SupervisorSpec`. A future flip to a non-camelCase attribute
8077        // at the derive surfaces both here (this test fails on the
8078        // stale-constant shape) and at
8079        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8080        // (that test fails on the mismatch between const and derive).
8081        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
8082        // (d8b8b4f) on the sibling M2 `:limits` axis.
8083        for key in [
8084            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8085            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8086            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8087            crate::render::SUPERVISOR_KEY_CHILDREN,
8088        ] {
8089            assert!(
8090                !key.is_empty(),
8091                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
8092            );
8093            let first = key.chars().next().unwrap();
8094            assert!(
8095                first.is_ascii_lowercase(),
8096                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
8097                 (got {key:?}, leads with {first:?})",
8098            );
8099            assert!(
8100                key.chars().all(|c| c.is_ascii_alphanumeric()),
8101                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
8102                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8103            );
8104        }
8105    }
8106
8107    #[test]
8108    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
8109        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
8110        // (camelCase JSON keys, no leading colon) must never collide
8111        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
8112        // consts (kebab-case author-facing labels with leading colon)
8113        // that sit next to them at `caixa_core::render`. Both families
8114        // cover the same four typed Supervisor slots on two distinct
8115        // axes (author-side kebab vs renderer-side camelCase);
8116        // collapsing either family onto the other's byte-shape would
8117        // silently reroute the render-side probe onto the author-facing
8118        // surface, or vice versa. Peer of the byte-distinctness
8119        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
8120        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
8121        let pairs = [
8122            (
8123                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8124                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
8125            ),
8126            (
8127                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8128                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
8129            ),
8130            (
8131                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8132                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
8133            ),
8134            (
8135                crate::render::SUPERVISOR_KEY_CHILDREN,
8136                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
8137            ),
8138        ];
8139        for (json_key, author_key) in pairs {
8140            assert_ne!(
8141                json_key, author_key,
8142                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
8143                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
8144                 got JSON `{json_key}` == author `{author_key}`",
8145            );
8146        }
8147    }
8148
8149    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
8150
8151    #[test]
8152    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
8153        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
8154        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
8155        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
8156        // keys the `#[serde(rename_all = "camelCase")]` attribute on
8157        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
8158        // pin that each canonical byte-sequence appears verbatim in the
8159        // JSON — a future accidental `rename_all = "snake_case"` /
8160        // `"kebab-case"` / verbatim-field-name flip at the derive
8161        // attribute (any of which would silently break every downstream
8162        // JSON consumer that reaches for one of the three consts via
8163        // `Value::get(...)`) surfaces here as a build-time test failure at
8164        // `supervisor.rs`, not as an apply-time
8165        // `.get(<stale-canonical-const>)` returning `None` far from the
8166        // derive-attr drift's commit. Peer with the enclosing
8167        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8168        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
8169        // discipline the SupervisorSpec top-level lift established,
8170        // extended here to the sibling per-`:children` entry `ChildSpec`
8171        // derive so the last M2 typed-struct sub-block
8172        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
8173        // surface without a lifted serde-key peer joins the substrate's
8174        // "one canonical byte-string per typed serialized-key axis"
8175        // discipline.
8176        let c = ChildSpec {
8177            caixa: "worker".into(),
8178            versao: "^0.1".into(),
8179            restart: RestartPolicy::Permanent,
8180        };
8181        let json = serde_json::to_string(&c).unwrap();
8182        for key in [
8183            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8184            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8185            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8186        ] {
8187            let quoted = format!("\"{key}\"");
8188            assert!(
8189                json.contains(&quoted),
8190                "serialized ChildSpec must carry the lifted \
8191                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
8192                 in the JSON emission (got: {json})",
8193            );
8194        }
8195    }
8196
8197    #[test]
8198    fn supervisor_child_key_consts_are_pairwise_distinct() {
8199        // Cross-axis drift-detection pin: a future collapse of two
8200        // canonical `ChildSpec` per-entry byte-strings onto the same
8201        // value (e.g. an accidental copy-paste flip of
8202        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
8203        // silently reroute every downstream probe on one axis onto the
8204        // sibling axis's overlay entry and pass every propagation-probe
8205        // test that expected only the stale axis's value. Peer of the
8206        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
8207        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
8208        // pair (ce80ca0).
8209        let all = [
8210            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8211            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8212            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8213        ];
8214        for (i, a) in all.iter().enumerate() {
8215            for b in all.iter().skip(i + 1) {
8216                assert_ne!(
8217                    a, b,
8218                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
8219                     distinct canonical byte-sequences — got `{a}` == `{b}`",
8220                );
8221            }
8222        }
8223    }
8224
8225    #[test]
8226    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
8227        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
8228        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8229        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8230        // capital, no whitespace / dots) — the canonical shape the
8231        // `#[serde(rename_all = "camelCase")]` derive produces on
8232        // `ChildSpec`. A future flip to a non-camelCase attribute at the
8233        // derive surfaces both here (this test fails on the
8234        // stale-constant shape) and at
8235        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
8236        // (that test fails on the mismatch between const and derive).
8237        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
8238        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
8239        for key in [
8240            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8241            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8242            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8243        ] {
8244            assert!(
8245                !key.is_empty(),
8246                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
8247            );
8248            let first = key.chars().next().unwrap();
8249            assert!(
8250                first.is_ascii_lowercase(),
8251                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
8252                 byte (got {key:?}, leads with {first:?})",
8253            );
8254            assert!(
8255                key.chars().all(|c| c.is_ascii_alphanumeric()),
8256                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
8257                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8258            );
8259        }
8260    }
8261
8262    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
8263
8264    #[test]
8265    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
8266        // The fail-before-pass-after pin: pre-lift there was no
8267        // single-source binding between the [`RestartStrategy`] variant
8268        // name the un-`rename`d `Serialize` derive emits under
8269        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
8270        // every downstream cluster-side dispatcher (the future
8271        // wasm-operator's per-supervisor sibling-restart branch, the
8272        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8273        // admission-time enum-arm bind, the `caixa-operator`'s
8274        // hierarchical reconciliation scheduler's per-strategy fan-out)
8275        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
8276        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
8277        // override, or a variant rename in the source — would silently
8278        // rebrand the emitted scalar under one spelling while every
8279        // downstream dispatcher still probed the other, with the failure
8280        // surfacing at the operator's reconcile posture (subtrees coming
8281        // up under the `default()` `OneForOne` arm rather than the typed
8282        // slot's declared strategy — a bad child would then only take
8283        // itself down instead of the sibling set the author intended, so
8284        // shared-state children fall out of sync) far from the source
8285        // rebrand commit and with no field naming the drift. Pinning the
8286        // two paths (the `Serialize` derive's serialized string AND the
8287        // [`RestartStrategy::as_str`] helper) to the same four lifted
8288        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
8289        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
8290        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
8291        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
8292        // byte-strings makes any future drift on either endpoint fail
8293        // here at caixa-core build time. Peer of the M3
8294        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8295        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
8296        // three-path-convergence discipline, extended to close the
8297        // OTP-shaped per-supervisor sibling-restart axis.
8298        for (variant, expected) in [
8299            (
8300                RestartStrategy::OneForOne,
8301                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8302            ),
8303            (
8304                RestartStrategy::OneForAll,
8305                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8306            ),
8307            (
8308                RestartStrategy::RestForOne,
8309                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8310            ),
8311            (
8312                RestartStrategy::SimpleOneForOne,
8313                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8314            ),
8315        ] {
8316            let json = serde_json::to_string(&variant).unwrap();
8317            assert_eq!(
8318                json,
8319                format!("\"{expected}\""),
8320                "RestartStrategy::{variant:?} must serialize to {expected:?}"
8321            );
8322            assert_eq!(
8323                variant.as_str(),
8324                expected,
8325                "RestartStrategy::{variant:?}.as_str() must return the lifted \
8326                 SUPERVISOR_ESTRATEGIA_* constant"
8327            );
8328        }
8329    }
8330
8331    #[test]
8332    fn supervisor_estrategia_consts_are_pairwise_distinct() {
8333        // Cross-arm drift-detection pin: a future collapse of two
8334        // canonical variant byte-strings onto the same value (e.g. an
8335        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8336        // to also read `"OneForOne"`) would silently reroute every
8337        // downstream operator's per-strategy dispatch onto the sibling
8338        // arm's reconcile branch and pass every propagation-probe test
8339        // that expected only the stale arm's value — the mis-strategied
8340        // subtree would come up with the wrong sibling-restart posture
8341        // on every subsequent failure. Peer of the sibling four-way
8342        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8343        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8344        let all = [
8345            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8346            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8347            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8348            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8349        ];
8350        for (i, a) in all.iter().enumerate() {
8351            for (j, b) in all.iter().enumerate() {
8352                if i != j {
8353                    assert_ne!(
8354                        a, b,
8355                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8356                         — got duplicate {a:?} at indices {i} and {j}",
8357                    );
8358                }
8359            }
8360        }
8361    }
8362
8363    #[test]
8364    fn restart_strategy_display_routes_through_as_str_helper() {
8365        // The fail-before-pass-after pin on the first half of the
8366        // three-path convergence: pre-convergence the sibling
8367        // OTP-shape typed enum [`RestartStrategy`] carried a
8368        // [`std::fmt::Display`] surface via its
8369        // `#[discriminant(also_display)]` gen-platform derive route,
8370        // which arrived kebab-case as `"one-for-one"` /
8371        // `"one-for-all"` / `"rest-for-one"` /
8372        // `"simple-one-for-one"` while the wire format ran as
8373        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8374        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8375        // Every consumer reaching for a strategy byte-string past the
8376        // wire format had to pick between three paths
8377        // ([`RestartStrategy::as_str`], the `Serialize` derive's
8378        // serialized string, or `format!("{v}")` on the
8379        // discriminant-Display route), any two of which a future
8380        // variant rename or `#[serde(rename_all = "kebab-case")]`
8381        // attribute would silently desynchronize. Wiring
8382        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8383        // closes the third path: every `format!("{v}")` call reaches
8384        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8385        // const the wire format and the [`RestartStrategy::as_str`]
8386        // helper already route through, so a future variant rename
8387        // lands at exactly one place. Pin the routing here so a future
8388        // `impl std::fmt::Display for RestartStrategy`
8389        // reimplementation that hand-rolls the arms instead of
8390        // delegating to [`RestartStrategy::as_str`] fails at
8391        // caixa-core build time. Peer of the M3
8392        // `placement_strategy_display_routes_through_as_str_helper`
8393        // (cc8f749) which the M3 axis converged first.
8394        for &variant in RestartStrategy::ALL {
8395            assert_eq!(
8396                variant.to_string(),
8397                variant.as_str(),
8398                "RestartStrategy::{variant:?} Display must route through \
8399                 RestartStrategy::as_str (single source of truth: the lifted \
8400                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8401            );
8402        }
8403    }
8404
8405    #[test]
8406    fn restart_strategy_display_matches_serialized_wire_byte_string() {
8407        // The fail-before-pass-after pin on the second half of the
8408        // three-path convergence: `Display` (user-facing text) agrees
8409        // byte-for-byte with the `Serialize` derive's wire format
8410        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8411        // scalar) on every variant. Pre-convergence the two paths
8412        // were structurally independent — a future
8413        // `#[serde(rename_all = "kebab-case")]` attribute on the
8414        // enum would silently rebrand the emitted wire scalar
8415        // (`one-for-one`, `one-for-all`, `rest-for-one`,
8416        // `simple-one-for-one`) while every consumer that
8417        // pretty-prints the strategy (the future wasm-operator's
8418        // per-supervisor sibling-restart-strategy diagnostic line,
8419        // the future `feira app graph` per-supervisor strategy line,
8420        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8421        // materializer's admission-webhook rejection body) would
8422        // still emit the PascalCase form the `as_str` / `Display`
8423        // route returns, with the mismatch surfacing at consumer
8424        // parse time / operator dispatch time far from the source
8425        // rebrand commit. Pin the two paths byte-for-byte here so any
8426        // future serde-attribute or variant-rename drift is a
8427        // caixa-core-build-time test failure at this call, not a
8428        // silent per-consumer dispatch miss. Peer of the M3
8429        // `placement_strategy_display_matches_serialized_wire_byte_string`
8430        // (cc8f749) which the M3 axis converged first.
8431        for &variant in RestartStrategy::ALL {
8432            let wire = serde_json::to_string(&variant).unwrap();
8433            let unquoted = wire
8434                .strip_prefix('"')
8435                .and_then(|s| s.strip_suffix('"'))
8436                .expect("serialized RestartStrategy is a JSON string");
8437            assert_eq!(
8438                variant.to_string(),
8439                unquoted,
8440                "RestartStrategy::{variant:?} Display byte-string must match the \
8441                 Serialize derive's wire byte-string (three-path convergence: \
8442                 Display + as_str + Serialize all resolve to the same \
8443                 SUPERVISOR_ESTRATEGIA_* const)"
8444            );
8445        }
8446    }
8447
8448    #[test]
8449    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8450        // Fail-before-pass-after byte-parity pin on the lifted
8451        // `impl AsRef<str> for RestartStrategy` — asserts the
8452        // standard-library trait impl and the substrate-primitive
8453        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8454        // to the same `&str` per instance across the four-arm
8455        // closed set, so any future silent detour that routes the
8456        // impl through a divergent projection (a per-arm inline
8457        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8458        // re-inlining that opens a compile-time link to the un-lifted
8459        // arm-literal, a swap onto the kebab-case
8460        // [`gen_platform::Discriminant`] catalog identity that would
8461        // collide the wire axis with the dispatcher-catalog axis) trips
8462        // at caixa-core test time under `PartialEq` rather than at a
8463        // downstream `impl AsRef<str>`-bound consumer's silent split.
8464        // Sweeps every one of the four arms
8465        // [`RestartStrategy::ALL`] carries so no arm's projection is
8466        // covered only by the sibling wire-format `Serialize` derive
8467        // path. Peer of the sibling
8468        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8469        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8470        // top-level `:versao` typed newtype — the two pins together
8471        // cover the substrate primitive's `AsRef<str>` projection axis
8472        // on the paired newtype + closed-set-typed-enum surface.
8473        for &variant in RestartStrategy::ALL {
8474            assert_eq!(
8475                <RestartStrategy as AsRef<str>>::as_ref(&variant),
8476                variant.as_str(),
8477                "AsRef<str> impl on RestartStrategy::{variant:?} must \
8478                 byte-equal RestartStrategy::as_str on the same instance \
8479                 — divergence signals a silent detour off the substrate-\
8480                 primitive accessor"
8481            );
8482        }
8483    }
8484
8485    #[test]
8486    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8487        // Fail-before-pass-after byte-parity pin on the three-path
8488        // convergence discipline the M2 sibling-restart primitive now
8489        // carries on the `&str`-projection axis:
8490        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8491        // lifted impl), `format!("{s}")` (the pre-existing
8492        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8493        // primitive `pub const fn` accessor both trait impls delegate
8494        // through) must resolve to the same byte-string on every
8495        // instance across the four-arm closed set. Refuses any future
8496        // divergence between the two trait impls (a stray
8497        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8498        // rather than delegating through the shared accessor; a
8499        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8500        // literal cascade) that would silently split the two
8501        // projection paths of the same closed-set typed enum. Mirrors
8502        // the sibling three-path-convergence discipline the peer
8503        // [`crate::CaixaVersion`] typed newtype carries on its
8504        // `AsRef<str>` / `Display` / `as_str` triple
8505        // (version.rs pin
8506        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8507        // 16d5c7e).
8508        for &variant in RestartStrategy::ALL {
8509            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8510            let via_display: String = format!("{variant}");
8511            let via_accessor: &str = variant.as_str();
8512            assert_eq!(via_as_ref, via_accessor);
8513            assert_eq!(via_display, via_accessor);
8514            assert_eq!(via_as_ref, via_display.as_str());
8515        }
8516    }
8517
8518    #[test]
8519    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8520        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8521        // exhaustive-iteration surface: every variant appears exactly
8522        // once, and the slice length matches the arm count of the
8523        // closed set. Every consumer that walks the accepted-strategy
8524        // set (a future `feira supervisor --estrategia …` CLI-side
8525        // arg-parse's "did you mean" hint, a future M4 admission-
8526        // webhook's rejection body naming the accepted-`:estrategia`
8527        // list, the [`RestartStrategy::from_wire`] reverse-projection
8528        // consumers that iterate the accept-set for diagnostic
8529        // rendering) reads through this slice, so a future arm addition
8530        // that grows the enum but forgets to grow [`Self::ALL`]
8531        // silently truncates every downstream consumer's accept-set at
8532        // the same pre-addition boundary — this pin fails at caixa-core
8533        // build time on the pairwise-distinct + arm-count invariants.
8534        //
8535        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8536        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8537        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8538        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8539        // pins on the peer closed-set typed-enum axes.
8540        let all: &[RestartStrategy] = RestartStrategy::ALL;
8541        assert_eq!(
8542            all.len(),
8543            4,
8544            "RestartStrategy::ALL must enumerate every variant of the \
8545             four-arm closed set (OneForOne, OneForAll, RestForOne, \
8546             SimpleOneForOne); got {all:?}"
8547        );
8548        for (i, a) in all.iter().enumerate() {
8549            for (j, b) in all.iter().enumerate() {
8550                if i != j {
8551                    assert_ne!(
8552                        a, b,
8553                        "RestartStrategy::ALL must carry every variant exactly \
8554                         once — got duplicate {a:?} at indices {i} and {j}"
8555                    );
8556                }
8557            }
8558        }
8559        for variant in [
8560            RestartStrategy::OneForOne,
8561            RestartStrategy::OneForAll,
8562            RestartStrategy::RestForOne,
8563            RestartStrategy::SimpleOneForOne,
8564        ] {
8565            assert!(
8566                all.contains(&variant),
8567                "RestartStrategy::ALL must contain {variant:?} — a future arm \
8568                 addition that grows the enum but forgets to grow the ALL slice \
8569                 silently truncates every downstream consumer's accept-set at \
8570                 the pre-addition boundary"
8571            );
8572        }
8573    }
8574
8575    #[test]
8576    fn restart_strategy_wire_names_covers_every_arm() {
8577        // Load-bearing pin on the substrate-canonical
8578        // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8579        // on the `PascalCase` wire byte-string axis: every variant of
8580        // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8581        // surface must project through [`RestartStrategy::as_str`] onto
8582        // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8583        // and the roster's length must byte-equal
8584        // `RestartStrategy::ALL.len()` so a silent skew between the
8585        // [`RestartStrategy::as_str`] match's arm-set and the roster's
8586        // arm-set trips here at caixa-core test time rather than at a
8587        // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8588        // admission-webhook rejection body's wire-form `:estrategia`
8589        // accepted-set enumeration miss / a `feira supervisor
8590        // --estrategia …` "did you mean" hint drift / a future
8591        // wasm-operator per-reconcile-step diagnostic log line's
8592        // accepted-wire-form enumeration miss. A future arm addition
8593        // (an OTP-`rest_for_all` arm the theory
8594        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
8595        // might reach for once the four canonical OTP strategies stop
8596        // covering the substrate's discovered load-shape) extends
8597        // [`RestartStrategy::ALL`] as a single edit and this pin
8598        // sweeps the new arm by iteration; the paired
8599        // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
8600        // or this assertion trips. Every entry is further pinned to
8601        // open with an ASCII uppercase byte so a silent collapse of
8602        // the wire-form axis with the peer kebab-case
8603        // dispatcher-catalog axis (an entry byte-identical to a
8604        // sibling [`Self::discriminant`] kebab byte-string that would
8605        // let a wire-axis consumer accept the dispatcher-catalog
8606        // vocabulary) trips here rather than at a downstream K8s-CR
8607        // round-trip miss.
8608        //
8609        // Peer of the sibling
8610        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
8611        // (bd708bd) pin on the top-level typed-kind discriminator's
8612        // `PascalCase` wire byte-string axis, and of the sibling
8613        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
8614        // (cc42c0e) /
8615        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
8616        // (1898d77) pins on the OTP-appup discriminator's two-axis
8617        // roster split — the same closed-set exhaustive-roster
8618        // coverage discipline extended here onto the first M2
8619        // OTP-shape sibling-restart closed-set typed enum.
8620        //
8621        // Fail-before-pass-after locally verified by mutating one arm
8622        // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8623        // const family (e.g. dropping the trailing `e` from
8624        // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
8625        // but the `contains` check fires on the mutated arm; and by
8626        // shortening the roster to three entries — the length pin
8627        // fires first.
8628        assert_eq!(
8629            RestartStrategy::WIRE_NAMES.len(),
8630            RestartStrategy::ALL.len(),
8631            "RestartStrategy::WIRE_NAMES.len() must byte-equal \
8632             RestartStrategy::ALL.len() — a mismatch means the roster \
8633             and the enum's arm-set have drifted; downstream consumers \
8634             that fan through both will silently disagree on the \
8635             accepted arm-set"
8636        );
8637        for &variant in RestartStrategy::ALL {
8638            let wire = variant.as_str();
8639            assert!(
8640                RestartStrategy::WIRE_NAMES.contains(&wire),
8641                "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
8642                 be a member of RestartStrategy::WIRE_NAMES — the \
8643                 emitter and the roster have drifted out of lockstep"
8644            );
8645        }
8646        for tag in RestartStrategy::WIRE_NAMES {
8647            let first = tag.chars().next().unwrap_or_else(|| {
8648                panic!(
8649                    "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
8650                     a non-empty PascalCase byte-string"
8651                )
8652            });
8653            assert!(
8654                first.is_ascii_uppercase(),
8655                "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
8656                 with an ASCII uppercase byte (PascalCase wire form) — \
8657                 a lowercase entry would collide the wire-form axis \
8658                 with the peer kebab-case dispatcher-catalog axis \
8659                 [`RestartStrategy::discriminant`] serves"
8660            );
8661        }
8662    }
8663
8664    #[test]
8665    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8666        // Fail-before-pass-after pin on the forward accept-set of the
8667        // [`RestartStrategy::from_wire`] reverse projection: every
8668        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8669        // constant the [`RestartStrategy::as_str`] emitter walks parses
8670        // back to its paired variant. Any future arm addition that
8671        // grows the emitter's `as_str` match but forgets to grow the
8672        // parser's `from_wire` match silently splits the two halves of
8673        // the round-trip — the wire byte-string one non-serde consumer
8674        // parses from the one the emitter wrote — with the failure
8675        // surfacing at parse time far from the rebrand commit. Pinning
8676        // the four-arm accept-set here catches the drift at caixa-core
8677        // build time.
8678        //
8679        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8680        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8681        // accept-set pins on the peer closed-set typed-enum `str → Self`
8682        // axes.
8683        for (wire, expected) in [
8684            (
8685                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8686                RestartStrategy::OneForOne,
8687            ),
8688            (
8689                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8690                RestartStrategy::OneForAll,
8691            ),
8692            (
8693                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8694                RestartStrategy::RestForOne,
8695            ),
8696            (
8697                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8698                RestartStrategy::SimpleOneForOne,
8699            ),
8700        ] {
8701            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8702                panic!(
8703                    "RestartStrategy::from_wire({wire:?}) must accept every \
8704                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8705                     lifted canonical byte-string that RestartStrategy::{expected:?} \
8706                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8707                )
8708            });
8709            assert_eq!(
8710                parsed, expected,
8711                "RestartStrategy::from_wire({wire:?}) must return \
8712                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8713            );
8714        }
8715    }
8716
8717    #[test]
8718    fn restart_strategy_from_wire_round_trips_through_as_str() {
8719        // Fail-before-pass-after pin on the closed round-trip between
8720        // the forward [`RestartStrategy::as_str`] emitter and the
8721        // reverse [`RestartStrategy::from_wire`] parser: for every
8722        // variant in [`RestartStrategy::ALL`], parsing the emitter's
8723        // output must return exactly the same variant. Any per-arm
8724        // divergence — a future arm added to `as_str` but not
8725        // `from_wire`, an accidental copy-paste flip in one but not
8726        // the other — silently splits the emit and parse halves and
8727        // the failure surfaces at consumer parse time far from the
8728        // drift site. The `ALL`-iterating shape means a future arm
8729        // addition picks up the coverage by construction.
8730        //
8731        // Peer of the sibling
8732        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8733        // (18c7342) round-trip pin on
8734        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8735        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8736        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8737        for &variant in RestartStrategy::ALL {
8738            let wire = variant.as_str();
8739            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8740                panic!(
8741                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8742                     must be Some({variant:?}) — the two halves of the round-trip \
8743                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8744                     got None on wire byte-string {wire:?}"
8745                )
8746            });
8747            assert_eq!(
8748                parsed, variant,
8749                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8750                 must round-trip to the same variant; got {parsed:?}"
8751            );
8752        }
8753    }
8754
8755    #[test]
8756    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8757        // Fail-before-pass-after pin on the closed-set refusal
8758        // discipline of [`RestartStrategy::from_wire`]: every
8759        // byte-string outside the four-arm accept-set returns `None`
8760        // rather than silently collapsing onto the [`Default`]
8761        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8762        // exercised here sweeps the load-bearing drift shapes: the
8763        // empty string (a stripped serde-attribute drift), all-
8764        // whitespace strings (the canonical text-editor accidental
8765        // padding shape), the kebab-case dispatcher-catalog identities
8766        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8767        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8768        // derived [`std::str::FromStr`] accept-set, which parses the
8769        // *other* axis of this enum's two-axis split and must not leak
8770        // into the `from_wire` PascalCase-wire accept-set), the
8771        // lowercased single-word forms (`"oneforone"`), the padded
8772        // canonical scalar (`" OneForOne "`), the trailing-newline
8773        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8774        // (`"AllForOne"` — the canonical typo direction).
8775        //
8776        // Peer of the sibling
8777        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8778        // (2aa6d23) +
8779        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8780        // (18c7342) refusal pins on the peer closed-set typed-enum
8781        // axes.
8782        for bad in [
8783            "",
8784            " ",
8785            "\n",
8786            "\t",
8787            "one-for-one",
8788            "one-for-all",
8789            "rest-for-one",
8790            "simple-one-for-one",
8791            "oneforone",
8792            "OneForOnes",
8793            "one_for_one",
8794            "one for one",
8795            "ONEFORONE",
8796            "OneForOne ",
8797            " OneForOne",
8798            " SimpleOneForOne ",
8799            "OneForOne\n",
8800            "restforone",
8801            "REST_FOR_ONE",
8802            "AllForOne",
8803            "Simple",
8804            "?",
8805        ] {
8806            assert!(
8807                RestartStrategy::from_wire(bad).is_none(),
8808                "RestartStrategy::from_wire({bad:?}) must return None — the \
8809                 parser's accept-set is exactly the four RestartStrategy::as_str \
8810                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8811                 and this byte-string is outside that closed set"
8812            );
8813        }
8814    }
8815
8816    #[test]
8817    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8818        // Fail-before-pass-after pin on the fourth path of the four-path
8819        // convergence: `from_wire` (the reverse projection) inverts the
8820        // `Serialize` derive's wire byte-string on every variant.
8821        // Together with the pre-existing three-path convergence
8822        // (`Display` + `as_str` + `Serialize` all resolve to the same
8823        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8824        // pinned by
8825        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8826        // this closes the round-trip: the wire byte-string the
8827        // `Serialize` derive emits parses back to the same variant
8828        // through `from_wire`, so any future serde-attribute or variant-
8829        // rename drift on the emit half now surfaces as a matched drift
8830        // on the parse half at caixa-core build time — the two halves
8831        // migrate as a unit through the lifted consts on any future
8832        // rename, and the round-trip cannot silently split.
8833        //
8834        // Peer of the sibling
8835        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8836        // (18c7342) wire-format pin on
8837        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8838        for &variant in RestartStrategy::ALL {
8839            let wire = serde_json::to_string(&variant).unwrap();
8840            let unquoted = wire
8841                .strip_prefix('"')
8842                .and_then(|s| s.strip_suffix('"'))
8843                .expect("serialized RestartStrategy is a JSON string");
8844            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8845                panic!(
8846                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8847                     Serialize derive's wire byte-string for \
8848                     RestartStrategy::{variant:?} — the four-path convergence \
8849                     (Display + as_str + Serialize + from_wire) resolves through \
8850                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8851                )
8852            });
8853            assert_eq!(
8854                parsed, variant,
8855                "RestartStrategy::from_wire of the Serialize derive's wire \
8856                 byte-string for RestartStrategy::{variant:?} must round-trip \
8857                 to the same variant; got {parsed:?}"
8858            );
8859        }
8860    }
8861
8862    #[test]
8863    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8864        // Fail-before-pass-after byte-parity pin on the newly lifted
8865        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8866        // library trait impl and the substrate-primitive
8867        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8868        // the same four-arm accept-set across every arm the exhaustive
8869        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8870        // detour that routes the trait impl through a divergent projection
8871        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8872        // … }` re-inlining that opens a compile-time link to the un-
8873        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8874        // attribute drift that silently splits the wire byte-string from
8875        // every consumer that reaches for this typed dispatch, an
8876        // accidental swap onto the kebab-case dispatcher-catalog axis the
8877        // pre-existing [`std::str::FromStr`] impl parses through and which
8878        // would collide the two-axis wire/catalog split the sibling
8879        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8880        // trips at caixa-core test time under `assert_eq!` rather than at
8881        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8882        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8883        // carries so no arm's projection is covered only by the sibling
8884        // method-named `from_wire` path. Peer of the sibling
8885        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8886        // (3c83606),
8887        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8888        // (bf33136), and the M3
8889        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8890        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8891        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8892        // surface.
8893        for &variant in RestartStrategy::ALL {
8894            let wire = variant.as_str();
8895            assert_eq!(
8896                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8897                Ok(variant),
8898                "TryFrom<&str> impl on RestartStrategy must round-trip \
8899                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8900                 Ok(RestartStrategy::{variant:?}) — divergence from \
8901                 RestartStrategy::from_wire signals a silent detour off \
8902                 the substrate-primitive accessor"
8903            );
8904            assert_eq!(
8905                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8906                RestartStrategy::from_wire(wire),
8907                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8908                 RestartStrategy::from_wire on the same input"
8909            );
8910        }
8911    }
8912
8913    #[test]
8914    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8915        // Rejection witness on the `impl TryFrom<&str> for
8916        // RestartStrategy` — sweeps a candidate set of byte-strings
8917        // outside the four-arm PascalCase wire accept-set the sibling
8918        // [`RestartStrategy::as_str`] emits and asserts every one lands on
8919        // `Err(())`, so a future accidental widening of the trait impl's
8920        // accept-set (a stray additional
8921        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8922        // path, a silent inclusion of the kebab-case dispatcher-catalog
8923        // byte-string the pre-existing [`std::str::FromStr`] impl the
8924        // [`gen_platform::FromStrKind`] derive installs parses onto the
8925        // wire axis — which would collide the two-axis
8926        // wire/dispatcher-catalog split the sibling
8927        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8928        // an English-rebrand or plural-arm silent alias that would
8929        // widen the wire accept-set past the OTP-canonical four) trips at
8930        // caixa-core test time. The candidate set includes the empty
8931        // string, whitespace-only padding, the kebab-case dispatcher-
8932        // catalog byte-strings on the sibling axis (a caller who confuses
8933        // the two axes trips here rather than at a downstream consumer's
8934        // silent reject), a lowercase / uppercase / mixed-case fold of
8935        // each PascalCase arm (a caller who assumes case-fold acceptance
8936        // trips here), leading/trailing whitespace padding, the trailing-
8937        // newline shape, quote-wrapped candidates, and a residual set of
8938        // plausible-but-wrong English rebrand candidates. Peer of the
8939        // sibling
8940        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8941        // (3c83606) and
8942        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8943        // (6fd00cd) rejection witnesses.
8944        let rejected: &[&str] = &[
8945            "",
8946            " ",
8947            "\n",
8948            "\t",
8949            "one-for-one",
8950            "one-for-all",
8951            "rest-for-one",
8952            "simple-one-for-one",
8953            "oneforone",
8954            "one_for_one",
8955            "OneForOnes",
8956            "ONEFORONE",
8957            "oneforall",
8958            "restforone",
8959            "simpleoneforone",
8960            "OneForOne ",
8961            " OneForOne",
8962            " OneForAll ",
8963            "OneForOne\n",
8964            "RestForOne\t",
8965            "OneForEach",
8966            "AllForOne",
8967            "one for one",
8968            "\"OneForOne\"",
8969            "?",
8970        ];
8971        for &input in rejected {
8972            assert_eq!(
8973                <RestartStrategy as TryFrom<&str>>::try_from(input),
8974                Err(()),
8975                "TryFrom<&str> impl on RestartStrategy must reject the \
8976                 non-wire byte-string {input:?} — silent acceptance signals \
8977                 an accept-set widening off the paired \
8978                 RestartStrategy::from_wire resolver"
8979            );
8980        }
8981    }
8982
8983    #[test]
8984    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8985        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8986        // `from_wire` reverse projections must resolve identically on
8987        // *every* input, not just the ones [`RestartStrategy::ALL`]
8988        // enumerates. Sweeps a mixed candidate set spanning accepted
8989        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8990        // dispatcher-catalog byte-strings, empty, whitespace-padded,
8991        // quoted, English-rebrand candidates) inputs and asserts the
8992        // trait's `Result::ok()` projection byte-equals the method-named
8993        // resolver's `Option<Self>` return-shape on each, locking the two
8994        // paths together by construction so any future detour (a stray
8995        // `try_from` special-case that widens or narrows the accept-set
8996        // outside the paired `from_wire` resolver, an accidental swap
8997        // onto the kebab-case [`std::str::FromStr`] impl the
8998        // [`gen_platform::FromStrKind`] derive installs on the sibling
8999        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
9000        // the sibling
9001        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
9002        // pin — extends the round-trip discipline onto the M2-OTP-shape
9003        // sibling-restart axis.
9004        let candidates: &[&str] = &[
9005            "OneForOne",
9006            "OneForAll",
9007            "RestForOne",
9008            "SimpleOneForOne",
9009            "",
9010            "one-for-one",
9011            "one-for-all",
9012            "rest-for-one",
9013            "simple-one-for-one",
9014            "oneforone",
9015            "unknown",
9016            "OneForOne ",
9017            " OneForOne",
9018            "\"OneForOne\"",
9019            "OneForEach",
9020            "?",
9021        ];
9022        for &input in candidates {
9023            let via_trait: Option<RestartStrategy> =
9024                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
9025            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
9026            assert_eq!(
9027                via_trait, via_method,
9028                "TryFrom<&str> and from_wire must resolve identically on \
9029                 input {input:?} — divergence signals the two reverse-\
9030                 projection paths have drifted onto different accept-sets"
9031            );
9032        }
9033    }
9034
9035    #[test]
9036    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
9037        // Fail-before-pass-after byte-parity pin on the newly lifted
9038        // `impl From<RestartStrategy> for &'static str` — asserts the
9039        // standard-library trait impl and the substrate-primitive
9040        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
9041        // the same four-arm emit-set across every arm the exhaustive
9042        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
9043        // detour that routes the trait impl through a divergent
9044        // projection (a per-arm inline `match strategy { OneForOne =>
9045        // "OneForOne", … }` re-inlining that opens a compile-time link to
9046        // the un-lifted arm-literal, an accidental swap onto the sibling
9047        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
9048        // would collide the two-axis wire/catalog split the sibling
9049        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
9050        // at caixa-core test time under `assert_eq!` rather than at a
9051        // downstream `impl Into<&'static str>`-bound consumer's silent
9052        // split. Sweeps every one of the four arms
9053        // [`RestartStrategy::ALL`] carries so no arm's projection is
9054        // covered only by the sibling method-named `as_str` /
9055        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
9056        // `<&'static str as From<RestartStrategy>>::from` output in a
9057        // `const`-shape binding to make the `'static` lifetime promise a
9058        // build-time invariant — a future accidental downgrade of any of
9059        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9060        // constants to a non-`&'static str` (a `String::leak()`-produced
9061        // return, a `Box::leak`-cast) trips at caixa-core build time
9062        // rather than at a downstream `'static`-bound consumer.
9063        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9064        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9065        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9066        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9067        for &variant in RestartStrategy::ALL {
9068            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9069            let via_method: &'static str = variant.as_str();
9070            assert_eq!(
9071                via_trait, via_method,
9072                "From<RestartStrategy> for &'static str impl must round-trip \
9073                 RestartStrategy::{variant:?} to the same lifted \
9074                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
9075                 divergence signals a silent detour off the substrate-primitive \
9076                 accessor"
9077            );
9078            let via_into: &'static str = variant.into();
9079            assert_eq!(
9080                via_into, via_method,
9081                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
9082                 byte-equal RestartStrategy::as_str on the same input — the \
9083                 blanket-derived Into shape must resolve to the same as_str \
9084                 dispatch as the explicit From impl"
9085            );
9086        }
9087        assert_eq!(
9088            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9089            [
9090                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9091                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9092                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9093                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9094            ],
9095            "const-context RestartStrategy::as_str must resolve to the four \
9096             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
9097             downgrade of any arm to a non-const or non-static byte-string \
9098             breaks the `&'static str`-lifetime promise the paired \
9099             From<RestartStrategy> for &'static str impl carries by \
9100             construction"
9101        );
9102    }
9103
9104    #[test]
9105    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
9106        // Cross-axis partition pin: the paired trait-idiomatic
9107        // `From<RestartStrategy> for &'static str` forward projection and
9108        // the method-named [`RestartStrategy::as_str`] forward projection
9109        // must resolve identically on *every* arm, not just the ones
9110        // named in the primary byte-parity pin above. Sweeps every
9111        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
9112        // output byte-equals the method-named accessor's return-value on
9113        // each, locking the two forward-projection paths together by
9114        // construction so any future detour (a stray `From` special-case
9115        // that lands on a divergent per-arm literal outside the paired
9116        // `as_str` dispatch, a hypothetical rebrand touching one axis
9117        // without the other) trips at caixa-core test time. Peer of the
9118        // sibling reverse-projection partition pin
9119        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9120        // — extends the round-trip discipline onto the trait-idiomatic
9121        // *forward* axis, closing the two-way `Self ↔ &'static str`
9122        // round-trip on the trait-idiomatic pair
9123        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
9124        // well as the pre-existing method-named pair
9125        // (`as_str` + `from_wire`).
9126        for &variant in RestartStrategy::ALL {
9127            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9128            let via_method: &'static str = variant.as_str();
9129            assert_eq!(
9130                via_trait, via_method,
9131                "From<RestartStrategy> for &'static str and \
9132                 RestartStrategy::as_str must resolve identically on \
9133                 RestartStrategy::{variant:?} — divergence signals the \
9134                 two forward-projection paths have drifted onto different \
9135                 emit-sets"
9136            );
9137        }
9138        // Round-trip witness: every arm's forward `From` output re-parses
9139        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9140        // to the original variant. Closes the two-way `RestartStrategy ↔
9141        // &'static str` round-trip on the trait-idiomatic axis pair,
9142        // mirroring the pre-existing method-named `as_str` + `from_wire`
9143        // round-trip on the substrate-primitive axis pair.
9144        for &variant in RestartStrategy::ALL {
9145            let emitted: &'static str = variant.into();
9146            let re_parsed: Result<RestartStrategy, ()> =
9147                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9148            assert_eq!(
9149                re_parsed,
9150                Ok(variant),
9151                "trait-idiomatic axis pair must round-trip \
9152                 RestartStrategy::{variant:?} through `.into::<&'static \
9153                 str>()` and back through `TryFrom<&str>` — a break signals \
9154                 the forward-emit and reverse-parse axes have drifted onto \
9155                 different vocabularies"
9156            );
9157        }
9158    }
9159
9160    #[test]
9161    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9162        // Fail-before-pass-after byte-parity pin on the newly lifted
9163        // `impl From<&RestartStrategy> for &'static str` — asserts the
9164        // borrowed-input standard-library trait impl and the substrate-
9165        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
9166        // resolve to the same four-arm emit-set across every arm the
9167        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
9168        // `From` trait does not auto-derive the borrowed-input sibling
9169        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9170        // where T: Copy, U: From<T>` blanket in `core`), so the
9171        // borrowed-input axis is a distinct trait-idiomatic surface
9172        // that a `.iter().map(Into::into)` shape over
9173        // [`RestartStrategy::ALL`] (whose iterator yields
9174        // `&RestartStrategy`, not `RestartStrategy`) reaches through
9175        // this impl and no other — the paired owned-input
9176        // [`From<RestartStrategy>`] impl requires an explicit
9177        // `.copied()` / dereference before the trait fires.
9178        // Materializes the `<&'static str as
9179        // From<&RestartStrategy>>::from` output in a `const`-shape
9180        // binding to make the `'static` lifetime promise a build-time
9181        // invariant.
9182        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9183        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9184        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9185        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9186        for variant in RestartStrategy::ALL {
9187            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
9188            let via_method: &'static str = variant.as_str();
9189            assert_eq!(
9190                via_trait, via_method,
9191                "From<&RestartStrategy> for &'static str impl must \
9192                 round-trip &RestartStrategy::{variant:?} to the same \
9193                 lifted SUPERVISOR_ESTRATEGIA_* const \
9194                 RestartStrategy::as_str returns — divergence signals a \
9195                 silent detour off the substrate-primitive accessor"
9196            );
9197            let via_into: &'static str = variant.into();
9198            assert_eq!(
9199                via_into, via_method,
9200                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
9201                 must byte-equal RestartStrategy::as_str on the same input — \
9202                 the blanket-derived Into shape must resolve to the same \
9203                 as_str dispatch as the explicit From impl"
9204            );
9205        }
9206        assert_eq!(
9207            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9208            [
9209                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9210                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9211                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9212                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9213            ],
9214            "const-context RestartStrategy::as_str must resolve to the \
9215             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
9216             input From<&RestartStrategy> for &'static str impl inherits \
9217             its `'static` lifetime promise from the same accessor the \
9218             owned-input sibling routes through"
9219        );
9220    }
9221
9222    #[test]
9223    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9224        // Cross-axis partition pin: the paired trait-idiomatic
9225        // owned-input `From<RestartStrategy> for &'static str` (523157d
9226        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
9227        // &'static str` (this lift) forward projections must resolve
9228        // identically on every arm, locking the two input-shape paths
9229        // together so any future detour trips at caixa-core test time.
9230        // Then a witness that a `.iter().map(Into::into)` pipe over
9231        // [`RestartStrategy::ALL`] (whose iterator yields
9232        // `&RestartStrategy`) materializes the four-arm accept-set
9233        // through the borrowed-input axis alone — the exact shape a
9234        // future wasm-operator per-supervisor sibling-restart-strategy
9235        // diagnostic line, a future substrate-wide per-arm diagnostic
9236        // column, or a
9237        // `HashMap::<&'static str, RestartStrategy>::from_iter(
9238        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
9239        // per-strategy lookup reaches through — closing the two-way
9240        // owned/borrowed input-shape symmetry on the forward-projection
9241        // trait-idiomatic axis. Peer of the sibling
9242        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9243        // (64aa742) /
9244        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9245        // (5ab993a) /
9246        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9247        // (807b0b5) partition pins on the sibling closed-set typed-enum
9248        // discriminator axes — extends the borrowed-input axis
9249        // discipline onto the first M2 OTP-shape sibling-restart
9250        // closed-set typed enum on the caixa surface. Also closes the
9251        // direct two-way `&Self → &'static str → Self` round-trip via
9252        // the paired [`TryFrom<&str>`] axis — unlike the peer
9253        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
9254        // lowercase Portuguese diagnostic bytes while the reverse
9255        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
9256        // trip through an intermediate wire-vocab hop), the
9257        // [`RestartStrategy::as_str`] emit and
9258        // [`RestartStrategy::from_wire`] parse share the same
9259        // `PascalCase` vocabulary by construction, so the borrowed-
9260        // input forward axis and the reverse axis compose directly.
9261        for &variant in RestartStrategy::ALL {
9262            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9263            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
9264            assert_eq!(
9265                owned, borrowed,
9266                "From<RestartStrategy> and From<&RestartStrategy> for \
9267                 &'static str must resolve identically on \
9268                 RestartStrategy::{variant:?} — divergence signals the \
9269                 owned-input and borrowed-input forward-projection paths \
9270                 have drifted onto different emit-sets"
9271            );
9272        }
9273        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
9274        let via_method: Vec<&'static str> =
9275            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
9276        assert_eq!(
9277            via_iter, via_method,
9278            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
9279             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
9280             borrowed-input `From<&RestartStrategy> for &'static str` \
9281             axis is what makes the `.iter().map(Into::into)` shape route \
9282             through the substrate-primitive `RestartStrategy::as_str` \
9283             accessor rather than through a per-call-site `.copied()` / \
9284             dereference detour"
9285        );
9286        for variant in RestartStrategy::ALL {
9287            let emitted: &'static str = variant.into();
9288            let re_parsed: Result<RestartStrategy, ()> =
9289                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9290            assert_eq!(
9291                re_parsed,
9292                Ok(*variant),
9293                "trait-idiomatic borrowed-input forward-projection + \
9294                 reverse-projection axis pair must round-trip \
9295                 &RestartStrategy::{variant:?} through `.into::<&'static \
9296                 str>()` (via the borrowed-input axis) and back through \
9297                 `TryFrom<&str>` — a break signals the borrowed-input \
9298                 forward-emit and reverse-parse axes have drifted onto \
9299                 different vocabularies"
9300            );
9301        }
9302    }
9303
9304    #[test]
9305    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
9306        // Fail-before-pass-after byte-parity pin on the newly lifted
9307        // `impl From<RestartStrategy> for String` — asserts the
9308        // owned-`String`-returning standard-library trait impl and the
9309        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
9310        // accessor resolve to the same four-arm emit-set across every
9311        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
9312        // Rust's standard library does not carry a blanket
9313        // `impl<T: AsRef<str>> From<T> for String` (nor an
9314        // `impl<T: fmt::Display> From<T> for String`), so the
9315        // owned-`String` forward-projection axis is a distinct
9316        // trait-idiomatic surface that a
9317        // `let key: String = strategy.into();`-shaped call site
9318        // reaches through this impl and no other — the paired sibling
9319        // `From<RestartStrategy> for &'static str` impl forces every
9320        // owned-`String` call site through an explicit
9321        // `.to_owned()` / `String::from` restatement.
9322        for &variant in RestartStrategy::ALL {
9323            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
9324            let via_method: &'static str = variant.as_str();
9325            assert_eq!(
9326                via_trait.as_str(),
9327                via_method,
9328                "From<RestartStrategy> for String impl must round-trip \
9329                 RestartStrategy::{variant:?} to the same lifted \
9330                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9331                 returns — divergence signals a silent detour off the \
9332                 substrate-primitive accessor"
9333            );
9334            let via_into: String = variant.into();
9335            assert_eq!(
9336                via_into.as_str(),
9337                via_method,
9338                "Into<String>::into on RestartStrategy::{variant:?} must \
9339                 byte-equal RestartStrategy::as_str on the same input — the \
9340                 blanket-derived Into shape must resolve to the same as_str \
9341                 dispatch as the explicit From impl"
9342            );
9343        }
9344    }
9345
9346    #[test]
9347    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9348        // Cross-axis partition pin: the paired trait-idiomatic
9349        // owned-`String` `From<RestartStrategy> for String` (this lift)
9350        // and owned-`&'static str` `From<RestartStrategy> for &'static
9351        // str` (523157d) forward projections must resolve identically
9352        // on every arm, locking the two return-type-shape paths
9353        // together so any future detour trips at caixa-core test time.
9354        // Also byte-parity witness against the sibling
9355        // [`ToString::to_string`] surface routed through
9356        // [`std::fmt::Display`] — the three owned-heap-string paths
9357        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9358        // resolve identically on every arm so a future consumer that
9359        // picks any of the three lands on the same lifted
9360        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9361        // witness through the paired trait-idiomatic reverse
9362        // [`TryFrom<&str>`] axis on the owned-`String`'s
9363        // [`String::as_str`] borrow that closes the two-way
9364        // `Self → String → Self` round-trip on the trait-idiomatic
9365        // owned-`String` forward + reverse axis pair.
9366        for &variant in RestartStrategy::ALL {
9367            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9368            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9369            assert_eq!(
9370                owned_string.as_str(),
9371                owned_static,
9372                "From<RestartStrategy> for String and From<RestartStrategy> \
9373                 for &'static str must resolve identically on \
9374                 RestartStrategy::{variant:?} — divergence signals the \
9375                 owned-`String` and owned-`&'static str` forward-projection \
9376                 return-type-shape paths have drifted onto different \
9377                 emit-sets"
9378            );
9379            let via_to_string: String = variant.to_string();
9380            assert_eq!(
9381                owned_string, via_to_string,
9382                "From<RestartStrategy> for String must byte-equal \
9383                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9384                 divergence signals the trait-idiomatic owned-`String` \
9385                 forward-projection axis and the ToString-through-Display \
9386                 axis have drifted onto different emit-sets"
9387            );
9388        }
9389        let via_iter: Vec<String> = RestartStrategy::ALL
9390            .iter()
9391            .copied()
9392            .map(String::from)
9393            .collect();
9394        let via_method: Vec<String> = RestartStrategy::ALL
9395            .iter()
9396            .map(|s| s.as_str().to_owned())
9397            .collect();
9398        assert_eq!(
9399            via_iter, via_method,
9400            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9401             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9402             every arm — the owned-`String` `From<RestartStrategy> for \
9403             String` axis is what makes the `String::from` composition \
9404             route through the substrate-primitive `RestartStrategy::as_str` \
9405             accessor rather than through a per-call-site `.to_owned()` / \
9406             `String::from(strategy.as_str())` detour"
9407        );
9408        for &variant in RestartStrategy::ALL {
9409            let emitted: String = variant.into();
9410            let re_parsed: Result<RestartStrategy, ()> =
9411                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9412            assert_eq!(
9413                re_parsed,
9414                Ok(variant),
9415                "trait-idiomatic owned-`String` forward-projection + \
9416                 reverse-projection axis pair must round-trip \
9417                 RestartStrategy::{variant:?} through `.into::<String>()` \
9418                 and back through `TryFrom<&str>` on the owned-`String`'s \
9419                 String::as_str borrow — a break signals the owned-`String` \
9420                 forward-emit and reverse-parse axes have drifted onto \
9421                 different vocabularies"
9422            );
9423        }
9424    }
9425
9426    #[test]
9427    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9428        // Fail-before-pass-after byte-parity pin on the newly lifted
9429        // `impl From<&RestartStrategy> for String` — asserts the
9430        // borrowed-input owned-`String`-returning standard-library trait
9431        // impl and the substrate-primitive [`RestartStrategy::as_str`]
9432        // `pub const fn` accessor resolve to the same four-arm emit-set
9433        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9434        // enumerates. Rust's standard library does not carry a blanket
9435        // `impl<T: AsRef<str>> From<&T> for String` (nor an
9436        // `impl<T: fmt::Display> From<&T> for String`), so the
9437        // borrowed-input owned-`String` forward-projection axis is a
9438        // distinct trait-idiomatic surface that a
9439        // `let key: String = (&strategy).into();`-shaped call site
9440        // reaches through this impl and no other — the paired sibling
9441        // `From<RestartStrategy> for String` impl forces every
9442        // borrowed-input call site through an explicit `Copy` deref
9443        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9444        // `.to_string()` detour.
9445        for &variant in RestartStrategy::ALL {
9446            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9447            let via_method: &'static str = variant.as_str();
9448            assert_eq!(
9449                via_trait.as_str(),
9450                via_method,
9451                "From<&RestartStrategy> for String impl must round-trip \
9452                 &RestartStrategy::{variant:?} to the same lifted \
9453                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9454                 returns — divergence signals a silent detour off the \
9455                 substrate-primitive accessor"
9456            );
9457            let via_into: String = (&variant).into();
9458            assert_eq!(
9459                via_into.as_str(),
9460                via_method,
9461                "Into<String>::into on &RestartStrategy::{variant:?} must \
9462                 byte-equal RestartStrategy::as_str on the same input — the \
9463                 blanket-derived Into shape must resolve to the same as_str \
9464                 dispatch as the explicit From impl"
9465            );
9466        }
9467    }
9468
9469    #[test]
9470    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9471        // Cross-axis partition pin: the newly lifted trait-idiomatic
9472        // borrowed-input owned-`String` `From<&RestartStrategy> for
9473        // String` (this lift), the paired owned-input owned-`String`
9474        // `From<RestartStrategy> for String` (7baa18a), the paired
9475        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9476        // for &'static str` (e941836), and the paired owned-input
9477        // owned-`&'static str` `From<RestartStrategy> for &'static str`
9478        // (523157d) — every corner of the `{Self, &Self} × {&'static
9479        // str, String}` 2×2 trait-idiomatic projection family — must
9480        // resolve identically on every arm, locking the four
9481        // return-shape × input-shape paths together so any future
9482        // detour trips at caixa-core test time. Also byte-parity
9483        // witness against the sibling [`ToString::to_string`] surface
9484        // routed through [`std::fmt::Display`] and a direct round-trip
9485        // witness through the paired trait-idiomatic reverse
9486        // [`TryFrom<&str>`] axis on the owned-`String`'s
9487        // [`String::as_str`] borrow that closes the two-way
9488        // `&Self → String → Self` round-trip on the trait-idiomatic
9489        // borrowed-input owned-`String` forward + reverse axis pair.
9490        for &variant in RestartStrategy::ALL {
9491            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9492            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9493            let borrowed_static: &'static str =
9494                <&'static str as From<&RestartStrategy>>::from(&variant);
9495            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9496            assert_eq!(
9497                borrowed_string, owned_string,
9498                "From<&RestartStrategy> for String and From<RestartStrategy> \
9499                 for String must resolve identically on \
9500                 RestartStrategy::{variant:?} — divergence signals the \
9501                 borrowed-input and owned-input owned-`String` \
9502                 forward-projection input-shape paths have drifted onto \
9503                 different emit-sets"
9504            );
9505            assert_eq!(
9506                borrowed_string.as_str(),
9507                borrowed_static,
9508                "From<&RestartStrategy> for String and From<&RestartStrategy> \
9509                 for &'static str must resolve identically on \
9510                 RestartStrategy::{variant:?} — divergence signals the \
9511                 borrowed-input `&'static str` and owned-`String` \
9512                 return-shape paths have drifted onto different emit-sets"
9513            );
9514            assert_eq!(
9515                borrowed_string.as_str(),
9516                owned_static,
9517                "From<&RestartStrategy> for String and From<RestartStrategy> \
9518                 for &'static str must resolve identically on \
9519                 RestartStrategy::{variant:?} — divergence signals a break \
9520                 in the diagonal corner of the {{Self, &Self}} × \
9521                 {{&'static str, String}} 2×2 trait-idiomatic \
9522                 projection family"
9523            );
9524            let via_to_string: String = variant.to_string();
9525            assert_eq!(
9526                borrowed_string, via_to_string,
9527                "From<&RestartStrategy> for String must byte-equal \
9528                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9529                 divergence signals the trait-idiomatic borrowed-input \
9530                 owned-`String` forward-projection axis and the \
9531                 ToString-through-Display axis have drifted onto different \
9532                 emit-sets"
9533            );
9534        }
9535        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9536        let via_method: Vec<String> = RestartStrategy::ALL
9537            .iter()
9538            .map(|s| s.as_str().to_owned())
9539            .collect();
9540        assert_eq!(
9541            via_iter, via_method,
9542            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9543             call site whose iteration axis holds `&RestartStrategy` by \
9544             construction — must byte-equal `.iter().map(|s| \
9545             s.as_str().to_owned())` on every arm — the borrowed-input \
9546             owned-`String` `From<&RestartStrategy> for String` axis is \
9547             what makes the `String::from` composition route through the \
9548             substrate-primitive `RestartStrategy::as_str` accessor \
9549             without a spurious `Copy` deref (which would only be \
9550             reachable through the owned-input `From<RestartStrategy> for \
9551             String` axis by first calling `.copied()` on the iterator)"
9552        );
9553        for &variant in RestartStrategy::ALL {
9554            let emitted: String = (&variant).into();
9555            let re_parsed: Result<RestartStrategy, ()> =
9556                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9557            assert_eq!(
9558                re_parsed,
9559                Ok(variant),
9560                "trait-idiomatic borrowed-input owned-`String` \
9561                 forward-projection + reverse-projection axis pair must \
9562                 round-trip &RestartStrategy::{variant:?} through \
9563                 `.into::<String>()` on the borrowed-input surface and \
9564                 back through `TryFrom<&str>` on the owned-`String`'s \
9565                 String::as_str borrow — a break signals the \
9566                 borrowed-input owned-`String` forward-emit and \
9567                 reverse-parse axes have drifted onto different \
9568                 vocabularies"
9569            );
9570        }
9571    }
9572
9573    #[test]
9574    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9575        // Fail-before-pass-after byte-parity pin on the newly lifted
9576        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9577        // asserts the standard-library trait impl and the substrate-
9578        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9579        // accessor resolve to the same four-arm emit-set across every
9580        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9581        // enumerates. Rust's standard library does not carry a blanket
9582        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9583        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9584        // the `Cow<'static, str>` forward-projection axis is a
9585        // distinct trait-idiomatic surface that a
9586        // `let key: Cow<'static, str> = strategy.into();`-shaped call
9587        // site reaches through this impl and no other — the paired
9588        // sibling `From<RestartStrategy> for &'static str` and
9589        // `From<RestartStrategy> for String` impls force every
9590        // `Cow<'static, str>`-parameterized call site through a
9591        // `Cow::Borrowed(strategy.as_str())` /
9592        // `Cow::Owned(strategy.to_string())` composition whose type
9593        // bounds have no compile-time link back to the substrate
9594        // primitive.
9595        //
9596        // Also asserts the projection lands on the zero-alloc
9597        // [`std::borrow::Cow::Borrowed`] arm (not the
9598        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9599        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9600        // return lifetime by construction makes the borrowed arm the
9601        // type-correct projection with no runtime allocation. Any
9602        // future silent detour that routes the impl through the owned
9603        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9604        // that would allocate on every call site where the
9605        // `&'static str` return of [`super::RestartStrategy::as_str`]
9606        // makes the zero-alloc borrowed projection type-correct) trips
9607        // at caixa-core test time under the
9608        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9609        // than at a downstream `Cow<'static, str>`-bound consumer's
9610        // silent allocation.
9611        //
9612        // First peer on the substrate-wide trait-idiomatic
9613        // [`std::borrow::Cow<'static, str>`] forward-projection family
9614        // to extend the axis off the top-level [`super::CaixaKind`]
9615        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9616        // first M2 OTP-shape closed-set fieldless typed enum on the
9617        // caixa surface.
9618        for &variant in RestartStrategy::ALL {
9619            let via_trait: std::borrow::Cow<'static, str> =
9620                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9621            let via_method: &'static str = variant.as_str();
9622            assert_eq!(
9623                via_trait.as_ref(),
9624                via_method,
9625                "From<RestartStrategy> for Cow<'static, str> impl must \
9626                 round-trip RestartStrategy::{variant:?} to the same \
9627                 lifted SUPERVISOR_ESTRATEGIA_* const \
9628                 RestartStrategy::as_str returns — divergence signals a \
9629                 silent detour off the substrate-primitive accessor"
9630            );
9631            assert!(
9632                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9633                "From<RestartStrategy> for Cow<'static, str> impl must \
9634                 land on the zero-alloc Cow::Borrowed arm on \
9635                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9636                 signals the projection has silently allocated where \
9637                 the substrate-primitive RestartStrategy::as_str \
9638                 `&'static str` return makes the borrowed arm the \
9639                 type-correct projection"
9640            );
9641            let via_into: std::borrow::Cow<'static, str> = variant.into();
9642            assert_eq!(
9643                via_into.as_ref(),
9644                via_method,
9645                "Into<Cow<'static, str>>::into on \
9646                 RestartStrategy::{variant:?} must byte-equal \
9647                 RestartStrategy::as_str on the same input — the \
9648                 blanket-derived Into shape must resolve to the same \
9649                 as_str dispatch as the explicit From impl"
9650            );
9651            assert!(
9652                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9653                "Into<Cow<'static, str>>::into on \
9654                 RestartStrategy::{variant:?} must land on the \
9655                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9656                 Into shape must resolve to the same Cow::Borrowed \
9657                 dispatch as the explicit From impl"
9658            );
9659        }
9660    }
9661
9662    #[test]
9663    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9664        // Cross-axis partition pin: the newly lifted trait-idiomatic
9665        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9666        // (this lift), the paired owned-input `From<RestartStrategy>
9667        // for &'static str` (523157d), and the paired owned-input
9668        // `From<RestartStrategy> for String` (7baa18a) forward
9669        // projections must resolve identically on every arm, locking
9670        // the three return-shape paths together by construction so any
9671        // future detour trips at caixa-core test time. Also byte-parity
9672        // witness against the sibling [`ToString::to_string`] surface
9673        // routed through [`std::fmt::Display`] — every owned-heap-
9674        // string path (the `Cow::Owned` promotion of this axis's
9675        // `.into_owned()`, `From<RestartStrategy> for String`, and
9676        // `.to_string()`) resolves to the same lifted
9677        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9678        //
9679        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9680        // witness over [`super::RestartStrategy::ALL`] that
9681        // materializes the four-arm accept-set through the
9682        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9683        // shape a future `axum::response::IntoResponse` per-strategy
9684        // rejection-body composer, a future M4 admission-webhook
9685        // per-strategy rejection-reason emitter whose typing rules out
9686        // the sibling [`AsRef<str>`] borrowed return, or a future
9687        // substrate-wide per-strategy diagnostic surface that binds
9688        // through a [`Cow<'static, str>`] boundary reaches through.
9689        // The pipe witness also pins the zero-alloc discipline: every
9690        // element in the collected vector satisfies the
9691        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9692        // accidental silent-allocation regression on the pipe's
9693        // iteration axis is a caixa-core-test-time failure.
9694        for &variant in RestartStrategy::ALL {
9695            let via_cow: std::borrow::Cow<'static, str> =
9696                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9697            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9698            let via_string: String = <String as From<RestartStrategy>>::from(variant);
9699            assert_eq!(
9700                via_cow.as_ref(),
9701                via_static,
9702                "From<RestartStrategy> for Cow<'static, str> and \
9703                 From<RestartStrategy> for &'static str must resolve \
9704                 identically on RestartStrategy::{variant:?} — \
9705                 divergence signals the Cow<'static, str> and \
9706                 &'static str return-shape paths have drifted onto \
9707                 different emit-sets"
9708            );
9709            assert_eq!(
9710                via_cow.as_ref(),
9711                via_string.as_str(),
9712                "From<RestartStrategy> for Cow<'static, str> and \
9713                 From<RestartStrategy> for String must resolve \
9714                 identically on RestartStrategy::{variant:?} — \
9715                 divergence signals the Cow<'static, str> and String \
9716                 return-shape paths have drifted onto different \
9717                 emit-sets"
9718            );
9719            let via_to_string: String = variant.to_string();
9720            assert_eq!(
9721                via_cow.as_ref(),
9722                via_to_string.as_str(),
9723                "From<RestartStrategy> for Cow<'static, str> must \
9724                 byte-equal RestartStrategy::to_string on \
9725                 RestartStrategy::{variant:?} — divergence signals the \
9726                 trait-idiomatic Cow<'static, str> forward-projection \
9727                 axis and the ToString-through-Display axis have \
9728                 drifted onto different emit-sets"
9729            );
9730        }
9731        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9732            .iter()
9733            .copied()
9734            .map(std::borrow::Cow::from)
9735            .collect();
9736        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9737            .iter()
9738            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9739            .collect();
9740        assert_eq!(
9741            via_iter, via_method,
9742            "`.iter().copied().map(Cow::from)` over \
9743             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9744             Cow::Borrowed(s.as_str()))` on every arm — the \
9745             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9746             str>` axis is what makes the `Cow::from` composition \
9747             route through the substrate-primitive \
9748             `RestartStrategy::as_str` accessor with the zero-alloc \
9749             Cow::Borrowed arm by construction, rather than a \
9750             per-call-site `Cow::Owned(strategy.to_string())` \
9751             allocation"
9752        );
9753        for cow in &via_iter {
9754            assert!(
9755                matches!(cow, std::borrow::Cow::Borrowed(_)),
9756                "every element of the \
9757                 .iter().copied().map(Cow::from) pipe over \
9758                 RestartStrategy::ALL must land on the zero-alloc \
9759                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9760                 signals the pipe's iteration axis has silently \
9761                 allocated where the substrate-primitive \
9762                 RestartStrategy::as_str `&'static str` return makes \
9763                 the borrowed arm the type-correct projection"
9764            );
9765        }
9766    }
9767
9768    #[test]
9769    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9770        // Fail-before-pass-after byte-parity pin on the newly lifted
9771        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9772        // asserts the borrowed-input standard-library trait impl and
9773        // the substrate-primitive [`super::RestartStrategy::as_str`]
9774        // `pub const fn` accessor resolve to the same four-arm emit-
9775        // set across every arm the exhaustive
9776        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9777        // standard library does not carry a blanket
9778        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9779        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9780        // the borrowed-input `Cow<'static, str>` forward-projection
9781        // axis is a distinct trait-idiomatic surface that a
9782        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9783        // call site or a
9784        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9785        // reaches through this impl and no other — the paired owned-
9786        // input `From<RestartStrategy> for Cow<'static, str>` impl
9787        // (7dd28b3) forces every borrowed-input call site through an
9788        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9789        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9790        // bounds have no compile-time link back to the substrate
9791        // primitive.
9792        //
9793        // Also asserts the projection lands on the zero-alloc
9794        // [`std::borrow::Cow::Borrowed`] arm (not the
9795        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9796        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9797        // return lifetime by construction makes the borrowed arm the
9798        // type-correct projection with no runtime allocation on the
9799        // borrowed-input surface just as on the paired owned-input
9800        // surface.
9801        //
9802        // Second peer on the substrate-wide trait-idiomatic
9803        // [`std::borrow::Cow<'static, str>`] forward-projection family
9804        // on this enum — closes the `{Self, &Self}` input-shape
9805        // corner of the [`Cow<'static, str>`] axis on the first M2
9806        // OTP-shape closed-set fieldless typed enum peer on the caixa
9807        // surface (`:supervisor :estrategia`), exactly as d45c409
9808        // closed it on the top-level [`super::CaixaKind`] one commit
9809        // after the owning half (99c1735) landed. Every future
9810        // closed-set fieldless typed enum peer on the substrate is a
9811        // future target of the campaign.
9812        for &variant in RestartStrategy::ALL {
9813            let via_trait: std::borrow::Cow<'static, str> =
9814                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9815            let via_method: &'static str = variant.as_str();
9816            assert_eq!(
9817                via_trait.as_ref(),
9818                via_method,
9819                "From<&RestartStrategy> for Cow<'static, str> impl must \
9820                 round-trip &RestartStrategy::{variant:?} to the same \
9821                 lifted SUPERVISOR_ESTRATEGIA_* const \
9822                 RestartStrategy::as_str returns — divergence signals a \
9823                 silent detour off the substrate-primitive accessor"
9824            );
9825            assert!(
9826                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9827                "From<&RestartStrategy> for Cow<'static, str> impl must \
9828                 land on the zero-alloc Cow::Borrowed arm on \
9829                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9830                 signals the projection has silently allocated where \
9831                 the substrate-primitive RestartStrategy::as_str \
9832                 `&'static str` return makes the borrowed arm the \
9833                 type-correct projection"
9834            );
9835            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9836            assert_eq!(
9837                via_into.as_ref(),
9838                via_method,
9839                "Into<Cow<'static, str>>::into on \
9840                 &RestartStrategy::{variant:?} must byte-equal \
9841                 RestartStrategy::as_str on the same input — the \
9842                 blanket-derived Into shape must resolve to the same \
9843                 as_str dispatch as the explicit From impl"
9844            );
9845            assert!(
9846                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9847                "Into<Cow<'static, str>>::into on \
9848                 &RestartStrategy::{variant:?} must land on the \
9849                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9850                 Into shape must resolve to the same Cow::Borrowed \
9851                 dispatch as the explicit From impl"
9852            );
9853        }
9854    }
9855
9856    #[test]
9857    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9858        // Cross-axis partition pin: the newly lifted trait-idiomatic
9859        // borrowed-input `From<&RestartStrategy> for
9860        // std::borrow::Cow<'static, str>` (this lift), the paired
9861        // owned-input `From<RestartStrategy> for
9862        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9863        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9864        // for &'static str`, and the paired borrowed-input owned-
9865        // `String` `From<&RestartStrategy> for String` must resolve
9866        // identically on every arm, locking the four
9867        // return-shape × input-shape paths together by construction so
9868        // any future detour trips at caixa-core test time. Also byte-
9869        // parity witness against the sibling [`ToString::to_string`]
9870        // surface routed through [`std::fmt::Display`] — every owned-
9871        // heap-string path (this axis's `.into_owned()` promotion, the
9872        // paired [`From<&RestartStrategy> for String`], and
9873        // `.to_string()`) resolves to the same lifted
9874        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9875        //
9876        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9877        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9878        // `&RestartStrategy` by construction, so the borrowed-input
9879        // [`Cow<'static, str>`] axis is what routes the pipe through
9880        // the substrate-primitive [`super::RestartStrategy::as_str`]
9881        // accessor without a spurious [`Copy`] deref (which would only
9882        // be reachable through the owned-input
9883        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9884        // first calling `.copied()` on the iterator). The pipe witness
9885        // also pins the zero-alloc discipline: every element in the
9886        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9887        // arm predicate, so a future accidental silent-allocation
9888        // regression on the pipe's iteration axis is a caixa-core-
9889        // test-time failure.
9890        for &strategy in RestartStrategy::ALL {
9891            let borrowed_cow: std::borrow::Cow<'static, str> =
9892                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9893            let owned_cow: std::borrow::Cow<'static, str> =
9894                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9895            let borrowed_static: &'static str =
9896                <&'static str as From<&RestartStrategy>>::from(&strategy);
9897            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9898            assert_eq!(
9899                borrowed_cow, owned_cow,
9900                "From<&RestartStrategy> for Cow<'static, str> and \
9901                 From<RestartStrategy> for Cow<'static, str> must \
9902                 resolve identically on RestartStrategy::{strategy:?} — \
9903                 divergence signals the borrowed-input and owned-input \
9904                 Cow<'static, str> forward-projection input-shape \
9905                 paths have drifted onto different emit-sets"
9906            );
9907            assert_eq!(
9908                borrowed_cow.as_ref(),
9909                borrowed_static,
9910                "From<&RestartStrategy> for Cow<'static, str> and \
9911                 From<&RestartStrategy> for &'static str must resolve \
9912                 identically on RestartStrategy::{strategy:?} — \
9913                 divergence signals the borrowed-input Cow<'static, \
9914                 str> and &'static str return-shape paths have drifted \
9915                 onto different emit-sets"
9916            );
9917            assert_eq!(
9918                borrowed_cow.as_ref(),
9919                borrowed_string.as_str(),
9920                "From<&RestartStrategy> for Cow<'static, str> and \
9921                 From<&RestartStrategy> for String must resolve \
9922                 identically on RestartStrategy::{strategy:?} — \
9923                 divergence signals the borrowed-input Cow<'static, \
9924                 str> and owned-`String` return-shape paths have \
9925                 drifted onto different emit-sets"
9926            );
9927            let via_to_string: String = strategy.to_string();
9928            assert_eq!(
9929                borrowed_cow.as_ref(),
9930                via_to_string.as_str(),
9931                "From<&RestartStrategy> for Cow<'static, str> must \
9932                 byte-equal RestartStrategy::to_string on \
9933                 RestartStrategy::{strategy:?} — divergence signals \
9934                 the trait-idiomatic borrowed-input Cow<'static, str> \
9935                 forward-projection axis and the ToString-through-\
9936                 Display axis have drifted onto different emit-sets"
9937            );
9938        }
9939        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9940            .iter()
9941            .map(std::borrow::Cow::from)
9942            .collect();
9943        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9944            .iter()
9945            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9946            .collect();
9947        assert_eq!(
9948            via_iter, via_method,
9949            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9950             call site whose iteration axis holds `&RestartStrategy` \
9951             by construction — must byte-equal `.iter().map(|s| \
9952             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9953             input Cow<'static, str> `From<&RestartStrategy> for \
9954             Cow<'static, str>` axis is what makes the `Cow::from` \
9955             composition route through the substrate-primitive \
9956             `RestartStrategy::as_str` accessor with the zero-alloc \
9957             Cow::Borrowed arm by construction and without a spurious \
9958             `Copy` deref (which would only be reachable through the \
9959             owned-input `From<RestartStrategy> for Cow<'static, str>` \
9960             axis by first calling `.copied()` on the iterator)"
9961        );
9962        for cow in &via_iter {
9963            assert!(
9964                matches!(cow, std::borrow::Cow::Borrowed(_)),
9965                "every element of the .iter().map(Cow::from) pipe \
9966                 over RestartStrategy::ALL must land on the zero-\
9967                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9968                 any arm signals the pipe's iteration axis has \
9969                 silently allocated where the substrate-primitive \
9970                 RestartStrategy::as_str `&'static str` return makes \
9971                 the borrowed arm the type-correct projection"
9972            );
9973        }
9974    }
9975
9976    #[test]
9977    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9978        // Fail-before-pass-after byte-parity pin on the newly lifted
9979        // `impl From<RestartStrategy> for Box<str>` — asserts the
9980        // owned-input standard-library trait impl and the
9981        // substrate-primitive [`super::RestartStrategy::as_str`]
9982        // `pub const fn` accessor resolve to the same four-arm emit-
9983        // set across every arm the exhaustive
9984        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9985        // substrate-wide `Box<str>` forward-projection campaign tier
9986        // on the first M2 OTP-shape closed-set fieldless typed enum
9987        // peer on the caixa surface (`:supervisor :estrategia`),
9988        // immediately after the paired `Cow<'static, str>` axis
9989        // (7dd28b3 / ee577fd) closed the
9990        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9991        // 2×3 corner on this enum. Rust's standard library carries
9992        // `impl From<&str> for Box<str>` and
9993        // `impl From<String> for Box<str>` but no blanket
9994        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9995        // a distinct trait-idiomatic surface that a
9996        // `let key: Box<str> = strategy.into();`-shaped call site
9997        // reaches through this impl and no other — a paired
9998        // `Box::from(strategy.as_str())` open-code has no compile-
9999        // time link back to the substrate primitive.
10000        for &variant in RestartStrategy::ALL {
10001            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10002            let via_method: &'static str = variant.as_str();
10003            assert_eq!(
10004                via_trait.as_ref(),
10005                via_method,
10006                "From<RestartStrategy> for Box<str> impl must round-\
10007                 trip RestartStrategy::{variant:?} to the same lifted \
10008                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10009                 returns — divergence signals a silent detour off the \
10010                 substrate-primitive accessor"
10011            );
10012            let via_into: Box<str> = variant.into();
10013            assert_eq!(
10014                via_into.as_ref(),
10015                via_method,
10016                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
10017                 must byte-equal RestartStrategy::as_str on the same \
10018                 input — the blanket-derived Into shape must resolve \
10019                 to the same as_str dispatch as the explicit From impl"
10020            );
10021        }
10022    }
10023
10024    #[test]
10025    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10026        // Fail-before-pass-after byte-parity pin on the newly lifted
10027        // `impl From<&RestartStrategy> for Box<str>` — asserts the
10028        // borrowed-input standard-library trait impl and the
10029        // substrate-primitive [`super::RestartStrategy::as_str`]
10030        // `pub const fn` accessor resolve to the same four-arm emit-
10031        // set across every arm the exhaustive
10032        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10033        // standard library does not carry a blanket
10034        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10035        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10036        // so the borrowed-input `Box<str>` forward-projection axis
10037        // is a distinct trait-idiomatic surface that a
10038        // `let key: Box<str> = (&strategy).into();`-shaped call site
10039        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
10040        // shaped pipe reaches through this impl and no other — the
10041        // paired owned-input `From<RestartStrategy> for Box<str>`
10042        // impl (69ef45c) forces every borrowed-input call site
10043        // through an explicit `Copy` deref
10044        // (`Box::<str>::from((*strategy).as_str())`) or a
10045        // `Box::<str>::from(strategy.as_str())` open-code whose
10046        // type bounds have no compile-time link back to the
10047        // substrate primitive.
10048        //
10049        // Second peer on the substrate-wide trait-idiomatic
10050        // [`Box<str>`] forward-projection family on this enum —
10051        // closes the `{Self, &Self}` input-shape corner of the
10052        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
10053        // fieldless typed enum peer on the caixa surface
10054        // (`:supervisor :estrategia`), exactly as ee577fd closed
10055        // the paired [`Cow<'static, str>`] axis one commit after
10056        // its owning half (7dd28b3) landed. Every future closed-
10057        // set fieldless typed enum peer on the substrate is a
10058        // future target of the campaign.
10059        //
10060        // Also byte-parity witness against the paired owned-input
10061        // [`From<RestartStrategy> for Box<str>`] and the sibling
10062        // borrowed-input [`From<&RestartStrategy> for &'static str`],
10063        // [`From<&RestartStrategy> for String`], and
10064        // [`From<&RestartStrategy> for Cow<'static, str>`]
10065        // return-shape axes — locking the four
10066        // return-shape × input-shape paths together by construction
10067        // so any future detour trips at caixa-core test time. Then a
10068        // `.iter().map(Box::<str>::from)` pipe witness over
10069        // [`super::RestartStrategy::ALL`] — whose iterator yields
10070        // `&RestartStrategy` by construction, so the borrowed-input
10071        // [`Box<str>`] axis is what routes the pipe through the
10072        // substrate-primitive [`super::RestartStrategy::as_str`]
10073        // accessor without a spurious [`Copy`] deref (which would
10074        // only be reachable through the owned-input
10075        // [`From<RestartStrategy> for Box<str>`] axis by first
10076        // calling `.copied()` on the iterator).
10077        for &variant in RestartStrategy::ALL {
10078            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10079            let via_method: &'static str = variant.as_str();
10080            assert_eq!(
10081                via_trait.as_ref(),
10082                via_method,
10083                "From<&RestartStrategy> for Box<str> impl must \
10084                 round-trip &RestartStrategy::{variant:?} to the same \
10085                 lifted SUPERVISOR_ESTRATEGIA_* const \
10086                 RestartStrategy::as_str returns — divergence signals \
10087                 a silent detour off the substrate-primitive accessor"
10088            );
10089            let via_into: Box<str> = (&variant).into();
10090            assert_eq!(
10091                via_into.as_ref(),
10092                via_method,
10093                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
10094                 must byte-equal RestartStrategy::as_str on the same \
10095                 input — the blanket-derived Into shape must resolve \
10096                 to the same as_str dispatch as the explicit From impl"
10097            );
10098            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10099            assert_eq!(
10100                via_trait, owned_box,
10101                "From<&RestartStrategy> for Box<str> and \
10102                 From<RestartStrategy> for Box<str> must resolve \
10103                 identically on RestartStrategy::{variant:?} — \
10104                 divergence signals the borrowed-input and owned-input \
10105                 Box<str> forward-projection input-shape paths have \
10106                 drifted onto different emit-sets"
10107            );
10108            let borrowed_static: &'static str =
10109                <&'static str as From<&RestartStrategy>>::from(&variant);
10110            assert_eq!(
10111                via_trait.as_ref(),
10112                borrowed_static,
10113                "From<&RestartStrategy> for Box<str> and \
10114                 From<&RestartStrategy> for &'static str must resolve \
10115                 identically on RestartStrategy::{variant:?} — \
10116                 divergence signals the borrowed-input Box<str> and \
10117                 &'static str return-shape paths have drifted onto \
10118                 different emit-sets"
10119            );
10120            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10121            assert_eq!(
10122                via_trait.as_ref(),
10123                borrowed_string.as_str(),
10124                "From<&RestartStrategy> for Box<str> and \
10125                 From<&RestartStrategy> for String must resolve \
10126                 identically on RestartStrategy::{variant:?} — \
10127                 divergence signals the borrowed-input Box<str> and \
10128                 owned-`String` return-shape paths have drifted onto \
10129                 different emit-sets"
10130            );
10131            let borrowed_cow: std::borrow::Cow<'static, str> =
10132                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10133            assert_eq!(
10134                via_trait.as_ref(),
10135                borrowed_cow.as_ref(),
10136                "From<&RestartStrategy> for Box<str> and \
10137                 From<&RestartStrategy> for Cow<'static, str> must \
10138                 resolve identically on RestartStrategy::{variant:?} — \
10139                 divergence signals the borrowed-input Box<str> and \
10140                 Cow<'static, str> return-shape paths have drifted \
10141                 onto different emit-sets"
10142            );
10143        }
10144        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
10145        let via_method: Vec<Box<str>> = RestartStrategy::ALL
10146            .iter()
10147            .map(|s| Box::<str>::from(s.as_str()))
10148            .collect();
10149        assert_eq!(
10150            via_iter, via_method,
10151            "`.iter().map(Box::<str>::from)` over \
10152             RestartStrategy::ALL — a call site whose iteration axis \
10153             holds `&RestartStrategy` by construction — must byte-\
10154             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
10155             on every arm — the borrowed-input Box<str> \
10156             `From<&RestartStrategy> for Box<str>` axis is what \
10157             makes the `Box::<str>::from` composition route through \
10158             the substrate-primitive `RestartStrategy::as_str` \
10159             accessor without a spurious `Copy` deref (which would \
10160             only be reachable through the owned-input \
10161             `From<RestartStrategy> for Box<str>` axis by first \
10162             calling `.copied()` on the iterator)"
10163        );
10164    }
10165
10166    #[test]
10167    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
10168        // Fail-before-pass-after byte-parity pin on the newly lifted
10169        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
10170        // the owned-input standard-library trait impl and the
10171        // substrate-primitive [`super::RestartStrategy::as_str`]
10172        // `pub const fn` accessor resolve to the same four-arm emit-
10173        // set across every arm the exhaustive
10174        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10175        // substrate-wide [`std::sync::Arc<str>`] forward-projection
10176        // campaign tier on the first M2 OTP-shape closed-set fieldless
10177        // typed enum peer on the caixa surface
10178        // (`:supervisor :estrategia`), immediately after the paired
10179        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
10180        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
10181        // Box<str>}` 2×4 corner on this enum. Rust's standard library
10182        // carries `impl From<&str> for std::sync::Arc<str>` and
10183        // `impl From<String> for std::sync::Arc<str>` but no blanket
10184        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
10185        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
10186        // so this axis is a distinct trait-idiomatic surface that a
10187        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
10188        // site reaches through this impl and no other — a paired
10189        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10190        // has no compile-time link back to the substrate primitive,
10191        // and a two-step `std::sync::Arc::<str>::from(String::from(
10192        // strategy))` composition through the owned-`String` axis
10193        // allocates twice (once into the intermediate `String`, once
10194        // into the [`Arc<str>`] on the `From<String>` conversion)
10195        // where the single-step trait impl allocates once.
10196        //
10197        // Cross-axis byte-parity witness against the sibling owned-
10198        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
10199        // return-shape axes — locking the five return-shape paths on
10200        // the owned-input surface together by construction so any
10201        // future detour off the substrate-primitive
10202        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
10203        // core test time.
10204        for &variant in RestartStrategy::ALL {
10205            let via_trait: std::sync::Arc<str> =
10206                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10207            let via_method: &'static str = variant.as_str();
10208            assert_eq!(
10209                via_trait.as_ref(),
10210                via_method,
10211                "From<RestartStrategy> for std::sync::Arc<str> impl \
10212                 must round-trip RestartStrategy::{variant:?} to the \
10213                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10214                 RestartStrategy::as_str returns — divergence signals \
10215                 a silent detour off the substrate-primitive accessor"
10216            );
10217            let via_into: std::sync::Arc<str> = variant.into();
10218            assert_eq!(
10219                via_into.as_ref(),
10220                via_method,
10221                "Into<std::sync::Arc<str>>::into on \
10222                 RestartStrategy::{variant:?} must byte-equal \
10223                 RestartStrategy::as_str on the same input — the \
10224                 blanket-derived Into shape must resolve to the same \
10225                 as_str dispatch as the explicit From impl"
10226            );
10227            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10228            assert_eq!(
10229                via_trait.as_ref(),
10230                owned_static,
10231                "From<RestartStrategy> for std::sync::Arc<str> and \
10232                 From<RestartStrategy> for &'static str must resolve \
10233                 identically on RestartStrategy::{variant:?} — \
10234                 divergence signals the owned-input std::sync::Arc<str> \
10235                 and &'static str return-shape paths have drifted onto \
10236                 different emit-sets"
10237            );
10238            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10239            assert_eq!(
10240                via_trait.as_ref(),
10241                owned_string.as_str(),
10242                "From<RestartStrategy> for std::sync::Arc<str> and \
10243                 From<RestartStrategy> for String must resolve \
10244                 identically on RestartStrategy::{variant:?} — \
10245                 divergence signals the owned-input std::sync::Arc<str> \
10246                 and owned-`String` return-shape paths have drifted \
10247                 onto different emit-sets"
10248            );
10249            let owned_cow: std::borrow::Cow<'static, str> =
10250                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10251            assert_eq!(
10252                via_trait.as_ref(),
10253                owned_cow.as_ref(),
10254                "From<RestartStrategy> for std::sync::Arc<str> and \
10255                 From<RestartStrategy> for Cow<'static, str> must \
10256                 resolve identically on RestartStrategy::{variant:?} — \
10257                 divergence signals the owned-input std::sync::Arc<str> \
10258                 and Cow<'static, str> return-shape paths have drifted \
10259                 onto different emit-sets"
10260            );
10261            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10262            assert_eq!(
10263                via_trait.as_ref(),
10264                owned_box.as_ref(),
10265                "From<RestartStrategy> for std::sync::Arc<str> and \
10266                 From<RestartStrategy> for Box<str> must resolve \
10267                 identically on RestartStrategy::{variant:?} — \
10268                 divergence signals the owned-input std::sync::Arc<str> \
10269                 and Box<str> return-shape paths have drifted onto \
10270                 different emit-sets"
10271            );
10272        }
10273    }
10274
10275    #[test]
10276    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
10277        // Fail-before-pass-after byte-parity pin on the newly lifted
10278        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
10279        // asserts the borrowed-input standard-library trait impl and
10280        // the substrate-primitive [`super::RestartStrategy::as_str`]
10281        // `pub const fn` accessor resolve to the same four-arm emit-
10282        // set across every arm the exhaustive
10283        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10284        // standard library does not carry a blanket
10285        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
10286        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10287        // so the borrowed-input [`std::sync::Arc<str>`] forward-
10288        // projection axis is a distinct trait-idiomatic surface that a
10289        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
10290        // call site or a
10291        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
10292        // shaped pipe reaches through this impl and no other — the
10293        // paired owned-input
10294        // `From<RestartStrategy> for std::sync::Arc<str>` impl
10295        // (bca2ec8) forces every borrowed-input call site through an
10296        // explicit `Copy` deref
10297        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
10298        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10299        // whose type bounds have no compile-time link back to the
10300        // substrate primitive.
10301        //
10302        // Second peer on the substrate-wide trait-idiomatic
10303        // [`std::sync::Arc<str>`] forward-projection family on this
10304        // enum — closes the `{Self, &Self}` input-shape corner of
10305        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
10306        // closed-set fieldless typed enum peer on the caixa surface
10307        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
10308        // paired [`Box<str>`] axis one commit after its owning half
10309        // (69ef45c) landed. Every future closed-set fieldless typed
10310        // enum peer on the substrate is a future target of the
10311        // campaign.
10312        //
10313        // Also byte-parity witness against the paired owned-input
10314        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
10315        // sibling borrowed-input
10316        // [`From<&RestartStrategy> for &'static str`],
10317        // [`From<&RestartStrategy> for String`],
10318        // [`From<&RestartStrategy> for Cow<'static, str>`], and
10319        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
10320        // locking the five return-shape × input-shape paths together
10321        // by construction so any future detour trips at caixa-core
10322        // test time. Then a
10323        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
10324        // [`super::RestartStrategy::ALL`] — whose iterator yields
10325        // `&RestartStrategy` by construction, so the borrowed-input
10326        // [`std::sync::Arc<str>`] axis is what routes the pipe
10327        // through the substrate-primitive
10328        // [`super::RestartStrategy::as_str`] accessor without a
10329        // spurious [`Copy`] deref (which would only be reachable
10330        // through the owned-input
10331        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
10332        // first calling `.copied()` on the iterator).
10333        for &variant in RestartStrategy::ALL {
10334            let via_trait: std::sync::Arc<str> =
10335                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10336            let via_method: &'static str = variant.as_str();
10337            assert_eq!(
10338                via_trait.as_ref(),
10339                via_method,
10340                "From<&RestartStrategy> for std::sync::Arc<str> impl \
10341                 must round-trip &RestartStrategy::{variant:?} to the \
10342                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10343                 RestartStrategy::as_str returns — divergence signals \
10344                 a silent detour off the substrate-primitive accessor"
10345            );
10346            let via_into: std::sync::Arc<str> = (&variant).into();
10347            assert_eq!(
10348                via_into.as_ref(),
10349                via_method,
10350                "Into<std::sync::Arc<str>>::into on \
10351                 &RestartStrategy::{variant:?} must byte-equal \
10352                 RestartStrategy::as_str on the same input — the \
10353                 blanket-derived Into shape must resolve to the same \
10354                 as_str dispatch as the explicit From impl"
10355            );
10356            let owned_arc: std::sync::Arc<str> =
10357                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10358            assert_eq!(
10359                via_trait, owned_arc,
10360                "From<&RestartStrategy> for std::sync::Arc<str> and \
10361                 From<RestartStrategy> for std::sync::Arc<str> must \
10362                 resolve identically on RestartStrategy::{variant:?} — \
10363                 divergence signals the borrowed-input and owned-input \
10364                 std::sync::Arc<str> forward-projection input-shape \
10365                 paths have drifted onto different emit-sets"
10366            );
10367            let borrowed_static: &'static str =
10368                <&'static str as From<&RestartStrategy>>::from(&variant);
10369            assert_eq!(
10370                via_trait.as_ref(),
10371                borrowed_static,
10372                "From<&RestartStrategy> for std::sync::Arc<str> and \
10373                 From<&RestartStrategy> for &'static str must resolve \
10374                 identically on RestartStrategy::{variant:?} — \
10375                 divergence signals the borrowed-input \
10376                 std::sync::Arc<str> and &'static str return-shape \
10377                 paths have drifted onto different emit-sets"
10378            );
10379            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10380            assert_eq!(
10381                via_trait.as_ref(),
10382                borrowed_string.as_str(),
10383                "From<&RestartStrategy> for std::sync::Arc<str> and \
10384                 From<&RestartStrategy> for String must resolve \
10385                 identically on RestartStrategy::{variant:?} — \
10386                 divergence signals the borrowed-input \
10387                 std::sync::Arc<str> and owned-`String` return-shape \
10388                 paths have drifted onto different emit-sets"
10389            );
10390            let borrowed_cow: std::borrow::Cow<'static, str> =
10391                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10392            assert_eq!(
10393                via_trait.as_ref(),
10394                borrowed_cow.as_ref(),
10395                "From<&RestartStrategy> for std::sync::Arc<str> and \
10396                 From<&RestartStrategy> for Cow<'static, str> must \
10397                 resolve identically on RestartStrategy::{variant:?} — \
10398                 divergence signals the borrowed-input \
10399                 std::sync::Arc<str> and Cow<'static, str> return-shape \
10400                 paths have drifted onto different emit-sets"
10401            );
10402            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10403            assert_eq!(
10404                via_trait.as_ref(),
10405                borrowed_box.as_ref(),
10406                "From<&RestartStrategy> for std::sync::Arc<str> and \
10407                 From<&RestartStrategy> for Box<str> must resolve \
10408                 identically on RestartStrategy::{variant:?} — \
10409                 divergence signals the borrowed-input \
10410                 std::sync::Arc<str> and Box<str> return-shape paths \
10411                 have drifted onto different emit-sets"
10412            );
10413        }
10414        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10415            .iter()
10416            .map(std::sync::Arc::<str>::from)
10417            .collect();
10418        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10419            .iter()
10420            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10421            .collect();
10422        assert_eq!(
10423            via_iter, via_method,
10424            "`.iter().map(std::sync::Arc::<str>::from)` over \
10425             RestartStrategy::ALL — a call site whose iteration axis \
10426             holds `&RestartStrategy` by construction — must byte-\
10427             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10428             on every arm — the borrowed-input std::sync::Arc<str> \
10429             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10430             what makes the `std::sync::Arc::<str>::from` composition \
10431             route through the substrate-primitive \
10432             `RestartStrategy::as_str` accessor without a spurious \
10433             `Copy` deref (which would only be reachable through the \
10434             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10435             axis by first calling `.copied()` on the iterator)"
10436        );
10437    }
10438
10439    #[test]
10440    #[allow(
10441        clippy::too_many_lines,
10442        reason = "cross-axis partition pin folds the substrate-primitive \
10443                  as_str accessor's `.as_bytes()` byte-tail plus the \
10444                  paired str-view (AsRef<str>, Display, as_str) and \
10445                  reverse-projection ({&'static str, String, Cow<'static, \
10446                  str>, Box<str>, std::sync::Arc<str>}) return-shape \
10447                  axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
10448                  -bound-consumer witness plus a blake3::Hasher::update-\
10449                  shape byte-input surface witness into one exhaustive \
10450                  round-trip over RestartStrategy::ALL — the accepted \
10451                  line-count cost of opening the byte-view axis keyed \
10452                  to the substrate-primitive as_str accessor at the \
10453                  same test-site"
10454    )]
10455    #[allow(
10456        clippy::needless_borrows_for_generic_args,
10457        reason = "the borrowed-input surface (&variant) is exercised \
10458                  deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
10459                  and the `blake3::Hasher::update`-shape byte-input \
10460                  surface both accept either owned or borrowed input \
10461                  through the standard-library blanket \
10462                  `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
10463                  and this pin round-trips both input shapes to lock \
10464                  the borrowed-input path load-bearing against a \
10465                  future silent regression"
10466    )]
10467    fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
10468        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
10469        // function that binds its argument through the standard-library
10470        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
10471        // directly, without the caller open-coding the two-hop
10472        // `estrategia.as_str().as_bytes()` composition. Lifted to the top
10473        // of the function per `clippy::items_after_statements`.
10474        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
10475            t.as_ref().to_vec()
10476        }
10477        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
10478        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10479        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
10480        // signature so a per-supervisor BLAKE3 content-address closure
10481        // that composes `hasher.update(estrategia)` on the
10482        // [`crate::Lacre`] closure builder reaches the substrate-primitive
10483        // `as_str` accessor through the [`super::RestartStrategy`]
10484        // `AsRef<[u8]>` axis and no other. Lifted to the top of the
10485        // function per `clippy::items_after_statements`.
10486        struct MockHasher(Vec<u8>);
10487        impl MockHasher {
10488            fn new() -> Self {
10489                Self(Vec::new())
10490            }
10491            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
10492                self.0.extend_from_slice(bytes.as_ref());
10493                self
10494            }
10495            fn finalize(self) -> Vec<u8> {
10496                self.0
10497            }
10498        }
10499
10500        // Fail-before-pass-after byte-parity pin on the newly lifted
10501        // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
10502        // idiomatic byte-view standard-library impl and the substrate-
10503        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10504        // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
10505        // `PascalCase` wire byte-string emit-set across every arm the
10506        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10507        // Opens the trait-idiomatic byte-view axis onto the first M2
10508        // OTP-shape closed-set fieldless typed enum peer on the caixa
10509        // surface (`:supervisor :estrategia`), extending the substrate-
10510        // wide byte-view campaign the sibling
10511        // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
10512        //
10513        // Rust's standard library carries `impl AsRef<[u8]> for str` and
10514        // `impl AsRef<[u8]> for String`, so a two-hop composition
10515        // `estrategia.as_str().as_bytes()` (or the equally two-hop
10516        // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
10517        // through the pre-existing str-view axis alone. But that two-hop
10518        // shape has no compile-time link back to the byte-projection
10519        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
10520        // consumer to open-code the two-hop composition at every call
10521        // site, and admits a silent split whenever a future call site
10522        // takes a sibling reverse-projection axis whose `.as_bytes()`
10523        // byte-tail carries no compile-time byte-view surface. This
10524        // impl closes the byte-view axis at the substrate-primitive
10525        // [`super::RestartStrategy::as_str`] accessor so every future
10526        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
10527        // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
10528        // the paired str-view axes already return through — through one
10529        // trait dispatch.
10530        for &variant in RestartStrategy::ALL {
10531            let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10532            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
10533            assert_eq!(
10534                via_trait, via_method_bytes,
10535                "AsRef<[u8]> for RestartStrategy impl must byte-equal \
10536                 RestartStrategy::as_str().as_bytes() on \
10537                 RestartStrategy::{variant:?} — divergence signals a \
10538                 silent detour off the substrate-primitive accessor"
10539            );
10540            // Cross-axis witness against the paired str-view axes'
10541            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
10542            // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
10543            // all resolve to the same lifted
10544            // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
10545            // roster, and the byte-view axis must byte-equal each of
10546            // their `.as_bytes()` byte-tails by construction — locking
10547            // the str-view and byte-view axes together at the
10548            // substrate-primitive accessor.
10549            let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
10550            assert_eq!(
10551                via_trait,
10552                str_view_ref.as_bytes(),
10553                "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
10554                 RestartStrategy must resolve to byte-equal byte-tails \
10555                 on RestartStrategy::{variant:?} — divergence signals \
10556                 the byte-view and str-view axes have drifted off the \
10557                 same substrate-primitive as_str accessor"
10558            );
10559            let display_bytes = variant.to_string();
10560            assert_eq!(
10561                via_trait,
10562                display_bytes.as_bytes(),
10563                "AsRef<[u8]> for RestartStrategy and \
10564                 <RestartStrategy as std::fmt::Display>::to_string must \
10565                 resolve to byte-equal byte-tails on \
10566                 RestartStrategy::{variant:?} — divergence signals the \
10567                 byte-view axis and the Display formatter axis have \
10568                 drifted off the same substrate-primitive as_str \
10569                 accessor"
10570            );
10571            // Cross-axis witness against the paired reverse-projection
10572            // axes' `.as_bytes()` byte-tails: every one of `{&'static
10573            // str, String, Cow<'static, str>, Box<str>,
10574            // std::sync::Arc<str>}` allocates (or borrows) the same
10575            // `PascalCase` wire byte-string the substrate-primitive
10576            // accessor emits, so the byte-view axis must byte-equal
10577            // each of their `.as_bytes()` byte-tails by construction.
10578            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10579            assert_eq!(
10580                via_trait,
10581                owned_static.as_bytes(),
10582                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10583                 for &'static str must resolve to byte-equal byte-tails \
10584                 on RestartStrategy::{variant:?}"
10585            );
10586            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10587            assert_eq!(
10588                via_trait,
10589                owned_string.as_bytes(),
10590                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10591                 for String must resolve to byte-equal byte-tails on \
10592                 RestartStrategy::{variant:?}"
10593            );
10594            let owned_cow: std::borrow::Cow<'static, str> =
10595                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10596            assert_eq!(
10597                via_trait,
10598                owned_cow.as_bytes(),
10599                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10600                 for Cow<'static, str> must resolve to byte-equal byte-\
10601                 tails on RestartStrategy::{variant:?}"
10602            );
10603            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10604            assert_eq!(
10605                via_trait,
10606                owned_box.as_bytes(),
10607                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10608                 for Box<str> must resolve to byte-equal byte-tails on \
10609                 RestartStrategy::{variant:?}"
10610            );
10611            let owned_arc: std::sync::Arc<str> =
10612                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10613            assert_eq!(
10614                via_trait,
10615                owned_arc.as_bytes(),
10616                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10617                 for std::sync::Arc<str> must resolve to byte-equal byte-\
10618                 tails on RestartStrategy::{variant:?}"
10619            );
10620        }
10621        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
10622        // input function `generic_bytes_sink` (lifted above per
10623        // `clippy::items_after_statements`) accepts a
10624        // [`super::RestartStrategy`] directly through the trait bound,
10625        // without the caller open-coding the two-hop
10626        // `estrategia.as_str().as_bytes()` composition. This is the
10627        // shape that reaches the caixa-lacre BLAKE3 content-address
10628        // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
10629        // input surface through this impl and no other.
10630        for &variant in RestartStrategy::ALL {
10631            let via_generic = generic_bytes_sink(variant);
10632            let via_borrowed_generic = generic_bytes_sink(&variant);
10633            let via_method_bytes = variant.as_str().as_bytes().to_vec();
10634            assert_eq!(
10635                via_generic, via_method_bytes,
10636                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10637                 RestartStrategy::{variant:?} must yield the same byte-\
10638                 tail RestartStrategy::as_str().as_bytes() returns — \
10639                 divergence signals the byte-view axis fails to bridge \
10640                 a generic byte-input trait bound to the substrate-\
10641                 primitive accessor"
10642            );
10643            assert_eq!(
10644                via_borrowed_generic, via_method_bytes,
10645                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10646                 &RestartStrategy::{variant:?} must yield the same byte-\
10647                 tail RestartStrategy::as_str().as_bytes() returns — \
10648                 the borrowed-input surface must resolve to the same \
10649                 as_str dispatch"
10650            );
10651        }
10652        // `blake3::Hasher::update`-shape byte-input surface witness on
10653        // the caixa-lacre compounding target: the `MockHasher` (lifted
10654        // above per `clippy::items_after_statements`) mirrors
10655        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10656        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
10657        // signature and accepts a [`super::RestartStrategy`] directly,
10658        // routing its byte-tail through the substrate-primitive
10659        // `as_str` accessor — the shape a future per-supervisor BLAKE3
10660        // content-address closure composes to fold an `:estrategia`
10661        // discriminator byte-tag into the [`crate::Lacre`] closure
10662        // body.
10663        for &variant in RestartStrategy::ALL {
10664            let mut owned_hasher = MockHasher::new();
10665            owned_hasher.update(variant);
10666            let owned_folded = owned_hasher.finalize();
10667            assert_eq!(
10668                owned_folded,
10669                variant.as_str().as_bytes(),
10670                "`hasher.update(estrategia)`-shape composition on \
10671                 RestartStrategy::{variant:?} must fold the same byte-\
10672                 tail RestartStrategy::as_str().as_bytes() returns — \
10673                 the shape a future per-supervisor BLAKE3 content-\
10674                 address closure composes to fold an `:estrategia` \
10675                 discriminator byte-tag into the Lacre closure body"
10676            );
10677            let mut borrowed_hasher = MockHasher::new();
10678            borrowed_hasher.update(&variant);
10679            let borrowed_folded = borrowed_hasher.finalize();
10680            assert_eq!(
10681                borrowed_folded,
10682                variant.as_str().as_bytes(),
10683                "`hasher.update(&estrategia)`-shape composition on \
10684                 &RestartStrategy::{variant:?} must fold the same byte-\
10685                 tail RestartStrategy::as_str().as_bytes() returns — \
10686                 the borrowed-input surface must resolve to the same \
10687                 as_str dispatch"
10688            );
10689        }
10690    }
10691
10692    #[test]
10693    #[expect(
10694        clippy::too_many_lines,
10695        reason = "the byte-owned reverse-projection axis is extended \
10696                  here onto the first M2-OTP-shape closed-set fieldless \
10697                  typed-enum peer, so the pin binds the new impl against \
10698                  every paired byte-view and str-owned axis on the same \
10699                  enum plus a generic <T: Into<Vec<u8>>>-bound consumer \
10700                  witness and a std::io::Write::write_all-shape owned-\
10701                  byte-sink surface witness on both owned and borrowed \
10702                  input shapes to lock the whole family against a future \
10703                  silent regression"
10704    )]
10705    fn restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
10706        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
10707        // owned-byte-input function accepts a [`super::RestartStrategy`]
10708        // directly through the trait bound, without the caller open-
10709        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
10710        // composition. Lifted to the top of the function per
10711        // `clippy::items_after_statements`.
10712        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
10713            t.into()
10714        }
10715        // `std::io::Write::write_all`-shape owned-byte-sink surface
10716        // mock: mirrors `std::io::Write::write_all` /
10717        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
10718        // byte-sink that consumes a `Vec<u8>` payload via
10719        // `Into<Vec<u8>>`, so a future per-supervisor per-`:estrategia`
10720        // audit-log emit reaches the substrate-primitive `as_str`
10721        // accessor through the byte-owned reverse-projection axis and
10722        // no other. Lifted to the top of the function per
10723        // `clippy::items_after_statements`.
10724        struct MockOwnedByteSink(Vec<u8>);
10725        impl MockOwnedByteSink {
10726            fn new() -> Self {
10727                Self(Vec::new())
10728            }
10729            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
10730                self.0.extend_from_slice(&bytes.into());
10731                self
10732            }
10733            fn finalize(self) -> Vec<u8> {
10734                self.0
10735            }
10736        }
10737
10738        // Fail-before-pass-after byte-parity pin on the newly lifted
10739        // `impl From<RestartStrategy> for Vec<u8>` and
10740        // `impl From<&RestartStrategy> for Vec<u8>` — asserts the trait-
10741        // idiomatic byte-owned reverse-projection standard-library
10742        // impls and the substrate-primitive
10743        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
10744        // `.as_bytes().to_vec()` byte-tail resolve to the same four-arm
10745        // PascalCase wire byte-string emit-set across every arm the
10746        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10747        // Extends the substrate-wide trait-idiomatic byte-owned
10748        // reverse-projection axis onto the first M2-OTP-shape closed-
10749        // set fieldless typed-enum peer on the caixa surface
10750        // (`:supervisor :estrategia`), matching the trajectory the
10751        // first-mover [`super::crate::CaixaKind`] lift (b245fd6), the
10752        // second-mover [`super::crate::dialeto::CaixaDialeto`] lift
10753        // (4cceaf5), and the third-mover
10754        // [`super::crate::dep::DepList`] lift (e974ca2) established
10755        // across the caixa-core-internal tier.
10756        for &variant in RestartStrategy::ALL {
10757            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
10758            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
10759            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
10760            assert_eq!(
10761                via_owned_from, via_method_bytes,
10762                "From<RestartStrategy> for Vec<u8> impl must byte-equal \
10763                 RestartStrategy::as_str().as_bytes().to_vec() on \
10764                 RestartStrategy::{variant:?} — divergence signals a \
10765                 silent detour off the substrate-primitive accessor"
10766            );
10767            assert_eq!(
10768                via_borrowed_from, via_method_bytes,
10769                "From<&RestartStrategy> for Vec<u8> impl must byte-\
10770                 equal RestartStrategy::as_str().as_bytes().to_vec() \
10771                 on RestartStrategy::{variant:?} — divergence signals \
10772                 a silent detour off the substrate-primitive accessor"
10773            );
10774            assert_eq!(
10775                via_owned_from, via_borrowed_from,
10776                "From<RestartStrategy> for Vec<u8> and \
10777                 From<&RestartStrategy> for Vec<u8> must byte-equal \
10778                 each other on RestartStrategy::{variant:?} — \
10779                 divergence signals the owned-input and borrowed-input \
10780                 paths have drifted off the same substrate-primitive \
10781                 as_str accessor"
10782            );
10783            // Cross-axis witness against the paired [`AsRef<[u8]>`]
10784            // borrowed byte-view axis (cd4c4e0): the byte-owned
10785            // reverse-projection axis must byte-equal the paired
10786            // borrowed byte-view axis by construction — locking the
10787            // byte-view and byte-owned axes together at the substrate-
10788            // primitive accessor.
10789            let borrowed_bytes: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10790            assert_eq!(
10791                via_owned_from,
10792                borrowed_bytes.to_vec(),
10793                "From<RestartStrategy> for Vec<u8> and AsRef<[u8]> \
10794                 for RestartStrategy must resolve to byte-equal byte-\
10795                 tails on RestartStrategy::{variant:?} — divergence \
10796                 signals the byte-owned and byte-view axes have \
10797                 drifted off the same substrate-primitive as_str \
10798                 accessor"
10799            );
10800            // Cross-axis witness against the str-owned reverse-
10801            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
10802            // byte-tails: every one of `{String, Cow<'static, str>,
10803            // Box<str>, std::sync::Arc<str>, std::rc::Rc<str>}`
10804            // allocates (or borrows) the same PascalCase wire byte-
10805            // string the substrate-primitive accessor emits, so the
10806            // byte-owned axis must byte-equal each of their owned
10807            // byte-tails by construction.
10808            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10809            assert_eq!(
10810                via_owned_from,
10811                owned_string.into_bytes(),
10812                "From<RestartStrategy> for Vec<u8> and \
10813                 String::from(strategy).into_bytes() must resolve to \
10814                 byte-equal byte-tails on RestartStrategy::{variant:?}"
10815            );
10816            let owned_cow: std::borrow::Cow<'static, str> =
10817                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10818            assert_eq!(
10819                via_owned_from,
10820                owned_cow.as_bytes().to_vec(),
10821                "From<RestartStrategy> for Vec<u8> and \
10822                 From<RestartStrategy> for Cow<'static, str> must \
10823                 resolve to byte-equal byte-tails on \
10824                 RestartStrategy::{variant:?}"
10825            );
10826            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10827            assert_eq!(
10828                via_owned_from,
10829                owned_box.as_bytes().to_vec(),
10830                "From<RestartStrategy> for Vec<u8> and \
10831                 From<RestartStrategy> for Box<str> must resolve to \
10832                 byte-equal byte-tails on RestartStrategy::{variant:?}"
10833            );
10834            let owned_arc: std::sync::Arc<str> =
10835                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10836            assert_eq!(
10837                via_owned_from,
10838                owned_arc.as_bytes().to_vec(),
10839                "From<RestartStrategy> for Vec<u8> and \
10840                 From<RestartStrategy> for std::sync::Arc<str> must \
10841                 resolve to byte-equal byte-tails on \
10842                 RestartStrategy::{variant:?}"
10843            );
10844        }
10845        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
10846        // and borrowed input shapes: the generic owned-byte-input
10847        // function `generic_owned_bytes_sink` (lifted above per
10848        // `clippy::items_after_statements`) accepts a
10849        // [`super::RestartStrategy`] and a `&RestartStrategy`
10850        // directly through the trait bound, without the caller open-
10851        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
10852        // composition.
10853        for &variant in RestartStrategy::ALL {
10854            let via_generic_owned = generic_owned_bytes_sink(variant);
10855            // Bind the borrowed-input path through an explicit
10856            // `&RestartStrategy` local so the generic-consumer witness
10857            // routes through `From<&RestartStrategy> for Vec<u8>` (T
10858            // binds to `&RestartStrategy`) rather than clippy-collapsing
10859            // the borrow onto the owned-input peer.
10860            let variant_ref: &RestartStrategy = &variant;
10861            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
10862            let via_method_bytes = variant.as_str().as_bytes().to_vec();
10863            assert_eq!(
10864                via_generic_owned, via_method_bytes,
10865                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
10866                 RestartStrategy::{variant:?} must yield the same byte-\
10867                 tail RestartStrategy::as_str().as_bytes() returns — \
10868                 divergence signals the byte-owned axis fails to bridge \
10869                 a generic owned-byte-input trait bound to the \
10870                 substrate-primitive accessor"
10871            );
10872            assert_eq!(
10873                via_generic_borrowed, via_method_bytes,
10874                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
10875                 &RestartStrategy::{variant:?} must yield the same byte-\
10876                 tail RestartStrategy::as_str().as_bytes() returns — \
10877                 the borrowed-input surface must resolve to the same \
10878                 as_str dispatch"
10879            );
10880        }
10881        // `std::io::Write::write_all`-shape owned-byte-sink surface
10882        // witness: the `MockOwnedByteSink` (lifted above per
10883        // `clippy::items_after_statements`) mirrors
10884        // `std::io::Write::write_all` /
10885        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
10886        // bound owned-byte input signature and accepts a
10887        // [`super::RestartStrategy`] directly on both owned and
10888        // borrowed input shapes, routing its byte-tail through the
10889        // substrate-primitive `as_str` accessor — the shape a future
10890        // per-supervisor per-`:estrategia` audit-log emit composes to
10891        // fold an `:estrategia` discriminator byte-tag into a
10892        // downstream owned-byte-sink surface.
10893        for &variant in RestartStrategy::ALL {
10894            let mut owned_sink = MockOwnedByteSink::new();
10895            owned_sink.write_all(variant);
10896            let owned_folded = owned_sink.finalize();
10897            assert_eq!(
10898                owned_folded,
10899                variant.as_str().as_bytes(),
10900                "`sink.write_all(strategy)`-shape composition on \
10901                 RestartStrategy::{variant:?} must fold the same byte-\
10902                 tail RestartStrategy::as_str().as_bytes() returns"
10903            );
10904            let mut borrowed_sink = MockOwnedByteSink::new();
10905            let variant_ref: &RestartStrategy = &variant;
10906            borrowed_sink.write_all(variant_ref);
10907            let borrowed_folded = borrowed_sink.finalize();
10908            assert_eq!(
10909                borrowed_folded,
10910                variant.as_str().as_bytes(),
10911                "`sink.write_all(&strategy)`-shape composition on \
10912                 &RestartStrategy::{variant:?} must fold the same byte-\
10913                 tail RestartStrategy::as_str().as_bytes() returns — \
10914                 the borrowed-input surface must resolve to the same \
10915                 as_str dispatch"
10916            );
10917        }
10918    }
10919
10920    #[test]
10921    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
10922        // Fail-before-pass-after byte-parity pin on the newly lifted
10923        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
10924        // library trait impl and the substrate-primitive
10925        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
10926        // the same three-arm accept-set across every arm the exhaustive
10927        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10928        // detour that routes the trait impl through a divergent
10929        // projection (a per-arm inline `match s { "Permanent" =>
10930        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
10931        // link to the un-lifted arm-literal, a hypothetical
10932        // `#[serde(rename_all = "…")]` attribute drift that silently
10933        // splits the wire byte-string from every consumer that reaches
10934        // for this typed dispatch, an accidental swap onto the kebab-case
10935        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
10936        // impl parses through and which would collide the two-axis
10937        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
10938        // doc block makes load-bearing) trips at caixa-core test time
10939        // under `assert_eq!` rather than at a downstream
10940        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
10941        // every one of the three arms [`RestartPolicy::ALL`] carries so
10942        // no arm's projection is covered only by the sibling method-
10943        // named `from_wire` path. Peer of the sibling
10944        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
10945        // (5b828ed) — extends the trait-idiomatic reverse-projection
10946        // axis onto the third and final M2-OTP-shape closed-set typed
10947        // enum on the caixa surface (the paired per-child restart-
10948        // decision-policy sibling on the same M2 `:supervisor` slot).
10949        for &variant in RestartPolicy::ALL {
10950            let wire = variant.as_str();
10951            assert_eq!(
10952                <RestartPolicy as TryFrom<&str>>::try_from(wire),
10953                Ok(variant),
10954                "TryFrom<&str> impl on RestartPolicy must round-trip \
10955                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
10956                 Ok(RestartPolicy::{variant:?}) — divergence from \
10957                 RestartPolicy::from_wire signals a silent detour off \
10958                 the substrate-primitive accessor"
10959            );
10960            assert_eq!(
10961                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
10962                RestartPolicy::from_wire(wire),
10963                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
10964                 equal RestartPolicy::from_wire on the same input"
10965            );
10966        }
10967    }
10968
10969    #[test]
10970    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
10971        // Rejection witness on the `impl TryFrom<&str> for
10972        // RestartPolicy` — sweeps a candidate set of byte-strings
10973        // outside the three-arm PascalCase wire accept-set the sibling
10974        // [`RestartPolicy::as_str`] emits and asserts every one lands on
10975        // `Err(())`, so a future accidental widening of the trait impl's
10976        // accept-set (a stray additional
10977        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
10978        // path, a silent inclusion of the kebab-case dispatcher-catalog
10979        // byte-string the pre-existing [`std::str::FromStr`] impl the
10980        // [`gen_platform::FromStrKind`] derive installs parses onto the
10981        // wire axis — which would collide the two-axis
10982        // wire/dispatcher-catalog split the sibling
10983        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
10984        // an English-rebrand or plural-arm silent alias that would widen
10985        // the wire accept-set past the OTP-canonical three) trips at
10986        // caixa-core test time. The candidate set includes the empty
10987        // string, whitespace-only padding, the kebab-case dispatcher-
10988        // catalog byte-strings on the sibling axis (a caller who
10989        // confuses the two axes trips here rather than at a downstream
10990        // consumer's silent reject), a lowercase / uppercase / mixed-case
10991        // fold of each PascalCase arm (a caller who assumes case-fold
10992        // acceptance trips here), leading/trailing whitespace padding,
10993        // the trailing-newline shape, quote-wrapped candidates, and a
10994        // residual set of plausible-but-wrong English rebrand
10995        // candidates. Peer of the sibling
10996        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
10997        // (5b828ed) rejection witness.
10998        let rejected: &[&str] = &[
10999            "",
11000            " ",
11001            "\n",
11002            "\t",
11003            "permanent",
11004            "temporary",
11005            "transient",
11006            "PERMANENT",
11007            "TEMPORARY",
11008            "TRANSIENT",
11009            "Permanents",
11010            "Permanent ",
11011            " Permanent",
11012            " Temporary ",
11013            "Permanent\n",
11014            "Transient\t",
11015            "\"Permanent\"",
11016            "Ephemeral",
11017            "Always",
11018            "Never",
11019            "OnAbnormalExit",
11020            "intrinsic",
11021            "?",
11022        ];
11023        for &input in rejected {
11024            assert_eq!(
11025                <RestartPolicy as TryFrom<&str>>::try_from(input),
11026                Err(()),
11027                "TryFrom<&str> impl on RestartPolicy must reject the \
11028                 non-wire byte-string {input:?} — silent acceptance \
11029                 signals an accept-set widening off the paired \
11030                 RestartPolicy::from_wire resolver"
11031            );
11032        }
11033    }
11034
11035    #[test]
11036    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
11037        // Cross-axis partition pin: the paired `TryFrom<&str>` and
11038        // `from_wire` reverse projections must resolve identically on
11039        // *every* input, not just the ones [`RestartPolicy::ALL`]
11040        // enumerates. Sweeps a mixed candidate set spanning accepted
11041        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
11042        // case dispatcher-catalog byte-strings, empty, whitespace-
11043        // padded, quoted, English-rebrand candidates) inputs and asserts
11044        // the trait's `Result::ok()` projection byte-equals the method-
11045        // named resolver's `Option<Self>` return-shape on each, locking
11046        // the two paths together by construction so any future detour
11047        // (a stray `try_from` special-case that widens or narrows the
11048        // accept-set outside the paired `from_wire` resolver, an
11049        // accidental swap onto the kebab-case [`std::str::FromStr`]
11050        // impl the [`gen_platform::FromStrKind`] derive installs on the
11051        // sibling dispatcher-catalog axis) trips at caixa-core test
11052        // time. Peer of the sibling
11053        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
11054        // pin — extends the round-trip discipline onto the M2-OTP-shape
11055        // per-child restart-policy axis.
11056        let candidates: &[&str] = &[
11057            "Permanent",
11058            "Temporary",
11059            "Transient",
11060            "",
11061            "permanent",
11062            "temporary",
11063            "transient",
11064            "PERMANENT",
11065            "unknown",
11066            "Permanent ",
11067            " Permanent",
11068            "\"Permanent\"",
11069            "Ephemeral",
11070            "OnAbnormalExit",
11071            "?",
11072        ];
11073        for &input in candidates {
11074            let via_trait: Option<RestartPolicy> =
11075                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
11076            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
11077            assert_eq!(
11078                via_trait, via_method,
11079                "TryFrom<&str> and from_wire must resolve identically on \
11080                 input {input:?} — divergence signals the two reverse-\
11081                 projection paths have drifted onto different accept-sets"
11082            );
11083        }
11084    }
11085
11086    #[test]
11087    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
11088        // Fail-before-pass-after byte-parity pin on the newly lifted
11089        // `impl From<RestartPolicy> for &'static str` — asserts the
11090        // standard-library trait impl and the substrate-primitive
11091        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11092        // the same three-arm emit-set across every arm the exhaustive
11093        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
11094        // detour that routes the trait impl through a divergent
11095        // projection (a per-arm inline `match policy { Permanent =>
11096        // "Permanent", … }` re-inlining that opens a compile-time link
11097        // to the un-lifted arm-literal, an accidental swap onto the
11098        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
11099        // axis that would collide the two-axis wire/catalog split the
11100        // sibling [`RestartPolicy::from_wire`] doc block makes
11101        // load-bearing) trips at caixa-core test time under
11102        // `assert_eq!` rather than at a downstream
11103        // `impl Into<&'static str>`-bound consumer's silent split.
11104        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
11105        // carries so no arm's projection is covered only by the sibling
11106        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
11107        // paths. Materializes the `<&'static str as
11108        // From<RestartPolicy>>::from` output in a `const`-shape binding
11109        // to make the `'static` lifetime promise a build-time invariant
11110        // — a future accidental downgrade of any of the three arms'
11111        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
11112        // non-`&'static str` (a `String::leak()`-produced return, a
11113        // `Box::leak`-cast) trips at caixa-core build time rather than
11114        // at a downstream `'static`-bound consumer. Peer of the sibling
11115        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
11116        // (523157d) — extends the trait-idiomatic forward-projection
11117        // axis onto the second (and second-of-two-in-M2) closed-set
11118        // typed enum on the caixa surface (the paired per-child
11119        // restart-decision-policy sibling on the same M2 `:supervisor`
11120        // slot).
11121        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11122        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11123        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11124        for &variant in RestartPolicy::ALL {
11125            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11126            let via_method: &'static str = variant.as_str();
11127            assert_eq!(
11128                via_trait, via_method,
11129                "From<RestartPolicy> for &'static str impl must round-trip \
11130                 RestartPolicy::{variant:?} to the same lifted \
11131                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
11132                 divergence signals a silent detour off the substrate-primitive \
11133                 accessor"
11134            );
11135            let via_into: &'static str = variant.into();
11136            assert_eq!(
11137                via_into, via_method,
11138                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
11139                 byte-equal RestartPolicy::as_str on the same input — the \
11140                 blanket-derived Into shape must resolve to the same as_str \
11141                 dispatch as the explicit From impl"
11142            );
11143        }
11144        assert_eq!(
11145            [PERMANENT, TEMPORARY, TRANSIENT],
11146            [
11147                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11148                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11149                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11150            ],
11151            "const-context RestartPolicy::as_str must resolve to the three \
11152             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
11153             downgrade of any arm to a non-const or non-static byte-string \
11154             breaks the `&'static str`-lifetime promise the paired \
11155             From<RestartPolicy> for &'static str impl carries by \
11156             construction"
11157        );
11158    }
11159
11160    #[test]
11161    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
11162        // Cross-axis partition pin: the paired trait-idiomatic
11163        // `From<RestartPolicy> for &'static str` forward projection and
11164        // the method-named [`RestartPolicy::as_str`] forward projection
11165        // must resolve identically on *every* arm, not just the ones
11166        // named in the primary byte-parity pin above. Sweeps every
11167        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
11168        // output byte-equals the method-named accessor's return-value on
11169        // each, locking the two forward-projection paths together by
11170        // construction so any future detour (a stray `From` special-case
11171        // that lands on a divergent per-arm literal outside the paired
11172        // `as_str` dispatch, a hypothetical rebrand touching one axis
11173        // without the other) trips at caixa-core test time. Peer of the
11174        // sibling forward-projection partition pin
11175        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
11176        // (523157d) — extends the round-trip discipline onto the
11177        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
11178        // surface, closing the two-way `Self ↔ &'static str` round-trip
11179        // on the trait-idiomatic pair (`From<Self> for &'static str` +
11180        // `TryFrom<&str> for Self`) as well as the pre-existing method-
11181        // named pair (`as_str` + `from_wire`).
11182        for &variant in RestartPolicy::ALL {
11183            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11184            let via_method: &'static str = variant.as_str();
11185            assert_eq!(
11186                via_trait, via_method,
11187                "From<RestartPolicy> for &'static str and \
11188                 RestartPolicy::as_str must resolve identically on \
11189                 RestartPolicy::{variant:?} — divergence signals the \
11190                 two forward-projection paths have drifted onto different \
11191                 emit-sets"
11192            );
11193        }
11194        // Round-trip witness: every arm's forward `From` output re-parses
11195        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
11196        // to the original variant. Closes the two-way `RestartPolicy ↔
11197        // &'static str` round-trip on the trait-idiomatic axis pair,
11198        // mirroring the pre-existing method-named `as_str` + `from_wire`
11199        // round-trip on the substrate-primitive axis pair.
11200        for &variant in RestartPolicy::ALL {
11201            let emitted: &'static str = variant.into();
11202            let re_parsed: Result<RestartPolicy, ()> =
11203                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11204            assert_eq!(
11205                re_parsed,
11206                Ok(variant),
11207                "trait-idiomatic axis pair must round-trip \
11208                 RestartPolicy::{variant:?} through `.into::<&'static \
11209                 str>()` and back through `TryFrom<&str>` — a break signals \
11210                 the forward-emit and reverse-parse axes have drifted onto \
11211                 different vocabularies"
11212            );
11213        }
11214    }
11215
11216    #[test]
11217    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
11218        // Fail-before-pass-after byte-parity pin on the newly lifted
11219        // `impl From<&RestartPolicy> for &'static str` — asserts the
11220        // borrowed-input standard-library trait impl and the substrate-
11221        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
11222        // resolve to the same three-arm emit-set across every arm the
11223        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
11224        // `From` trait does not auto-derive the borrowed-input sibling
11225        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
11226        // where T: Copy, U: From<T>` blanket in `core`), so the
11227        // borrowed-input axis is a distinct trait-idiomatic surface
11228        // that a `.iter().map(Into::into)` shape over
11229        // [`RestartPolicy::ALL`] (whose iterator yields
11230        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
11231        // impl and no other — the paired owned-input
11232        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
11233        // / dereference before the trait fires. Materializes the
11234        // `<&'static str as From<&RestartPolicy>>::from` output in a
11235        // `const`-shape binding to make the `'static` lifetime promise
11236        // a build-time invariant.
11237        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11238        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11239        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11240        for variant in RestartPolicy::ALL {
11241            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
11242            let via_method: &'static str = variant.as_str();
11243            assert_eq!(
11244                via_trait, via_method,
11245                "From<&RestartPolicy> for &'static str impl must round-trip \
11246                 &RestartPolicy::{variant:?} to the same lifted \
11247                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11248                 returns — divergence signals a silent detour off the \
11249                 substrate-primitive accessor"
11250            );
11251            let via_into: &'static str = variant.into();
11252            assert_eq!(
11253                via_into, via_method,
11254                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
11255                 must byte-equal RestartPolicy::as_str on the same input — \
11256                 the blanket-derived Into shape must resolve to the same \
11257                 as_str dispatch as the explicit From impl"
11258            );
11259        }
11260        assert_eq!(
11261            [PERMANENT, TEMPORARY, TRANSIENT],
11262            [
11263                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11264                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11265                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11266            ],
11267            "const-context RestartPolicy::as_str must resolve to the three \
11268             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
11269             From<&RestartPolicy> for &'static str impl inherits its \
11270             `'static` lifetime promise from the same accessor the \
11271             owned-input sibling routes through"
11272        );
11273    }
11274
11275    #[test]
11276    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
11277        // Cross-axis partition pin: the paired trait-idiomatic
11278        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
11279        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
11280        // &'static str` (this lift) forward projections must resolve
11281        // identically on every arm, locking the two input-shape paths
11282        // together so any future detour trips at caixa-core test time.
11283        // Then a witness that a `.iter().map(Into::into)` pipe over
11284        // [`RestartPolicy::ALL`] (whose iterator yields
11285        // `&RestartPolicy`) materializes the three-arm accept-set
11286        // through the borrowed-input axis alone — the exact shape a
11287        // future wasm-operator per-child post-exit restart-decision
11288        // diagnostic line, a future substrate-wide per-arm diagnostic
11289        // column, or a
11290        // `HashMap::<&'static str, RestartPolicy>::from_iter(
11291        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
11292        // per-policy lookup reaches through — closing the two-way
11293        // owned/borrowed input-shape symmetry on the forward-projection
11294        // trait-idiomatic axis. Peer of the sibling
11295        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11296        // (64aa742) /
11297        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11298        // (5ab993a) /
11299        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11300        // (807b0b5) /
11301        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11302        // (e941836) partition pins on the sibling closed-set typed-enum
11303        // discriminator axes — extends the borrowed-input axis
11304        // discipline onto the second-of-two M2 OTP-shape closed-set
11305        // typed enum on the caixa surface (per-child restart-decision
11306        // policy). Also closes the direct two-way `&Self → &'static
11307        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
11308        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
11309        // forward `From` emits lowercase Portuguese diagnostic bytes
11310        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11311        // forcing the round-trip through an intermediate wire-vocab
11312        // hop), the [`RestartPolicy::as_str`] emit and
11313        // [`RestartPolicy::from_wire`] parse share the same
11314        // `PascalCase` vocabulary by construction, so the borrowed-
11315        // input forward axis and the reverse axis compose directly.
11316        for &variant in RestartPolicy::ALL {
11317            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11318            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
11319            assert_eq!(
11320                owned, borrowed,
11321                "From<RestartPolicy> and From<&RestartPolicy> for \
11322                 &'static str must resolve identically on \
11323                 RestartPolicy::{variant:?} — divergence signals the \
11324                 owned-input and borrowed-input forward-projection paths \
11325                 have drifted onto different emit-sets"
11326            );
11327        }
11328        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
11329        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
11330        assert_eq!(
11331            via_iter, via_method,
11332            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
11333             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
11334             borrowed-input `From<&RestartPolicy> for &'static str` axis \
11335             is what makes the `.iter().map(Into::into)` shape route \
11336             through the substrate-primitive `RestartPolicy::as_str` \
11337             accessor rather than through a per-call-site `.copied()` / \
11338             dereference detour"
11339        );
11340        for variant in RestartPolicy::ALL {
11341            let emitted: &'static str = variant.into();
11342            let re_parsed: Result<RestartPolicy, ()> =
11343                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11344            assert_eq!(
11345                re_parsed,
11346                Ok(*variant),
11347                "trait-idiomatic borrowed-input forward-projection + \
11348                 reverse-projection axis pair must round-trip \
11349                 &RestartPolicy::{variant:?} through `.into::<&'static \
11350                 str>()` (via the borrowed-input axis) and back through \
11351                 `TryFrom<&str>` — a break signals the borrowed-input \
11352                 forward-emit and reverse-parse axes have drifted onto \
11353                 different vocabularies"
11354            );
11355        }
11356    }
11357
11358    #[test]
11359    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
11360        // Fail-before-pass-after byte-parity pin on the newly lifted
11361        // `impl From<RestartPolicy> for String` — asserts the
11362        // owned-`String`-returning standard-library trait impl and the
11363        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
11364        // accessor resolve to the same three-arm emit-set across every
11365        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
11366        // Rust's standard library does not carry a blanket
11367        // `impl<T: AsRef<str>> From<T> for String` (nor an
11368        // `impl<T: fmt::Display> From<T> for String`), so the
11369        // owned-`String` forward-projection axis is a distinct
11370        // trait-idiomatic surface that a `let key: String =
11371        // policy.into();`-shaped call site reaches through this impl
11372        // and no other — the paired sibling `From<RestartPolicy> for
11373        // &'static str` impl forces every owned-`String` call site
11374        // through an explicit `.to_owned()` / `String::from`
11375        // restatement. Peer of the first-mover
11376        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
11377        // (7baa18a) — extends the trait-idiomatic owned-`String`
11378        // forward-projection axis onto the second-of-two M2 OTP-shape
11379        // closed-set typed enums on the caixa surface (per-child
11380        // restart-decision-policy sibling on the same M2 `:supervisor`
11381        // slot).
11382        for &variant in RestartPolicy::ALL {
11383            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
11384            let via_method: &'static str = variant.as_str();
11385            assert_eq!(
11386                via_trait.as_str(),
11387                via_method,
11388                "From<RestartPolicy> for String impl must round-trip \
11389                 RestartPolicy::{variant:?} to the same lifted \
11390                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11391                 returns — divergence signals a silent detour off the \
11392                 substrate-primitive accessor"
11393            );
11394            let via_into: String = variant.into();
11395            assert_eq!(
11396                via_into.as_str(),
11397                via_method,
11398                "Into<String>::into on RestartPolicy::{variant:?} must \
11399                 byte-equal RestartPolicy::as_str on the same input — the \
11400                 blanket-derived Into shape must resolve to the same as_str \
11401                 dispatch as the explicit From impl"
11402            );
11403        }
11404    }
11405
11406    #[test]
11407    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
11408        // Cross-axis partition pin: the paired trait-idiomatic
11409        // owned-`String` `From<RestartPolicy> for String` (this lift)
11410        // and owned-`&'static str` `From<RestartPolicy> for &'static
11411        // str` (9fb37d0) forward projections must resolve identically
11412        // on every arm, locking the two return-type-shape paths
11413        // together so any future detour trips at caixa-core test time.
11414        // Also byte-parity witness against the sibling
11415        // [`ToString::to_string`] surface routed through
11416        // [`std::fmt::Display`] — the three owned-heap-string paths
11417        // (`.into::<String>()`, `String::from`, `.to_string()`) must
11418        // resolve identically on every arm so a future consumer that
11419        // picks any of the three lands on the same lifted
11420        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
11421        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
11422        // that materializes the three-arm accept-set through the
11423        // owned-`String` axis alone — the exact shape a future
11424        // wasm-operator per-child post-exit restart-decision
11425        // diagnostic line composer or a
11426        // `HashMap::<String, RestartPolicy>::from_iter(
11427        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
11428        // owned-key per-policy lookup reaches through — closing the
11429        // owned-`String` forward-projection axis's iterator-pipe
11430        // shape. Then a direct round-trip witness through the paired
11431        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
11432        // owned-`String`'s [`String::as_str`] borrow that closes the
11433        // two-way `Self → String → Self` round-trip on the trait-
11434        // idiomatic owned-`String` forward + reverse axis pair —
11435        // unlike the peer [`crate::CaixaKind`] axis pair (whose
11436        // forward `From` emits lowercase Portuguese diagnostic bytes
11437        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11438        // forcing the round-trip through an intermediate wire-vocab
11439        // hop), the [`RestartPolicy::as_str`] emit and
11440        // [`RestartPolicy::from_wire`] parse share the same
11441        // `PascalCase` vocabulary by construction, so the owned-
11442        // `String` forward axis and the reverse axis compose directly.
11443        for &variant in RestartPolicy::ALL {
11444            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11445            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11446            assert_eq!(
11447                owned_string.as_str(),
11448                owned_static,
11449                "From<RestartPolicy> for String and From<RestartPolicy> \
11450                 for &'static str must resolve identically on \
11451                 RestartPolicy::{variant:?} — divergence signals the \
11452                 owned-`String` and owned-`&'static str` forward-projection \
11453                 return-type-shape paths have drifted onto different \
11454                 emit-sets"
11455            );
11456            let via_to_string: String = variant.to_string();
11457            assert_eq!(
11458                owned_string, via_to_string,
11459                "From<RestartPolicy> for String must byte-equal \
11460                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
11461                 divergence signals the trait-idiomatic owned-`String` \
11462                 forward-projection axis and the ToString-through-Display \
11463                 axis have drifted onto different emit-sets"
11464            );
11465        }
11466        let via_iter: Vec<String> = RestartPolicy::ALL
11467            .iter()
11468            .copied()
11469            .map(String::from)
11470            .collect();
11471        let via_method: Vec<String> = RestartPolicy::ALL
11472            .iter()
11473            .map(|p| p.as_str().to_owned())
11474            .collect();
11475        assert_eq!(
11476            via_iter, via_method,
11477            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
11478             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
11479             every arm — the owned-`String` `From<RestartPolicy> for \
11480             String` axis is what makes the `String::from` composition \
11481             route through the substrate-primitive `RestartPolicy::as_str` \
11482             accessor rather than through a per-call-site `.to_owned()` / \
11483             `String::from(policy.as_str())` detour"
11484        );
11485        for &variant in RestartPolicy::ALL {
11486            let emitted: String = variant.into();
11487            let re_parsed: Result<RestartPolicy, ()> =
11488                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11489            assert_eq!(
11490                re_parsed,
11491                Ok(variant),
11492                "trait-idiomatic owned-`String` forward-projection + \
11493                 reverse-projection axis pair must round-trip \
11494                 RestartPolicy::{variant:?} through `.into::<String>()` \
11495                 and back through `TryFrom<&str>` on the owned-`String`'s \
11496                 String::as_str borrow — a break signals the owned-`String` \
11497                 forward-emit and reverse-parse axes have drifted onto \
11498                 different vocabularies"
11499            );
11500        }
11501    }
11502
11503    #[test]
11504    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
11505        // Fail-before-pass-after byte-parity pin on the newly lifted
11506        // `impl From<&RestartPolicy> for String` — asserts the
11507        // borrowed-input owned-`String`-returning standard-library
11508        // trait impl and the substrate-primitive
11509        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11510        // the same three-arm emit-set across every arm the exhaustive
11511        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
11512        // library does not carry a blanket `impl<T: AsRef<str>>
11513        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
11514        // for String`), so the borrowed-input owned-`String` forward-
11515        // projection axis is a distinct trait-idiomatic surface that a
11516        // `let key: String = (&policy).into();`-shaped call site
11517        // reaches through this impl and no other — the paired sibling
11518        // `From<RestartPolicy> for String` impl forces every borrowed-
11519        // input call site through an explicit `Copy` deref
11520        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
11521        // `.to_string()` detour. Peer of the first-mover
11522        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
11523        // (579385f) — extends the trait-idiomatic borrowed-input
11524        // owned-`String` forward-projection axis onto the second-of-
11525        // two M2 OTP-shape closed-set typed enums on the caixa surface
11526        // (per-child restart-decision-policy sibling on the same M2
11527        // `:supervisor` slot).
11528        for &variant in RestartPolicy::ALL {
11529            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
11530            let via_method: &'static str = variant.as_str();
11531            assert_eq!(
11532                via_trait.as_str(),
11533                via_method,
11534                "From<&RestartPolicy> for String impl must round-trip \
11535                 &RestartPolicy::{variant:?} to the same lifted \
11536                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11537                 returns — divergence signals a silent detour off the \
11538                 substrate-primitive accessor"
11539            );
11540            let via_into: String = (&variant).into();
11541            assert_eq!(
11542                via_into.as_str(),
11543                via_method,
11544                "Into<String>::into on &RestartPolicy::{variant:?} must \
11545                 byte-equal RestartPolicy::as_str on the same input — \
11546                 the blanket-derived Into shape must resolve to the \
11547                 same as_str dispatch as the explicit From impl"
11548            );
11549        }
11550    }
11551
11552    #[test]
11553    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
11554        // Cross-axis partition pin: the newly lifted trait-idiomatic
11555        // borrowed-input owned-`String` `From<&RestartPolicy> for
11556        // String` (this lift), the paired owned-input owned-`String`
11557        // `From<RestartPolicy> for String` (7851725), the paired
11558        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11559        // for &'static str` (842c7f3), and the paired owned-input
11560        // owned-`&'static str` `From<RestartPolicy> for &'static str`
11561        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
11562        // str, String}` 2×2 trait-idiomatic projection family — must
11563        // resolve identically on every arm, locking the four
11564        // return-shape × input-shape paths together so any future
11565        // detour trips at caixa-core test time. Also byte-parity
11566        // witness against the sibling [`ToString::to_string`] surface
11567        // routed through [`std::fmt::Display`] and a direct round-trip
11568        // witness through the paired trait-idiomatic reverse
11569        // [`TryFrom<&str>`] axis on the owned-`String`'s
11570        // [`String::as_str`] borrow that closes the two-way
11571        // `&Self → String → Self` round-trip on the trait-idiomatic
11572        // borrowed-input owned-`String` forward + reverse axis pair.
11573        // Peer of the first-mover
11574        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
11575        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
11576        // String}` 2×2 projection corner on both M2 OTP-shape sibling
11577        // peers.
11578        for &variant in RestartPolicy::ALL {
11579            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11580            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11581            let borrowed_static: &'static str =
11582                <&'static str as From<&RestartPolicy>>::from(&variant);
11583            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11584            assert_eq!(
11585                borrowed_string, owned_string,
11586                "From<&RestartPolicy> for String and From<RestartPolicy> \
11587                 for String must resolve identically on \
11588                 RestartPolicy::{variant:?} — divergence signals the \
11589                 borrowed-input and owned-input owned-`String` \
11590                 forward-projection input-shape paths have drifted onto \
11591                 different emit-sets"
11592            );
11593            assert_eq!(
11594                borrowed_string.as_str(),
11595                borrowed_static,
11596                "From<&RestartPolicy> for String and From<&RestartPolicy> \
11597                 for &'static str must resolve identically on \
11598                 RestartPolicy::{variant:?} — divergence signals the \
11599                 borrowed-input `&'static str` and owned-`String` \
11600                 return-shape paths have drifted onto different \
11601                 emit-sets"
11602            );
11603            assert_eq!(
11604                borrowed_string.as_str(),
11605                owned_static,
11606                "From<&RestartPolicy> for String and From<RestartPolicy> \
11607                 for &'static str must resolve identically on \
11608                 RestartPolicy::{variant:?} — divergence signals a \
11609                 break in the diagonal corner of the {{Self, &Self}} × \
11610                 {{&'static str, String}} 2×2 trait-idiomatic \
11611                 projection family"
11612            );
11613            let via_to_string: String = variant.to_string();
11614            assert_eq!(
11615                borrowed_string, via_to_string,
11616                "From<&RestartPolicy> for String must byte-equal \
11617                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
11618                 — divergence signals the trait-idiomatic borrowed-input \
11619                 owned-`String` forward-projection axis and the \
11620                 ToString-through-Display axis have drifted onto \
11621                 different emit-sets"
11622            );
11623        }
11624        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
11625        let via_method: Vec<String> = RestartPolicy::ALL
11626            .iter()
11627            .map(|p| p.as_str().to_owned())
11628            .collect();
11629        assert_eq!(
11630            via_iter, via_method,
11631            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
11632             call site whose iteration axis holds `&RestartPolicy` by \
11633             construction — must byte-equal `.iter().map(|p| \
11634             p.as_str().to_owned())` on every arm — the borrowed-input \
11635             owned-`String` `From<&RestartPolicy> for String` axis is \
11636             what makes the `String::from` composition route through \
11637             the substrate-primitive `RestartPolicy::as_str` accessor \
11638             without a spurious `Copy` deref (which would only be \
11639             reachable through the owned-input `From<RestartPolicy> \
11640             for String` axis by first calling `.copied()` on the \
11641             iterator)"
11642        );
11643        for &variant in RestartPolicy::ALL {
11644            let emitted: String = (&variant).into();
11645            let re_parsed: Result<RestartPolicy, ()> =
11646                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11647            assert_eq!(
11648                re_parsed,
11649                Ok(variant),
11650                "trait-idiomatic borrowed-input owned-`String` \
11651                 forward-projection + reverse-projection axis pair must \
11652                 round-trip &RestartPolicy::{variant:?} through \
11653                 `.into::<String>()` on the borrowed-input surface and \
11654                 back through `TryFrom<&str>` on the owned-`String`'s \
11655                 String::as_str borrow — a break signals the \
11656                 borrowed-input owned-`String` forward-emit and \
11657                 reverse-parse axes have drifted onto different \
11658                 vocabularies"
11659            );
11660        }
11661    }
11662
11663    #[test]
11664    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
11665        // Fail-before-pass-after byte-parity pin on the newly lifted
11666        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
11667        // asserts the standard-library trait impl and the substrate-
11668        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
11669        // accessor resolve to the same three-arm emit-set across every
11670        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
11671        // enumerates. Rust's standard library does not carry a blanket
11672        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
11673        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
11674        // the `Cow<'static, str>` forward-projection axis is a
11675        // distinct trait-idiomatic surface that a
11676        // `let key: Cow<'static, str> = policy.into();`-shaped call
11677        // site reaches through this impl and no other — the paired
11678        // sibling `From<RestartPolicy> for &'static str` and
11679        // `From<RestartPolicy> for String` impls force every
11680        // `Cow<'static, str>`-parameterized call site through a
11681        // `Cow::Borrowed(policy.as_str())` /
11682        // `Cow::Owned(policy.to_string())` composition whose type
11683        // bounds have no compile-time link back to the substrate
11684        // primitive.
11685        //
11686        // Also asserts the projection lands on the zero-alloc
11687        // [`std::borrow::Cow::Borrowed`] arm (not the
11688        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11689        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11690        // return lifetime by construction makes the borrowed arm the
11691        // type-correct projection with no runtime allocation. Any
11692        // future silent detour that routes the impl through the owned
11693        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
11694        // that would allocate on every call site where the
11695        // `&'static str` return of [`super::RestartPolicy::as_str`]
11696        // makes the zero-alloc borrowed projection type-correct) trips
11697        // at caixa-core test time under the
11698        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
11699        // than at a downstream `Cow<'static, str>`-bound consumer's
11700        // silent allocation.
11701        //
11702        // Second peer on the substrate-wide trait-idiomatic
11703        // [`std::borrow::Cow<'static, str>`] forward-projection family
11704        // to extend the axis off the top-level [`super::CaixaKind`]
11705        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
11706        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
11707        // fieldless typed enum peer on the caixa surface — closes the
11708        // M2 OTP-shape tier of the campaign on the owned-input axis
11709        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
11710        // now carry the owned-input Cow<'static, str> forward
11711        // projection).
11712        for &variant in RestartPolicy::ALL {
11713            let via_trait: std::borrow::Cow<'static, str> =
11714                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11715            let via_method: &'static str = variant.as_str();
11716            assert_eq!(
11717                via_trait.as_ref(),
11718                via_method,
11719                "From<RestartPolicy> for Cow<'static, str> impl must \
11720                 round-trip RestartPolicy::{variant:?} to the same \
11721                 lifted SUPERVISOR_CHILD_RESTART_* const \
11722                 RestartPolicy::as_str returns — divergence signals a \
11723                 silent detour off the substrate-primitive accessor"
11724            );
11725            assert!(
11726                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11727                "From<RestartPolicy> for Cow<'static, str> impl must \
11728                 land on the zero-alloc Cow::Borrowed arm on \
11729                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
11730                 signals the projection has silently allocated where \
11731                 the substrate-primitive RestartPolicy::as_str \
11732                 `&'static str` return makes the borrowed arm the \
11733                 type-correct projection"
11734            );
11735            let via_into: std::borrow::Cow<'static, str> = variant.into();
11736            assert_eq!(
11737                via_into.as_ref(),
11738                via_method,
11739                "Into<Cow<'static, str>>::into on \
11740                 RestartPolicy::{variant:?} must byte-equal \
11741                 RestartPolicy::as_str on the same input — the \
11742                 blanket-derived Into shape must resolve to the same \
11743                 as_str dispatch as the explicit From impl"
11744            );
11745            assert!(
11746                matches!(via_into, std::borrow::Cow::Borrowed(_)),
11747                "Into<Cow<'static, str>>::into on \
11748                 RestartPolicy::{variant:?} must land on the \
11749                 zero-alloc Cow::Borrowed arm — the blanket-derived \
11750                 Into shape must resolve to the same Cow::Borrowed \
11751                 dispatch as the explicit From impl"
11752            );
11753        }
11754    }
11755
11756    #[test]
11757    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11758        // Cross-axis partition pin: the newly lifted trait-idiomatic
11759        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
11760        // (this lift), the paired owned-input `From<RestartPolicy>
11761        // for &'static str` (9fb37d0), and the paired owned-input
11762        // `From<RestartPolicy> for String` (7851725) forward
11763        // projections must resolve identically on every arm, locking
11764        // the three return-shape paths together by construction so any
11765        // future detour trips at caixa-core test time. Also byte-parity
11766        // witness against the sibling [`ToString::to_string`] surface
11767        // routed through [`std::fmt::Display`] — every owned-heap-
11768        // string path (the `Cow::Owned` promotion of this axis's
11769        // `.into_owned()`, `From<RestartPolicy> for String`, and
11770        // `.to_string()`) resolves to the same lifted
11771        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11772        //
11773        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
11774        // witness over [`super::RestartPolicy::ALL`] that
11775        // materializes the three-arm accept-set through the
11776        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
11777        // shape a future `axum::response::IntoResponse` per-policy
11778        // rejection-body composer, a future M4 admission-webhook
11779        // per-policy rejection-reason emitter whose typing rules out
11780        // the sibling [`AsRef<str>`] borrowed return, or a future
11781        // substrate-wide per-policy diagnostic surface that binds
11782        // through a [`Cow<'static, str>`] boundary reaches through.
11783        // The pipe witness also pins the zero-alloc discipline: every
11784        // element in the collected vector satisfies the
11785        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
11786        // accidental silent-allocation regression on the pipe's
11787        // iteration axis is a caixa-core-test-time failure. Peer of
11788        // the first-mover
11789        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11790        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
11791        // — closes the whole owned-input `Cow<'static, str>` +
11792        // paired `{&'static str, String}` cross-axis-parity corner on
11793        // both M2 OTP-shape sibling peers.
11794        for &variant in RestartPolicy::ALL {
11795            let via_cow: std::borrow::Cow<'static, str> =
11796                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11797            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11798            let via_string: String = <String as From<RestartPolicy>>::from(variant);
11799            assert_eq!(
11800                via_cow.as_ref(),
11801                via_static,
11802                "From<RestartPolicy> for Cow<'static, str> and \
11803                 From<RestartPolicy> for &'static str must resolve \
11804                 identically on RestartPolicy::{variant:?} — \
11805                 divergence signals the Cow<'static, str> and \
11806                 &'static str return-shape paths have drifted onto \
11807                 different emit-sets"
11808            );
11809            assert_eq!(
11810                via_cow.as_ref(),
11811                via_string.as_str(),
11812                "From<RestartPolicy> for Cow<'static, str> and \
11813                 From<RestartPolicy> for String must resolve \
11814                 identically on RestartPolicy::{variant:?} — \
11815                 divergence signals the Cow<'static, str> and String \
11816                 return-shape paths have drifted onto different \
11817                 emit-sets"
11818            );
11819            let via_to_string: String = variant.to_string();
11820            assert_eq!(
11821                via_cow.as_ref(),
11822                via_to_string.as_str(),
11823                "From<RestartPolicy> for Cow<'static, str> must \
11824                 byte-equal RestartPolicy::to_string on \
11825                 RestartPolicy::{variant:?} — divergence signals the \
11826                 trait-idiomatic Cow<'static, str> forward-projection \
11827                 axis and the ToString-through-Display axis have \
11828                 drifted onto different emit-sets"
11829            );
11830        }
11831        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11832            .iter()
11833            .copied()
11834            .map(std::borrow::Cow::from)
11835            .collect();
11836        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11837            .iter()
11838            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11839            .collect();
11840        assert_eq!(
11841            via_iter, via_method,
11842            "`.iter().copied().map(Cow::from)` over \
11843             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
11844             Cow::Borrowed(p.as_str()))` on every arm — the \
11845             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
11846             str>` axis is what makes the `Cow::from` composition \
11847             route through the substrate-primitive \
11848             `RestartPolicy::as_str` accessor with the zero-alloc \
11849             Cow::Borrowed arm by construction, rather than a \
11850             per-call-site `Cow::Owned(policy.to_string())` \
11851             allocation"
11852        );
11853        for cow in &via_iter {
11854            assert!(
11855                matches!(cow, std::borrow::Cow::Borrowed(_)),
11856                "every element of the \
11857                 .iter().copied().map(Cow::from) pipe over \
11858                 RestartPolicy::ALL must land on the zero-alloc \
11859                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11860                 signals the pipe's iteration axis has silently \
11861                 allocated where the substrate-primitive \
11862                 RestartPolicy::as_str `&'static str` return makes \
11863                 the borrowed arm the type-correct projection"
11864            );
11865        }
11866    }
11867
11868    #[test]
11869    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11870        // Fail-before-pass-after byte-parity pin on the newly lifted
11871        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
11872        // asserts the borrowed-input standard-library trait impl and
11873        // the substrate-primitive [`super::RestartPolicy::as_str`]
11874        // `pub const fn` accessor resolve to the same three-arm emit-
11875        // set across every arm the exhaustive
11876        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11877        // standard library does not carry a blanket
11878        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11879        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11880        // the borrowed-input `Cow<'static, str>` forward-projection
11881        // axis is a distinct trait-idiomatic surface that a
11882        // `let key: Cow<'static, str> = (&policy).into();`-shaped
11883        // call site or a
11884        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
11885        // reaches through this impl and no other — the paired owned-
11886        // input `From<RestartPolicy> for Cow<'static, str>` impl
11887        // (0612398) forces every borrowed-input call site through an
11888        // explicit `Copy` deref (`Cow::from(*policy)`) or a
11889        // `Cow::Borrowed(policy.as_str())` open-code whose type
11890        // bounds have no compile-time link back to the substrate
11891        // primitive.
11892        //
11893        // Also asserts the projection lands on the zero-alloc
11894        // [`std::borrow::Cow::Borrowed`] arm (not the
11895        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11896        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11897        // return lifetime by construction makes the borrowed arm the
11898        // type-correct projection with no runtime allocation on the
11899        // borrowed-input surface just as on the paired owned-input
11900        // surface.
11901        //
11902        // Closes the `{Self, &Self}` input-shape corner on the M2
11903        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
11904        // the second-of-two-in-M2 closed-set fieldless typed enum peer
11905        // on the caixa surface (`:supervisor :children :restart`),
11906        // exactly as d45c409 closed it on the top-level
11907        // [`super::CaixaKind`] one commit after the owning half
11908        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
11909        // M2 OTP-shape [`super::RestartStrategy`] one commit after
11910        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
11911        // tier of the substrate-wide Cow<'static, str> forward-
11912        // projection campaign on both input-shape corners
11913        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
11914        for &variant in RestartPolicy::ALL {
11915            let via_trait: std::borrow::Cow<'static, str> =
11916                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11917            let via_method: &'static str = variant.as_str();
11918            assert_eq!(
11919                via_trait.as_ref(),
11920                via_method,
11921                "From<&RestartPolicy> for Cow<'static, str> impl must \
11922                 round-trip &RestartPolicy::{variant:?} to the same \
11923                 lifted SUPERVISOR_CHILD_RESTART_* const \
11924                 RestartPolicy::as_str returns — divergence signals a \
11925                 silent detour off the substrate-primitive accessor"
11926            );
11927            assert!(
11928                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11929                "From<&RestartPolicy> for Cow<'static, str> impl must \
11930                 land on the zero-alloc Cow::Borrowed arm on \
11931                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
11932                 signals the projection has silently allocated where \
11933                 the substrate-primitive RestartPolicy::as_str \
11934                 `&'static str` return makes the borrowed arm the \
11935                 type-correct projection"
11936            );
11937            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
11938            assert_eq!(
11939                via_into.as_ref(),
11940                via_method,
11941                "Into<Cow<'static, str>>::into on \
11942                 &RestartPolicy::{variant:?} must byte-equal \
11943                 RestartPolicy::as_str on the same input — the \
11944                 blanket-derived Into shape must resolve to the same \
11945                 as_str dispatch as the explicit From impl"
11946            );
11947            assert!(
11948                matches!(via_into, std::borrow::Cow::Borrowed(_)),
11949                "Into<Cow<'static, str>>::into on \
11950                 &RestartPolicy::{variant:?} must land on the \
11951                 zero-alloc Cow::Borrowed arm — the blanket-derived \
11952                 Into shape must resolve to the same Cow::Borrowed \
11953                 dispatch as the explicit From impl"
11954            );
11955        }
11956    }
11957
11958    #[test]
11959    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11960        // Cross-axis partition pin: the newly lifted trait-idiomatic
11961        // borrowed-input `From<&RestartPolicy> for
11962        // std::borrow::Cow<'static, str>` (this lift), the paired
11963        // owned-input `From<RestartPolicy> for
11964        // std::borrow::Cow<'static, str>` (0612398), the paired
11965        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11966        // for &'static str`, and the paired borrowed-input owned-
11967        // `String` `From<&RestartPolicy> for String` must resolve
11968        // identically on every arm, locking the four
11969        // return-shape × input-shape paths together by construction so
11970        // any future detour trips at caixa-core test time. Also byte-
11971        // parity witness against the sibling [`ToString::to_string`]
11972        // surface routed through [`std::fmt::Display`] — every owned-
11973        // heap-string path (this axis's `.into_owned()` promotion, the
11974        // paired [`From<&RestartPolicy> for String`], and
11975        // `.to_string()`) resolves to the same lifted
11976        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11977        //
11978        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
11979        // over [`super::RestartPolicy::ALL`] — whose iterator yields
11980        // `&RestartPolicy` by construction, so the borrowed-input
11981        // [`Cow<'static, str>`] axis is what routes the pipe through
11982        // the substrate-primitive [`super::RestartPolicy::as_str`]
11983        // accessor without a spurious [`Copy`] deref (which would only
11984        // be reachable through the owned-input
11985        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
11986        // calling `.copied()` on the iterator). The pipe witness also
11987        // pins the zero-alloc discipline: every element in the
11988        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
11989        // arm predicate, so a future accidental silent-allocation
11990        // regression on the pipe's iteration axis is a caixa-core-
11991        // test-time failure. Peer of the sibling
11992        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11993        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
11994        // the whole borrowed-input `Cow<'static, str>` +
11995        // paired `{&'static str, String}` cross-axis-parity corner on
11996        // both M2 OTP-shape sibling peers.
11997        for &policy in RestartPolicy::ALL {
11998            let borrowed_cow: std::borrow::Cow<'static, str> =
11999                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
12000            let owned_cow: std::borrow::Cow<'static, str> =
12001                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
12002            let borrowed_static: &'static str =
12003                <&'static str as From<&RestartPolicy>>::from(&policy);
12004            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
12005            assert_eq!(
12006                borrowed_cow, owned_cow,
12007                "From<&RestartPolicy> for Cow<'static, str> and \
12008                 From<RestartPolicy> for Cow<'static, str> must \
12009                 resolve identically on RestartPolicy::{policy:?} — \
12010                 divergence signals the borrowed-input and owned-input \
12011                 Cow<'static, str> forward-projection input-shape \
12012                 paths have drifted onto different emit-sets"
12013            );
12014            assert_eq!(
12015                borrowed_cow.as_ref(),
12016                borrowed_static,
12017                "From<&RestartPolicy> for Cow<'static, str> and \
12018                 From<&RestartPolicy> for &'static str must resolve \
12019                 identically on RestartPolicy::{policy:?} — \
12020                 divergence signals the borrowed-input Cow<'static, \
12021                 str> and &'static str return-shape paths have drifted \
12022                 onto different emit-sets"
12023            );
12024            assert_eq!(
12025                borrowed_cow.as_ref(),
12026                borrowed_string.as_str(),
12027                "From<&RestartPolicy> for Cow<'static, str> and \
12028                 From<&RestartPolicy> for String must resolve \
12029                 identically on RestartPolicy::{policy:?} — \
12030                 divergence signals the borrowed-input Cow<'static, \
12031                 str> and owned-`String` return-shape paths have \
12032                 drifted onto different emit-sets"
12033            );
12034            let via_to_string: String = policy.to_string();
12035            assert_eq!(
12036                borrowed_cow.as_ref(),
12037                via_to_string.as_str(),
12038                "From<&RestartPolicy> for Cow<'static, str> must \
12039                 byte-equal RestartPolicy::to_string on \
12040                 RestartPolicy::{policy:?} — divergence signals \
12041                 the trait-idiomatic borrowed-input Cow<'static, str> \
12042                 forward-projection axis and the ToString-through-\
12043                 Display axis have drifted onto different emit-sets"
12044            );
12045        }
12046        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12047            .iter()
12048            .map(std::borrow::Cow::from)
12049            .collect();
12050        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12051            .iter()
12052            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
12053            .collect();
12054        assert_eq!(
12055            via_iter, via_method,
12056            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
12057             call site whose iteration axis holds `&RestartPolicy` \
12058             by construction — must byte-equal `.iter().map(|p| \
12059             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
12060             input Cow<'static, str> `From<&RestartPolicy> for \
12061             Cow<'static, str>` axis is what makes the `Cow::from` \
12062             composition route through the substrate-primitive \
12063             `RestartPolicy::as_str` accessor with the zero-alloc \
12064             Cow::Borrowed arm by construction and without a spurious \
12065             `Copy` deref (which would only be reachable through the \
12066             owned-input `From<RestartPolicy> for Cow<'static, str>` \
12067             axis by first calling `.copied()` on the iterator)"
12068        );
12069        for cow in &via_iter {
12070            assert!(
12071                matches!(cow, std::borrow::Cow::Borrowed(_)),
12072                "every element of the .iter().map(Cow::from) pipe \
12073                 over RestartPolicy::ALL must land on the zero-\
12074                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
12075                 any arm signals the pipe's iteration axis has \
12076                 silently allocated where the substrate-primitive \
12077                 RestartPolicy::as_str `&'static str` return makes \
12078                 the borrowed arm the type-correct projection"
12079            );
12080        }
12081    }
12082
12083    #[test]
12084    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
12085        // Fail-before-pass-after byte-parity pin on the newly lifted
12086        // `impl From<RestartPolicy> for Box<str>` — asserts the
12087        // owned-input standard-library trait impl and the
12088        // substrate-primitive [`super::RestartPolicy::as_str`]
12089        // `pub const fn` accessor resolve to the same three-arm emit-
12090        // set across every arm the exhaustive
12091        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12092        // substrate-wide `Box<str>` forward-projection campaign tier
12093        // opened one commit prior (69ef45c) on the paired sibling-
12094        // restart [`RestartStrategy`] onto the second (and third-and-
12095        // final) M2 OTP-shape closed-set fieldless typed enum peer on
12096        // the caixa surface (`:children :restart`), immediately after
12097        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
12098        // closed the
12099        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
12100        // 2×3 corner on this enum. Rust's standard library carries
12101        // `impl From<&str> for Box<str>` and
12102        // `impl From<String> for Box<str>` but no blanket
12103        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
12104        // a distinct trait-idiomatic surface that a
12105        // `let key: Box<str> = policy.into();`-shaped call site
12106        // reaches through this impl and no other — a paired
12107        // `Box::from(policy.as_str())` open-code has no compile-time
12108        // link back to the substrate primitive. Peer of the sibling
12109        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
12110        // (69ef45c) — extends the trait-idiomatic owned-input
12111        // [`Box<str>`] forward-projection axis onto the third and
12112        // final M2-OTP-shape closed-set typed enum on the caixa
12113        // surface.
12114        for &variant in RestartPolicy::ALL {
12115            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12116            let via_method: &'static str = variant.as_str();
12117            assert_eq!(
12118                via_trait.as_ref(),
12119                via_method,
12120                "From<RestartPolicy> for Box<str> impl must round-\
12121                 trip RestartPolicy::{variant:?} to the same lifted \
12122                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12123                 returns — divergence signals a silent detour off the \
12124                 substrate-primitive accessor"
12125            );
12126            let via_into: Box<str> = variant.into();
12127            assert_eq!(
12128                via_into.as_ref(),
12129                via_method,
12130                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
12131                 must byte-equal RestartPolicy::as_str on the same \
12132                 input — the blanket-derived Into shape must resolve \
12133                 to the same as_str dispatch as the explicit From impl"
12134            );
12135        }
12136    }
12137
12138    #[test]
12139    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
12140        // Fail-before-pass-after byte-parity pin on the newly lifted
12141        // `impl From<&RestartPolicy> for Box<str>` — asserts the
12142        // borrowed-input standard-library trait impl and the
12143        // substrate-primitive [`super::RestartPolicy::as_str`]
12144        // `pub const fn` accessor resolve to the same three-arm emit-
12145        // set across every arm the exhaustive
12146        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12147        // standard library does not carry a blanket
12148        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
12149        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12150        // so the borrowed-input `Box<str>` forward-projection axis
12151        // is a distinct trait-idiomatic surface that a
12152        // `let key: Box<str> = (&policy).into();`-shaped call site
12153        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
12154        // shaped pipe reaches through this impl and no other — the
12155        // paired owned-input `From<RestartPolicy> for Box<str>`
12156        // impl (0a1b313) forces every borrowed-input call site
12157        // through an explicit `Copy` deref
12158        // (`Box::<str>::from((*policy).as_str())`) or a
12159        // `Box::<str>::from(policy.as_str())` open-code whose
12160        // type bounds have no compile-time link back to the
12161        // substrate primitive.
12162        //
12163        // Fourth (and closing) peer on the substrate-wide trait-
12164        // idiomatic [`Box<str>`] forward-projection family on the
12165        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
12166        // shape corner of the [`Box<str>`] axis on the second (and
12167        // third-and-final) M2 OTP-shape closed-set fieldless typed
12168        // enum peer on the caixa surface (`:children :restart`),
12169        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
12170        // axis one commit after its owning half (0612398) landed
12171        // on this enum. Every remaining closed-set fieldless typed
12172        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
12173        // render-side / outside-caixa-core tiers is a future
12174        // target of the campaign.
12175        //
12176        // Also byte-parity witness against the paired owned-input
12177        // [`From<RestartPolicy> for Box<str>`] and the sibling
12178        // borrowed-input [`From<&RestartPolicy> for &'static str`],
12179        // [`From<&RestartPolicy> for String`], and
12180        // [`From<&RestartPolicy> for Cow<'static, str>`]
12181        // return-shape axes — locking the four
12182        // return-shape × input-shape paths together by construction
12183        // so any future detour trips at caixa-core test time. Then a
12184        // `.iter().map(Box::<str>::from)` pipe witness over
12185        // [`super::RestartPolicy::ALL`] — whose iterator yields
12186        // `&RestartPolicy` by construction, so the borrowed-input
12187        // [`Box<str>`] axis is what routes the pipe through the
12188        // substrate-primitive [`super::RestartPolicy::as_str`]
12189        // accessor without a spurious [`Copy`] deref (which would
12190        // only be reachable through the owned-input
12191        // [`From<RestartPolicy> for Box<str>`] axis by first
12192        // calling `.copied()` on the iterator).
12193        for &variant in RestartPolicy::ALL {
12194            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12195            let via_method: &'static str = variant.as_str();
12196            assert_eq!(
12197                via_trait.as_ref(),
12198                via_method,
12199                "From<&RestartPolicy> for Box<str> impl must round-\
12200                 trip &RestartPolicy::{variant:?} to the same lifted \
12201                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12202                 returns — divergence signals a silent detour off the \
12203                 substrate-primitive accessor"
12204            );
12205            let via_into: Box<str> = (&variant).into();
12206            assert_eq!(
12207                via_into.as_ref(),
12208                via_method,
12209                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
12210                 must byte-equal RestartPolicy::as_str on the same \
12211                 input — the blanket-derived Into shape must resolve \
12212                 to the same as_str dispatch as the explicit From impl"
12213            );
12214            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12215            assert_eq!(
12216                via_trait, owned_box,
12217                "From<&RestartPolicy> for Box<str> and \
12218                 From<RestartPolicy> for Box<str> must resolve \
12219                 identically on RestartPolicy::{variant:?} — \
12220                 divergence signals the borrowed-input and owned-input \
12221                 Box<str> forward-projection input-shape paths have \
12222                 drifted onto different emit-sets"
12223            );
12224            let borrowed_static: &'static str =
12225                <&'static str as From<&RestartPolicy>>::from(&variant);
12226            assert_eq!(
12227                via_trait.as_ref(),
12228                borrowed_static,
12229                "From<&RestartPolicy> for Box<str> and \
12230                 From<&RestartPolicy> for &'static str must resolve \
12231                 identically on RestartPolicy::{variant:?} — \
12232                 divergence signals the borrowed-input Box<str> and \
12233                 &'static str return-shape paths have drifted onto \
12234                 different emit-sets"
12235            );
12236            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12237            assert_eq!(
12238                via_trait.as_ref(),
12239                borrowed_string.as_str(),
12240                "From<&RestartPolicy> for Box<str> and \
12241                 From<&RestartPolicy> for String must resolve \
12242                 identically on RestartPolicy::{variant:?} — \
12243                 divergence signals the borrowed-input Box<str> and \
12244                 owned-`String` return-shape paths have drifted onto \
12245                 different emit-sets"
12246            );
12247            let borrowed_cow: std::borrow::Cow<'static, str> =
12248                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12249            assert_eq!(
12250                via_trait.as_ref(),
12251                borrowed_cow.as_ref(),
12252                "From<&RestartPolicy> for Box<str> and \
12253                 From<&RestartPolicy> for Cow<'static, str> must \
12254                 resolve identically on RestartPolicy::{variant:?} — \
12255                 divergence signals the borrowed-input Box<str> and \
12256                 Cow<'static, str> return-shape paths have drifted \
12257                 onto different emit-sets"
12258            );
12259        }
12260        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
12261        let via_method: Vec<Box<str>> = RestartPolicy::ALL
12262            .iter()
12263            .map(|p| Box::<str>::from(p.as_str()))
12264            .collect();
12265        assert_eq!(
12266            via_iter, via_method,
12267            "`.iter().map(Box::<str>::from)` over \
12268             RestartPolicy::ALL — a call site whose iteration axis \
12269             holds `&RestartPolicy` by construction — must byte-\
12270             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
12271             on every arm — the borrowed-input Box<str> \
12272             `From<&RestartPolicy> for Box<str>` axis is what \
12273             makes the `Box::<str>::from` composition route through \
12274             the substrate-primitive `RestartPolicy::as_str` \
12275             accessor without a spurious `Copy` deref (which would \
12276             only be reachable through the owned-input \
12277             `From<RestartPolicy> for Box<str>` axis by first \
12278             calling `.copied()` on the iterator)"
12279        );
12280    }
12281
12282    #[test]
12283    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
12284        // Fail-before-pass-after byte-parity pin on the newly lifted
12285        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
12286        // the owned-input standard-library trait impl and the
12287        // substrate-primitive [`super::RestartPolicy::as_str`]
12288        // `pub const fn` accessor resolve to the same three-arm emit-
12289        // set across every arm the exhaustive
12290        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12291        // substrate-wide [`std::sync::Arc<str>`] forward-projection
12292        // campaign tier opened one projection tier prior (bca2ec8) on
12293        // the paired sibling-restart [`RestartStrategy`] owned-input
12294        // first-mover onto the second (and third-and-final) M2 OTP-
12295        // shape closed-set fieldless typed enum peer on the caixa
12296        // surface (`:children :restart`), immediately after the paired
12297        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
12298        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
12299        // Box<str>}` 2×4 corner on this enum. Rust's standard library
12300        // carries `impl From<&str> for std::sync::Arc<str>` and
12301        // `impl From<String> for std::sync::Arc<str>` but no blanket
12302        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
12303        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
12304        // so this axis is a distinct trait-idiomatic surface that a
12305        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
12306        // site reaches through this impl and no other — a paired
12307        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12308        // has no compile-time link back to the substrate primitive,
12309        // and a two-step `std::sync::Arc::<str>::from(String::from(
12310        // policy))` composition through the owned-`String` axis
12311        // allocates twice (once into the intermediate `String`, once
12312        // into the [`Arc<str>`] on the `From<String>` conversion)
12313        // where the single-step trait impl allocates once.
12314        //
12315        // Cross-axis byte-parity witness against the sibling owned-
12316        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
12317        // return-shape axes — locking the five return-shape paths on
12318        // the owned-input surface together by construction so any
12319        // future detour off the substrate-primitive
12320        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
12321        // core test time.
12322        for &variant in RestartPolicy::ALL {
12323            let via_trait: std::sync::Arc<str> =
12324                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12325            let via_method: &'static str = variant.as_str();
12326            assert_eq!(
12327                via_trait.as_ref(),
12328                via_method,
12329                "From<RestartPolicy> for std::sync::Arc<str> impl \
12330                 must round-trip RestartPolicy::{variant:?} to the \
12331                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12332                 RestartPolicy::as_str returns — divergence signals \
12333                 a silent detour off the substrate-primitive accessor"
12334            );
12335            let via_into: std::sync::Arc<str> = variant.into();
12336            assert_eq!(
12337                via_into.as_ref(),
12338                via_method,
12339                "Into<std::sync::Arc<str>>::into on \
12340                 RestartPolicy::{variant:?} must byte-equal \
12341                 RestartPolicy::as_str on the same input — the \
12342                 blanket-derived Into shape must resolve to the same \
12343                 as_str dispatch as the explicit From impl"
12344            );
12345            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12346            assert_eq!(
12347                via_trait.as_ref(),
12348                owned_static,
12349                "From<RestartPolicy> for std::sync::Arc<str> and \
12350                 From<RestartPolicy> for &'static str must resolve \
12351                 identically on RestartPolicy::{variant:?} — \
12352                 divergence signals the owned-input std::sync::Arc<str> \
12353                 and &'static str return-shape paths have drifted onto \
12354                 different emit-sets"
12355            );
12356            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12357            assert_eq!(
12358                via_trait.as_ref(),
12359                owned_string.as_str(),
12360                "From<RestartPolicy> for std::sync::Arc<str> and \
12361                 From<RestartPolicy> for String must resolve \
12362                 identically on RestartPolicy::{variant:?} — \
12363                 divergence signals the owned-input std::sync::Arc<str> \
12364                 and owned-`String` return-shape paths have drifted \
12365                 onto different emit-sets"
12366            );
12367            let owned_cow: std::borrow::Cow<'static, str> =
12368                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12369            assert_eq!(
12370                via_trait.as_ref(),
12371                owned_cow.as_ref(),
12372                "From<RestartPolicy> for std::sync::Arc<str> and \
12373                 From<RestartPolicy> for Cow<'static, str> must \
12374                 resolve identically on RestartPolicy::{variant:?} — \
12375                 divergence signals the owned-input std::sync::Arc<str> \
12376                 and Cow<'static, str> return-shape paths have drifted \
12377                 onto different emit-sets"
12378            );
12379            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12380            assert_eq!(
12381                via_trait.as_ref(),
12382                owned_box.as_ref(),
12383                "From<RestartPolicy> for std::sync::Arc<str> and \
12384                 From<RestartPolicy> for Box<str> must resolve \
12385                 identically on RestartPolicy::{variant:?} — \
12386                 divergence signals the owned-input std::sync::Arc<str> \
12387                 and Box<str> return-shape paths have drifted onto \
12388                 different emit-sets"
12389            );
12390        }
12391    }
12392
12393    #[test]
12394    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
12395        // Fail-before-pass-after byte-parity pin on the newly lifted
12396        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
12397        // asserts the borrowed-input standard-library trait impl and
12398        // the substrate-primitive [`super::RestartPolicy::as_str`]
12399        // `pub const fn` accessor resolve to the same three-arm
12400        // emit-set across every arm the exhaustive
12401        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12402        // standard library carries `impl From<&str> for
12403        // std::sync::Arc<str>` and `impl From<String> for
12404        // std::sync::Arc<str>` but no blanket
12405        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
12406        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12407        // so the borrowed-input [`std::sync::Arc<str>`] forward-
12408        // projection axis is a distinct trait-idiomatic surface that
12409        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
12410        // call site or a
12411        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
12412        // shaped pipe reaches through this impl and no other — the
12413        // paired owned-input [`From<RestartPolicy> for
12414        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
12415        // input call site through an explicit [`Copy`] deref
12416        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
12417        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12418        // whose type bounds have no compile-time link back to the
12419        // substrate primitive.
12420        //
12421        // Closes the `{Self, &Self}` input-shape corner of the
12422        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
12423        // forward-projection family on the second (and third-and-
12424        // final) M2 OTP-shape closed-set fieldless typed enum peer
12425        // on the caixa surface (`:children :restart`), one commit
12426        // after b05724e opened the owned-input half — exactly as
12427        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
12428        // the sibling-restart [`RestartStrategy`] first-mover one
12429        // commit after its owning half (bca2ec8) landed, and as
12430        // cb1d068 closed the paired [`Box<str>`] corner on this
12431        // enum one commit after its owning half (0a1b313) landed.
12432        //
12433        // Also byte-parity witness against the paired owned-input
12434        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
12435        // sibling borrowed-input [`From<&RestartPolicy> for
12436        // &'static str`], [`From<&RestartPolicy> for String`],
12437        // [`From<&RestartPolicy> for Cow<'static, str>`], and
12438        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
12439        // locking the five return-shape × input-shape paths together
12440        // by construction so any future detour off the substrate-
12441        // primitive [`super::RestartPolicy::as_str`] accessor trips
12442        // at caixa-core test time. Then a
12443        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
12444        // over [`super::RestartPolicy::ALL`] — whose iterator yields
12445        // `&RestartPolicy` by construction, so the borrowed-input
12446        // [`std::sync::Arc<str>`] axis is what routes the pipe
12447        // through the substrate-primitive
12448        // [`super::RestartPolicy::as_str`] accessor without a
12449        // spurious [`Copy`] deref (which would only be reachable
12450        // through the owned-input
12451        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
12452        // first calling `.copied()` on the iterator).
12453        for &variant in RestartPolicy::ALL {
12454            let via_trait: std::sync::Arc<str> =
12455                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
12456            let via_method: &'static str = variant.as_str();
12457            assert_eq!(
12458                via_trait.as_ref(),
12459                via_method,
12460                "From<&RestartPolicy> for std::sync::Arc<str> impl \
12461                 must round-trip &RestartPolicy::{variant:?} to the \
12462                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12463                 RestartPolicy::as_str returns — divergence signals \
12464                 a silent detour off the substrate-primitive accessor"
12465            );
12466            let via_into: std::sync::Arc<str> = (&variant).into();
12467            assert_eq!(
12468                via_into.as_ref(),
12469                via_method,
12470                "Into<std::sync::Arc<str>>::into on \
12471                 &RestartPolicy::{variant:?} must byte-equal \
12472                 RestartPolicy::as_str on the same input — the \
12473                 blanket-derived Into shape must resolve to the same \
12474                 as_str dispatch as the explicit From impl"
12475            );
12476            let owned_arc: std::sync::Arc<str> =
12477                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12478            assert_eq!(
12479                via_trait, owned_arc,
12480                "From<&RestartPolicy> for std::sync::Arc<str> and \
12481                 From<RestartPolicy> for std::sync::Arc<str> must \
12482                 resolve identically on RestartPolicy::{variant:?} — \
12483                 divergence signals the borrowed-input and owned-input \
12484                 std::sync::Arc<str> forward-projection input-shape \
12485                 paths have drifted onto different emit-sets"
12486            );
12487            let borrowed_static: &'static str =
12488                <&'static str as From<&RestartPolicy>>::from(&variant);
12489            assert_eq!(
12490                via_trait.as_ref(),
12491                borrowed_static,
12492                "From<&RestartPolicy> for std::sync::Arc<str> and \
12493                 From<&RestartPolicy> for &'static str must resolve \
12494                 identically on RestartPolicy::{variant:?} — \
12495                 divergence signals the borrowed-input std::sync::Arc<str> \
12496                 and &'static str return-shape paths have drifted onto \
12497                 different emit-sets"
12498            );
12499            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12500            assert_eq!(
12501                via_trait.as_ref(),
12502                borrowed_string.as_str(),
12503                "From<&RestartPolicy> for std::sync::Arc<str> and \
12504                 From<&RestartPolicy> for String must resolve \
12505                 identically on RestartPolicy::{variant:?} — \
12506                 divergence signals the borrowed-input std::sync::Arc<str> \
12507                 and owned-`String` return-shape paths have drifted \
12508                 onto different emit-sets"
12509            );
12510            let borrowed_cow: std::borrow::Cow<'static, str> =
12511                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12512            assert_eq!(
12513                via_trait.as_ref(),
12514                borrowed_cow.as_ref(),
12515                "From<&RestartPolicy> for std::sync::Arc<str> and \
12516                 From<&RestartPolicy> for Cow<'static, str> must \
12517                 resolve identically on RestartPolicy::{variant:?} — \
12518                 divergence signals the borrowed-input std::sync::Arc<str> \
12519                 and Cow<'static, str> return-shape paths have drifted \
12520                 onto different emit-sets"
12521            );
12522            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12523            assert_eq!(
12524                via_trait.as_ref(),
12525                borrowed_box.as_ref(),
12526                "From<&RestartPolicy> for std::sync::Arc<str> and \
12527                 From<&RestartPolicy> for Box<str> must resolve \
12528                 identically on RestartPolicy::{variant:?} — \
12529                 divergence signals the borrowed-input std::sync::Arc<str> \
12530                 and Box<str> return-shape paths have drifted onto \
12531                 different emit-sets"
12532            );
12533        }
12534        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12535            .iter()
12536            .map(std::sync::Arc::<str>::from)
12537            .collect();
12538        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12539            .iter()
12540            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
12541            .collect();
12542        assert_eq!(
12543            via_iter, via_method,
12544            "`.iter().map(std::sync::Arc::<str>::from)` over \
12545             RestartPolicy::ALL — a call site whose iteration axis \
12546             holds `&RestartPolicy` by construction — must byte-\
12547             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
12548             on every arm — the borrowed-input std::sync::Arc<str> \
12549             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
12550             what makes the `std::sync::Arc::<str>::from` composition \
12551             route through the substrate-primitive \
12552             `RestartPolicy::as_str` accessor without a spurious \
12553             `Copy` deref (which would only be reachable through the \
12554             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
12555             axis by first calling `.copied()` on the iterator)"
12556        );
12557    }
12558
12559    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
12560
12561    #[test]
12562    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
12563        // The fail-before-pass-after pin: pre-lift there was no
12564        // single-source binding between the [`RestartPolicy`] variant
12565        // name the un-`rename`d `Serialize` derive emits under
12566        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
12567        // byte-string every downstream cluster-side dispatcher (the
12568        // future wasm-operator's per-child post-exit restart-decision
12569        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
12570        // materializer's admission-time enum-arm bind, the
12571        // `caixa-operator`'s hierarchical reconciliation scheduler's
12572        // per-child-policy fan-out) probes verbatim. A future
12573        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
12574        // or a per-variant `#[serde(rename = "…")]` override, or a
12575        // variant rename in the source — would silently rebrand the
12576        // emitted scalar under one spelling while every downstream
12577        // dispatcher still probed the other, with the failure surfacing
12578        // at the operator's reconcile posture (children coming up under
12579        // the `default()` `Permanent` arm rather than the typed slot's
12580        // declared policy — a `:temporary` `oneShot` child would be
12581        // restarted on clean exit, treating the successful-completion
12582        // signal as failure and re-running the completion-terminal
12583        // one-shot indefinitely; a `:transient` child that clean-exited
12584        // would be restarted, masking the clean-completion contract)
12585        // far from the source rebrand commit and with no field naming
12586        // the drift. Pinning the two paths (the `Serialize` derive's
12587        // serialized string AND the [`RestartPolicy::as_str`] helper)
12588        // to the same three lifted
12589        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
12590        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
12591        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
12592        // byte-strings makes any future drift on either endpoint fail
12593        // here at caixa-core build time. Peer of the sibling
12594        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
12595        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12596        // and the M3
12597        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
12598        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
12599        // same three-path-convergence discipline, extended to close the
12600        // third OTP-shaped closed-enum discriminator axis on the caixa
12601        // typed surface (per-child restart-decision policy).
12602        for (variant, expected) in [
12603            (
12604                RestartPolicy::Permanent,
12605                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12606            ),
12607            (
12608                RestartPolicy::Temporary,
12609                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12610            ),
12611            (
12612                RestartPolicy::Transient,
12613                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12614            ),
12615        ] {
12616            let json = serde_json::to_string(&variant).unwrap();
12617            assert_eq!(
12618                json,
12619                format!("\"{expected}\""),
12620                "RestartPolicy::{variant:?} must serialize to {expected:?}"
12621            );
12622            assert_eq!(
12623                variant.as_str(),
12624                expected,
12625                "RestartPolicy::{variant:?}.as_str() must return the lifted \
12626                 SUPERVISOR_CHILD_RESTART_* constant"
12627            );
12628        }
12629    }
12630
12631    #[test]
12632    fn supervisor_child_restart_consts_are_pairwise_distinct() {
12633        // Cross-arm drift-detection pin: a future collapse of two
12634        // canonical variant byte-strings onto the same value (e.g. an
12635        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
12636        // to also read `"Permanent"`) would silently reroute every
12637        // downstream operator's per-child-policy dispatch onto the
12638        // sibling arm's reconcile branch and pass every propagation-probe
12639        // test that expected only the stale arm's value — a `:transient`
12640        // child would come up under the `:permanent` restart-decision
12641        // posture on every subsequent clean exit, so a completion-terminal
12642        // child would be restarted indefinitely against its declared
12643        // policy. Peer of the sibling
12644        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
12645        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12646        // and the four-way distinct pin
12647        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
12648        // top-level `SUPERVISOR_KEY_*` axis.
12649        let all = [
12650            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12651            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12652            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12653        ];
12654        for (i, a) in all.iter().enumerate() {
12655            for (j, b) in all.iter().enumerate() {
12656                if i != j {
12657                    assert_ne!(
12658                        a, b,
12659                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
12660                         — got duplicate {a:?} at indices {i} and {j}",
12661                    );
12662                }
12663            }
12664        }
12665    }
12666
12667    #[test]
12668    fn restart_policy_display_routes_through_as_str_helper() {
12669        // The fail-before-pass-after pin on the first half of the
12670        // three-path convergence: pre-convergence [`RestartPolicy`]
12671        // carried a [`std::fmt::Display`] surface via its
12672        // `#[discriminant(also_display)]` gen-platform derive route,
12673        // which arrived kebab-case as `"permanent"` / `"temporary"`
12674        // / `"transient"` on this three-arm enum (whose variant
12675        // names each collapse to their own lowercase form under the
12676        // kebab-case transform) while the wire format ran as
12677        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
12678        // through the un-`rename`d serde derive. Every consumer
12679        // reaching for a policy byte-string past the wire format had
12680        // to pick between three paths ([`RestartPolicy::as_str`],
12681        // the `Serialize` derive's serialized string, or
12682        // `format!("{v}")` on the discriminant-Display route), any
12683        // two of which a future variant rename or
12684        // `#[serde(rename_all = "kebab-case")]` attribute would
12685        // silently desynchronize. Wiring [`std::fmt::Display`]
12686        // through [`RestartPolicy::as_str`] closes the third path:
12687        // every `format!("{v}")` call reaches the same lifted
12688        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
12689        // wire format and the [`RestartPolicy::as_str`] helper
12690        // already route through, so a future variant rename lands at
12691        // exactly one place. Pin the routing here so a future
12692        // `impl std::fmt::Display for RestartPolicy`
12693        // reimplementation that hand-rolls the arms instead of
12694        // delegating to [`RestartPolicy::as_str`] fails at
12695        // caixa-core build time. Peer of the sibling
12696        // [`restart_strategy_display_routes_through_as_str_helper`]
12697        // on the per-supervisor sibling-restart-strategy axis and
12698        // the M3
12699        // `placement_strategy_display_routes_through_as_str_helper`
12700        // (cc8f749) — the third of three OTP-shape closed-enum
12701        // discriminator axes on the caixa typed surface now
12702        // converged onto the same three-path
12703        // (Display → as_str → lifted const) discipline.
12704        for variant in [
12705            RestartPolicy::Permanent,
12706            RestartPolicy::Temporary,
12707            RestartPolicy::Transient,
12708        ] {
12709            assert_eq!(
12710                variant.to_string(),
12711                variant.as_str(),
12712                "RestartPolicy::{variant:?} Display must route through \
12713                 RestartPolicy::as_str (single source of truth: the lifted \
12714                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
12715            );
12716        }
12717    }
12718
12719    #[test]
12720    fn restart_policy_display_matches_serialized_wire_byte_string() {
12721        // The fail-before-pass-after pin on the second half of the
12722        // three-path convergence: `Display` (user-facing text) agrees
12723        // byte-for-byte with the `Serialize` derive's wire format
12724        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
12725        // scalar) on every variant. Pre-convergence the two paths
12726        // were structurally independent — a future
12727        // `#[serde(rename_all = "kebab-case")]` attribute on the
12728        // enum would silently rebrand the emitted wire scalar
12729        // (`permanent`, `temporary`, `transient`) while every
12730        // consumer that pretty-prints the policy (the future
12731        // wasm-operator's per-child post-exit restart-decision
12732        // diagnostic line, the future `feira app graph` per-child
12733        // restart column, the future M4
12734        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
12735        // per-child admission-webhook rejection body) would still
12736        // emit the PascalCase form the `as_str` / `Display` route
12737        // returns, with the mismatch surfacing at consumer parse
12738        // time / operator dispatch time far from the source rebrand
12739        // commit. Pin the two paths byte-for-byte here so any future
12740        // serde-attribute or variant-rename drift is a
12741        // caixa-core-build-time test failure at this call, not a
12742        // silent per-consumer dispatch miss. Peer of the sibling
12743        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
12744        // on the per-supervisor sibling-restart-strategy axis and
12745        // the M3
12746        // `placement_strategy_display_matches_serialized_wire_byte_string`
12747        // (cc8f749).
12748        for variant in [
12749            RestartPolicy::Permanent,
12750            RestartPolicy::Temporary,
12751            RestartPolicy::Transient,
12752        ] {
12753            let wire = serde_json::to_string(&variant).unwrap();
12754            let unquoted = wire
12755                .strip_prefix('"')
12756                .and_then(|s| s.strip_suffix('"'))
12757                .expect("serialized RestartPolicy is a JSON string");
12758            assert_eq!(
12759                variant.to_string(),
12760                unquoted,
12761                "RestartPolicy::{variant:?} Display byte-string must match the \
12762                 Serialize derive's wire byte-string (three-path convergence: \
12763                 Display + as_str + Serialize all resolve to the same \
12764                 SUPERVISOR_CHILD_RESTART_* const)"
12765            );
12766        }
12767    }
12768
12769    #[test]
12770    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
12771        // Fail-before-pass-after byte-parity pin on the lifted
12772        // `impl AsRef<str> for RestartPolicy` — asserts the
12773        // standard-library trait impl and the substrate-primitive
12774        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
12775        // to the same `&str` per instance across the three-arm
12776        // closed set, so any future silent detour that routes the
12777        // impl through a divergent projection (a per-arm inline
12778        // `match self { RestartPolicy::Permanent => "Permanent", … }`
12779        // re-inlining that opens a compile-time link to the un-lifted
12780        // arm-literal, a swap onto the kebab-case
12781        // [`gen_platform::Discriminant`] catalog identity that would
12782        // collide the wire axis with the dispatcher-catalog axis) trips
12783        // at caixa-core test time under `PartialEq` rather than at a
12784        // downstream `impl AsRef<str>`-bound consumer's silent split.
12785        // Sweeps every one of the three arms
12786        // [`RestartPolicy::ALL`] carries so no arm's projection is
12787        // covered only by the sibling wire-format `Serialize` derive
12788        // path. Peer of the sibling
12789        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
12790        // (63eb1a4) on the paired per-supervisor sibling-restart-
12791        // strategy axis and the [`crate::CaixaVersion`]
12792        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
12793        // top-level `:versao` typed newtype — the three pins together
12794        // cover the substrate primitive's `AsRef<str>` projection axis
12795        // on the paired newtype + M2 closed-set-typed-enum surface.
12796        for &variant in RestartPolicy::ALL {
12797            assert_eq!(
12798                <RestartPolicy as AsRef<str>>::as_ref(&variant),
12799                variant.as_str(),
12800                "AsRef<str> impl on RestartPolicy::{variant:?} must \
12801                 byte-equal RestartPolicy::as_str on the same instance \
12802                 — divergence signals a silent detour off the substrate-\
12803                 primitive accessor"
12804            );
12805        }
12806    }
12807
12808    #[test]
12809    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
12810        // Fail-before-pass-after byte-parity pin on the three-path
12811        // convergence discipline the M2 per-child-restart-policy
12812        // primitive now carries on the `&str`-projection axis:
12813        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
12814        // lifted impl), `format!("{v}")` (the pre-existing
12815        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
12816        // primitive `pub const fn` accessor both trait impls delegate
12817        // through) must resolve to the same byte-string on every
12818        // instance across the three-arm closed set. Refuses any future
12819        // divergence between the two trait impls (a stray
12820        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
12821        // rather than delegating through the shared accessor; a
12822        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
12823        // literal cascade) that would silently split the two
12824        // projection paths of the same closed-set typed enum. Mirrors
12825        // the sibling three-path-convergence discipline the peer
12826        // [`RestartStrategy`] typed enum carries on its
12827        // `AsRef<str>` / `Display` / `as_str` triple
12828        // (supervisor.rs pin
12829        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
12830        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
12831        // carries on the same triple (version.rs pin
12832        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
12833        // 16d5c7e).
12834        for &variant in RestartPolicy::ALL {
12835            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12836            let via_display: String = format!("{variant}");
12837            let via_accessor: &str = variant.as_str();
12838            assert_eq!(via_as_ref, via_accessor);
12839            assert_eq!(via_display, via_accessor);
12840            assert_eq!(via_as_ref, via_display.as_str());
12841        }
12842    }
12843
12844    // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
12845    // shapes below are the borrowed-input witness half of the by-value +
12846    // by-reference partition the paired witness pair carries: the pair proves
12847    // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
12848    // shapes through the same substrate-primitive `as_str` accessor, which is
12849    // the shape the caixa-lacre BLAKE3 content-address closure composes.
12850    // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
12851    // into the owned half and collapse the by-value/by-reference partition
12852    // this test load-bears; the `#[allow]` documents that the partition is
12853    // deliberate, not an oversight.
12854    #[allow(clippy::needless_borrows_for_generic_args)]
12855    #[test]
12856    fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
12857        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
12858        // function that binds its argument through the standard-library
12859        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
12860        // directly, without the caller open-coding the two-hop
12861        // `restart.as_str().as_bytes()` composition. Lifted to the top
12862        // of the function per `clippy::items_after_statements`.
12863        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
12864            t.as_ref().to_vec()
12865        }
12866        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
12867        // `blake3::Hasher::update` / `ring::digest::Context::update` /
12868        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
12869        // signature so a per-child BLAKE3 content-address closure that
12870        // composes `hasher.update(restart)` on the [`crate::Lacre`]
12871        // closure builder reaches the substrate-primitive `as_str`
12872        // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
12873        // axis and no other. Lifted to the top of the function per
12874        // `clippy::items_after_statements`.
12875        struct MockHasher(Vec<u8>);
12876        impl MockHasher {
12877            fn new() -> Self {
12878                Self(Vec::new())
12879            }
12880            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
12881                self.0.extend_from_slice(bytes.as_ref());
12882                self
12883            }
12884            fn finalize(self) -> Vec<u8> {
12885                self.0
12886            }
12887        }
12888
12889        // Fail-before-pass-after byte-parity pin on the newly lifted
12890        // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
12891        // idiomatic byte-view standard-library impl and the substrate-
12892        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
12893        // accessor's `.as_bytes()` byte-tail resolve to the same three-
12894        // arm `PascalCase` wire byte-string emit-set across every arm
12895        // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
12896        // Extends the trait-idiomatic byte-view axis onto the second
12897        // (and final) M2 OTP-shape closed-set fieldless typed enum peer
12898        // on the caixa surface (the paired per-child restart-decision
12899        // policy sibling on the same M2 `:supervisor` slot), closing
12900        // the byte-view axis across the `:supervisor :estrategia` +
12901        // `:children :restart` M2 slot pair the sibling
12902        // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
12903        //
12904        // Rust's standard library carries `impl AsRef<[u8]> for str` and
12905        // `impl AsRef<[u8]> for String`, so a two-hop composition
12906        // `restart.as_str().as_bytes()` (or the equally two-hop
12907        // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
12908        // through the pre-existing str-view axis alone. But that two-hop
12909        // shape has no compile-time link back to the byte-projection
12910        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
12911        // consumer to open-code the two-hop composition at every call
12912        // site, and admits a silent split whenever a future call site
12913        // takes a sibling reverse-projection axis whose `.as_bytes()`
12914        // byte-tail carries no compile-time byte-view surface. This
12915        // impl closes the byte-view axis at the substrate-primitive
12916        // [`super::RestartPolicy::as_str`] accessor so every future
12917        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
12918        // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
12919        // roster the paired str-view axes already return through —
12920        // through one trait dispatch.
12921        for &variant in RestartPolicy::ALL {
12922            let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
12923            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
12924            assert_eq!(
12925                via_trait, via_method_bytes,
12926                "AsRef<[u8]> for RestartPolicy impl must byte-equal \
12927                 RestartPolicy::as_str().as_bytes() on \
12928                 RestartPolicy::{variant:?} — divergence signals a \
12929                 silent detour off the substrate-primitive accessor"
12930            );
12931            // Cross-axis witness against the paired str-view axes'
12932            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
12933            // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
12934            // all resolve to the same lifted
12935            // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
12936            // roster, and the byte-view axis must byte-equal each of
12937            // their `.as_bytes()` byte-tails by construction — locking
12938            // the str-view and byte-view axes together at the
12939            // substrate-primitive accessor.
12940            let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12941            assert_eq!(
12942                via_trait,
12943                str_view_ref.as_bytes(),
12944                "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
12945                 RestartPolicy must resolve to byte-equal byte-tails \
12946                 on RestartPolicy::{variant:?} — divergence signals \
12947                 the byte-view and str-view axes have drifted off the \
12948                 same substrate-primitive as_str accessor"
12949            );
12950            let display_bytes = variant.to_string();
12951            assert_eq!(
12952                via_trait,
12953                display_bytes.as_bytes(),
12954                "AsRef<[u8]> for RestartPolicy and \
12955                 <RestartPolicy as std::fmt::Display>::to_string must \
12956                 resolve to byte-equal byte-tails on \
12957                 RestartPolicy::{variant:?} — divergence signals the \
12958                 byte-view axis and the Display formatter axis have \
12959                 drifted off the same substrate-primitive as_str \
12960                 accessor"
12961            );
12962            // Cross-axis witness against the paired reverse-projection
12963            // axes' `.as_bytes()` byte-tails: every one of `{&'static
12964            // str, String, Cow<'static, str>, Box<str>,
12965            // std::sync::Arc<str>}` allocates (or borrows) the same
12966            // `PascalCase` wire byte-string the substrate-primitive
12967            // accessor emits, so the byte-view axis must byte-equal
12968            // each of their `.as_bytes()` byte-tails by construction.
12969            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12970            assert_eq!(
12971                via_trait,
12972                owned_static.as_bytes(),
12973                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12974                 for &'static str must resolve to byte-equal byte-tails \
12975                 on RestartPolicy::{variant:?}"
12976            );
12977            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12978            assert_eq!(
12979                via_trait,
12980                owned_string.as_bytes(),
12981                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12982                 for String must resolve to byte-equal byte-tails on \
12983                 RestartPolicy::{variant:?}"
12984            );
12985            let owned_cow: std::borrow::Cow<'static, str> =
12986                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12987            assert_eq!(
12988                via_trait,
12989                owned_cow.as_bytes(),
12990                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12991                 for Cow<'static, str> must resolve to byte-equal byte-\
12992                 tails on RestartPolicy::{variant:?}"
12993            );
12994            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12995            assert_eq!(
12996                via_trait,
12997                owned_box.as_bytes(),
12998                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12999                 for Box<str> must resolve to byte-equal byte-tails on \
13000                 RestartPolicy::{variant:?}"
13001            );
13002            let owned_arc: std::sync::Arc<str> =
13003                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13004            assert_eq!(
13005                via_trait,
13006                owned_arc.as_bytes(),
13007                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13008                 for std::sync::Arc<str> must resolve to byte-equal \
13009                 byte-tails on RestartPolicy::{variant:?}"
13010            );
13011        }
13012        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
13013        // input function `generic_bytes_sink` (lifted above per
13014        // `clippy::items_after_statements`) accepts a
13015        // [`super::RestartPolicy`] directly through the trait bound,
13016        // without the caller open-coding the two-hop
13017        // `restart.as_str().as_bytes()` composition. This is the shape
13018        // that reaches the caixa-lacre BLAKE3 content-address closure's
13019        // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
13020        // through this impl and no other.
13021        for &variant in RestartPolicy::ALL {
13022            let via_generic = generic_bytes_sink(variant);
13023            let via_borrowed_generic = generic_bytes_sink(&variant);
13024            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13025            assert_eq!(
13026                via_generic, via_method_bytes,
13027                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13028                 RestartPolicy::{variant:?} must yield the same byte-\
13029                 tail RestartPolicy::as_str().as_bytes() returns — \
13030                 divergence signals the byte-view axis fails to bridge \
13031                 a generic byte-input trait bound to the substrate-\
13032                 primitive accessor"
13033            );
13034            assert_eq!(
13035                via_borrowed_generic, via_method_bytes,
13036                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13037                 &RestartPolicy::{variant:?} must yield the same byte-\
13038                 tail RestartPolicy::as_str().as_bytes() returns — the \
13039                 borrowed-input surface must resolve to the same as_str \
13040                 dispatch"
13041            );
13042        }
13043        // `blake3::Hasher::update`-shape byte-input surface witness on
13044        // the caixa-lacre compounding target: the `MockHasher` (lifted
13045        // above per `clippy::items_after_statements`) mirrors
13046        // `blake3::Hasher::update` / `ring::digest::Context::update` /
13047        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
13048        // signature and accepts a [`super::RestartPolicy`] directly,
13049        // routing its byte-tail through the substrate-primitive
13050        // `as_str` accessor — the shape a future per-child BLAKE3
13051        // content-address closure composes to fold a `:restart`
13052        // discriminator byte-tag into the [`crate::Lacre`] closure
13053        // body.
13054        for &variant in RestartPolicy::ALL {
13055            let mut owned_hasher = MockHasher::new();
13056            owned_hasher.update(variant);
13057            let owned_folded = owned_hasher.finalize();
13058            assert_eq!(
13059                owned_folded,
13060                variant.as_str().as_bytes(),
13061                "`hasher.update(restart)`-shape composition on \
13062                 RestartPolicy::{variant:?} must fold the same byte-\
13063                 tail RestartPolicy::as_str().as_bytes() returns — the \
13064                 shape a future per-child BLAKE3 content-address \
13065                 closure composes to fold a `:restart` discriminator \
13066                 byte-tag into the Lacre closure body"
13067            );
13068            let mut borrowed_hasher = MockHasher::new();
13069            borrowed_hasher.update(&variant);
13070            let borrowed_folded = borrowed_hasher.finalize();
13071            assert_eq!(
13072                borrowed_folded,
13073                variant.as_str().as_bytes(),
13074                "`hasher.update(&restart)`-shape composition on \
13075                 &RestartPolicy::{variant:?} must fold the same byte-\
13076                 tail RestartPolicy::as_str().as_bytes() returns — the \
13077                 borrowed-input surface must resolve to the same as_str \
13078                 dispatch"
13079            );
13080        }
13081    }
13082
13083    #[test]
13084    #[expect(
13085        clippy::too_many_lines,
13086        reason = "the byte-owned reverse-projection axis is closed \
13087                  here across the M2-OTP-shape :supervisor slot pair by \
13088                  extending onto the second and final M2-OTP-shape \
13089                  closed-set fieldless typed-enum peer, so the pin \
13090                  binds the new impl against every paired byte-view \
13091                  and str-owned axis on the same enum plus a generic \
13092                  <T: Into<Vec<u8>>>-bound consumer witness and a \
13093                  std::io::Write::write_all-shape owned-byte-sink \
13094                  surface witness on both owned and borrowed input \
13095                  shapes to lock the whole family against a future \
13096                  silent regression"
13097    )]
13098    fn restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
13099        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
13100        // owned-byte-input function accepts a [`super::RestartPolicy`]
13101        // directly through the trait bound, without the caller open-
13102        // coding the three-hop `restart.as_str().as_bytes().to_vec()`
13103        // composition. Lifted to the top of the function per
13104        // `clippy::items_after_statements`.
13105        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
13106            t.into()
13107        }
13108        // `std::io::Write::write_all`-shape owned-byte-sink surface
13109        // mock: mirrors `std::io::Write::write_all` /
13110        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
13111        // byte-sink that consumes a `Vec<u8>` payload via
13112        // `Into<Vec<u8>>`, so a future per-child per-`:restart` audit-
13113        // log emit reaches the substrate-primitive `as_str` accessor
13114        // through the byte-owned reverse-projection axis and no
13115        // other. Lifted to the top of the function per
13116        // `clippy::items_after_statements`.
13117        struct MockOwnedByteSink(Vec<u8>);
13118        impl MockOwnedByteSink {
13119            fn new() -> Self {
13120                Self(Vec::new())
13121            }
13122            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
13123                self.0.extend(bytes.into());
13124                self
13125            }
13126            fn finalize(self) -> Vec<u8> {
13127                self.0
13128            }
13129        }
13130
13131        // Fail-before-pass-after byte-parity pin on the newly lifted
13132        // `impl From<RestartPolicy> for Vec<u8>` and
13133        // `impl From<&RestartPolicy> for Vec<u8>` — asserts the trait-
13134        // idiomatic byte-owned reverse-projection standard-library
13135        // impls and the substrate-primitive
13136        // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
13137        // `.as_bytes().to_vec()` byte-tail resolve to the same three-
13138        // arm PascalCase wire byte-string emit-set across every arm
13139        // the exhaustive [`super::RestartPolicy::ALL`] slice
13140        // enumerates. Closes the substrate-wide trait-idiomatic byte-
13141        // owned reverse-projection axis on the M2-OTP-shape closed-
13142        // set typed-enum pair the sibling first-mover
13143        // [`super::RestartStrategy`] `From<{Self, &Self}> for Vec<u8>`
13144        // lift (63e5dd0) opened one commit prior, matching the
13145        // trajectory the paired [`AsRef<[u8]>`] borrowed byte-view
13146        // axis campaign already tracked across the same slot pair
13147        // (cd4c4e0 → 98b08fa).
13148        for &variant in RestartPolicy::ALL {
13149            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
13150            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
13151            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
13152            assert_eq!(
13153                via_owned_from, via_method_bytes,
13154                "From<RestartPolicy> for Vec<u8> impl must byte-equal \
13155                 RestartPolicy::as_str().as_bytes().to_vec() on \
13156                 RestartPolicy::{variant:?} — divergence signals a \
13157                 silent detour off the substrate-primitive accessor"
13158            );
13159            assert_eq!(
13160                via_borrowed_from, via_method_bytes,
13161                "From<&RestartPolicy> for Vec<u8> impl must byte-\
13162                 equal RestartPolicy::as_str().as_bytes().to_vec() \
13163                 on RestartPolicy::{variant:?} — divergence signals \
13164                 a silent detour off the substrate-primitive accessor"
13165            );
13166            assert_eq!(
13167                via_owned_from, via_borrowed_from,
13168                "From<RestartPolicy> for Vec<u8> and \
13169                 From<&RestartPolicy> for Vec<u8> must byte-equal \
13170                 each other on RestartPolicy::{variant:?} — \
13171                 divergence signals the owned-input and borrowed-input \
13172                 paths have drifted off the same substrate-primitive \
13173                 as_str accessor"
13174            );
13175            // Cross-axis witness against the paired [`AsRef<[u8]>`]
13176            // borrowed byte-view axis (98b08fa): the byte-owned
13177            // reverse-projection axis must byte-equal the paired
13178            // borrowed byte-view axis by construction — locking the
13179            // byte-view and byte-owned axes together at the substrate-
13180            // primitive accessor.
13181            let borrowed_bytes: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
13182            assert_eq!(
13183                via_owned_from,
13184                borrowed_bytes.to_vec(),
13185                "From<RestartPolicy> for Vec<u8> and AsRef<[u8]> for \
13186                 RestartPolicy must resolve to byte-equal byte-tails \
13187                 on RestartPolicy::{variant:?} — divergence signals \
13188                 the byte-owned and byte-view axes have drifted off \
13189                 the same substrate-primitive as_str accessor"
13190            );
13191            // Cross-axis witness against the str-owned reverse-
13192            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
13193            // byte-tails: every one of `{String, Cow<'static, str>,
13194            // Box<str>, std::sync::Arc<str>}` allocates (or borrows)
13195            // the same PascalCase wire byte-string the substrate-
13196            // primitive accessor emits, so the byte-owned axis must
13197            // byte-equal each of their owned byte-tails by
13198            // construction.
13199            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13200            assert_eq!(
13201                via_owned_from,
13202                owned_string.into_bytes(),
13203                "From<RestartPolicy> for Vec<u8> and \
13204                 String::from(policy).into_bytes() must resolve to \
13205                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13206            );
13207            let owned_cow: std::borrow::Cow<'static, str> =
13208                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13209            assert_eq!(
13210                via_owned_from,
13211                owned_cow.as_bytes().to_vec(),
13212                "From<RestartPolicy> for Vec<u8> and \
13213                 From<RestartPolicy> for Cow<'static, str> must \
13214                 resolve to byte-equal byte-tails on \
13215                 RestartPolicy::{variant:?}"
13216            );
13217            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13218            assert_eq!(
13219                via_owned_from,
13220                owned_box.as_bytes().to_vec(),
13221                "From<RestartPolicy> for Vec<u8> and \
13222                 From<RestartPolicy> for Box<str> must resolve to \
13223                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13224            );
13225            let owned_arc: std::sync::Arc<str> =
13226                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13227            assert_eq!(
13228                via_owned_from,
13229                owned_arc.as_bytes().to_vec(),
13230                "From<RestartPolicy> for Vec<u8> and \
13231                 From<RestartPolicy> for std::sync::Arc<str> must \
13232                 resolve to byte-equal byte-tails on \
13233                 RestartPolicy::{variant:?}"
13234            );
13235        }
13236        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
13237        // and borrowed input shapes: the generic owned-byte-input
13238        // function `generic_owned_bytes_sink` (lifted above per
13239        // `clippy::items_after_statements`) accepts a
13240        // [`super::RestartPolicy`] and a `&RestartPolicy` directly
13241        // through the trait bound, without the caller open-coding
13242        // the three-hop `restart.as_str().as_bytes().to_vec()`
13243        // composition.
13244        for &variant in RestartPolicy::ALL {
13245            let via_generic_owned = generic_owned_bytes_sink(variant);
13246            // Bind the borrowed-input path through an explicit
13247            // `&RestartPolicy` local so the generic-consumer witness
13248            // routes through `From<&RestartPolicy> for Vec<u8>` (T
13249            // binds to `&RestartPolicy`) rather than clippy-collapsing
13250            // the borrow onto the owned-input peer.
13251            let variant_ref: &RestartPolicy = &variant;
13252            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
13253            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13254            assert_eq!(
13255                via_generic_owned, via_method_bytes,
13256                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13257                 RestartPolicy::{variant:?} must yield the same byte-\
13258                 tail RestartPolicy::as_str().as_bytes() returns — \
13259                 divergence signals the byte-owned axis fails to bridge \
13260                 a generic owned-byte-input trait bound to the \
13261                 substrate-primitive accessor"
13262            );
13263            assert_eq!(
13264                via_generic_borrowed, via_method_bytes,
13265                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13266                 &RestartPolicy::{variant:?} must yield the same byte-\
13267                 tail RestartPolicy::as_str().as_bytes() returns — \
13268                 the borrowed-input surface must resolve to the same \
13269                 as_str dispatch"
13270            );
13271        }
13272        // `std::io::Write::write_all`-shape owned-byte-sink surface
13273        // witness: the `MockOwnedByteSink` (lifted above per
13274        // `clippy::items_after_statements`) mirrors
13275        // `std::io::Write::write_all` /
13276        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
13277        // bound owned-byte input signature and accepts a
13278        // [`super::RestartPolicy`] directly on both owned and
13279        // borrowed input shapes, routing its byte-tail through the
13280        // substrate-primitive `as_str` accessor — the shape a future
13281        // per-child per-`:restart` audit-log emit composes to fold a
13282        // `:restart` discriminator byte-tag into a downstream owned-
13283        // byte-sink surface.
13284        for &variant in RestartPolicy::ALL {
13285            let mut owned_sink = MockOwnedByteSink::new();
13286            owned_sink.write_all(variant);
13287            let owned_folded = owned_sink.finalize();
13288            assert_eq!(
13289                owned_folded,
13290                variant.as_str().as_bytes(),
13291                "`sink.write_all(restart)`-shape composition on \
13292                 RestartPolicy::{variant:?} must fold the same byte-\
13293                 tail RestartPolicy::as_str().as_bytes() returns"
13294            );
13295            let mut borrowed_sink = MockOwnedByteSink::new();
13296            let variant_ref: &RestartPolicy = &variant;
13297            borrowed_sink.write_all(variant_ref);
13298            let borrowed_folded = borrowed_sink.finalize();
13299            assert_eq!(
13300                borrowed_folded,
13301                variant.as_str().as_bytes(),
13302                "`sink.write_all(&restart)`-shape composition on \
13303                 &RestartPolicy::{variant:?} must fold the same byte-\
13304                 tail RestartPolicy::as_str().as_bytes() returns — \
13305                 the borrowed-input surface must resolve to the same \
13306                 as_str dispatch"
13307            );
13308        }
13309    }
13310
13311    #[test]
13312    fn restart_policy_all_enumerates_every_variant_exactly_once() {
13313        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
13314        // exhaustive-iteration surface: every variant appears exactly
13315        // once, and the slice length matches the arm count of the
13316        // closed set. Every consumer that walks the accepted-policy
13317        // set (a future `feira supervisor --restart …` CLI-side
13318        // arg-parse's "did you mean" hint, a future M4 admission-
13319        // webhook's per-child rejection body naming the accepted-
13320        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
13321        // projection consumers that iterate the accept-set for
13322        // diagnostic rendering) reads through this slice, so a future
13323        // arm addition that grows the enum but forgets to grow
13324        // [`Self::ALL`] silently truncates every downstream consumer's
13325        // accept-set at the same pre-addition boundary — this pin
13326        // fails at caixa-core build time on the pairwise-distinct +
13327        // arm-count invariants.
13328        //
13329        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
13330        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
13331        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
13332        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
13333        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13334        // pins on the peer closed-set typed-enum axes.
13335        let all: &[RestartPolicy] = RestartPolicy::ALL;
13336        assert_eq!(
13337            all.len(),
13338            3,
13339            "RestartPolicy::ALL must enumerate every variant of the \
13340             three-arm closed set (Permanent, Temporary, Transient); \
13341             got {all:?}"
13342        );
13343        for (i, a) in all.iter().enumerate() {
13344            for (j, b) in all.iter().enumerate() {
13345                if i != j {
13346                    assert_ne!(
13347                        a, b,
13348                        "RestartPolicy::ALL must carry every variant exactly \
13349                         once — got duplicate {a:?} at indices {i} and {j}"
13350                    );
13351                }
13352            }
13353        }
13354        for variant in [
13355            RestartPolicy::Permanent,
13356            RestartPolicy::Temporary,
13357            RestartPolicy::Transient,
13358        ] {
13359            assert!(
13360                all.contains(&variant),
13361                "RestartPolicy::ALL must contain {variant:?} — a future arm \
13362                 addition that grows the enum but forgets to grow the ALL slice \
13363                 silently truncates every downstream consumer's accept-set at \
13364                 the pre-addition boundary"
13365            );
13366        }
13367    }
13368
13369    #[test]
13370    fn restart_policy_wire_names_covers_every_arm() {
13371        // Load-bearing pin on the substrate-canonical
13372        // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
13373        // the `PascalCase` wire byte-string axis: every variant of the
13374        // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
13375        // must project through [`RestartPolicy::as_str`] onto an entry
13376        // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
13377        // roster's length must byte-equal `RestartPolicy::ALL.len()` so
13378        // a silent skew between the [`RestartPolicy::as_str`] match's
13379        // arm-set and the roster's arm-set trips here at caixa-core
13380        // test time rather than at a downstream M4
13381        // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
13382        // rejection body's wire-form `:restart` accepted-set
13383        // enumeration miss / a `feira supervisor --restart …` "did you
13384        // mean" hint drift / a future wasm-operator per-reconcile-step
13385        // diagnostic log line's accepted-wire-form enumeration miss.
13386        // A future arm addition (an OTP-`intrinsic` fourth arm the
13387        // theory
13388        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
13389        // might reach for once the three canonical OTP restart policies
13390        // stop covering the substrate's discovered load-shape) extends
13391        // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
13392        // the new arm by iteration; the paired
13393        // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
13394        // this assertion trips. Every entry is further pinned to open
13395        // with an ASCII uppercase byte so a silent collapse of the
13396        // wire-form axis with the peer kebab-case dispatcher-catalog
13397        // axis (an entry byte-identical to a sibling
13398        // [`RestartPolicy::discriminant`] kebab byte-string that would
13399        // let a wire-axis consumer accept the dispatcher-catalog
13400        // vocabulary) trips here rather than at a downstream K8s-CR
13401        // round-trip miss.
13402        //
13403        // Peer of the sibling
13404        // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
13405        // pin on the first M2 OTP-shape sibling-restart closed-set
13406        // typed enum, the sibling
13407        // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
13408        // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
13409        // closed-set typed enum, the sibling
13410        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
13411        // (bd708bd) pin on the top-level typed-kind discriminator's
13412        // `PascalCase` wire byte-string axis, and the sibling
13413        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
13414        // (cc42c0e) /
13415        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
13416        // (1898d77) pins on the OTP-appup discriminator's two-axis
13417        // roster split — the same closed-set exhaustive-roster coverage
13418        // discipline extended here onto the second and final M2
13419        // OTP-shape sibling-enum on the caixa surface, closing the
13420        // per-child restart-decision-policy axis paired with the peer
13421        // per-supervisor sibling-restart-strategy axis on the same M2
13422        // `:supervisor` slot.
13423        //
13424        // Fail-before-pass-after locally verified by mutating one arm
13425        // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13426        // const family (e.g. dropping the trailing `t` from
13427        // `"Permanent"` → `"Permanen"`) — the length pin still passes
13428        // but the `contains` check fires on the mutated arm; and by
13429        // shortening the roster to two entries — the length pin fires
13430        // first.
13431        assert_eq!(
13432            RestartPolicy::WIRE_NAMES.len(),
13433            RestartPolicy::ALL.len(),
13434            "RestartPolicy::WIRE_NAMES.len() must byte-equal \
13435             RestartPolicy::ALL.len() — a mismatch means the roster \
13436             and the enum's arm-set have drifted; downstream consumers \
13437             that fan through both will silently disagree on the \
13438             accepted arm-set"
13439        );
13440        for &variant in RestartPolicy::ALL {
13441            let wire = variant.as_str();
13442            assert!(
13443                RestartPolicy::WIRE_NAMES.contains(&wire),
13444                "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
13445                 be a member of RestartPolicy::WIRE_NAMES — the \
13446                 emitter and the roster have drifted out of lockstep"
13447            );
13448        }
13449        for tag in RestartPolicy::WIRE_NAMES {
13450            let first = tag.chars().next().unwrap_or_else(|| {
13451                panic!(
13452                    "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
13453                     a non-empty PascalCase byte-string"
13454                )
13455            });
13456            assert!(
13457                first.is_ascii_uppercase(),
13458                "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
13459                 with an ASCII uppercase byte (PascalCase wire form) — \
13460                 a lowercase entry would collide the wire-form axis \
13461                 with the peer kebab-case dispatcher-catalog axis \
13462                 [`RestartPolicy::discriminant`] serves"
13463            );
13464        }
13465    }
13466
13467    #[test]
13468    fn restart_policy_from_wire_accepts_every_lifted_constant() {
13469        // Fail-before-pass-after pin on the forward accept-set of the
13470        // [`RestartPolicy::from_wire`] reverse projection: every
13471        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13472        // constant the [`RestartPolicy::as_str`] emitter walks parses
13473        // back to its paired variant. Any future arm addition that
13474        // grows the emitter's `as_str` match but forgets to grow the
13475        // parser's `from_wire` match silently splits the two halves of
13476        // the round-trip — the wire byte-string one non-serde consumer
13477        // parses from the one the emitter wrote — with the failure
13478        // surfacing at the operator's reconcile posture (a `:temporary`
13479        // `oneShot` child restarted on clean exit, a `:transient` child
13480        // restarted after clean completion) far from the rebrand
13481        // commit. Pinning the three-arm accept-set here catches the
13482        // drift at caixa-core build time.
13483        //
13484        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
13485        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
13486        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
13487        // accept-set pins on the peer closed-set typed-enum `str → Self`
13488        // axes.
13489        for (wire, expected) in [
13490            (
13491                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13492                RestartPolicy::Permanent,
13493            ),
13494            (
13495                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13496                RestartPolicy::Temporary,
13497            ),
13498            (
13499                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13500                RestartPolicy::Transient,
13501            ),
13502        ] {
13503            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13504                panic!(
13505                    "RestartPolicy::from_wire({wire:?}) must accept every \
13506                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
13507                     lifted canonical byte-string that RestartPolicy::{expected:?} \
13508                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
13509                )
13510            });
13511            assert_eq!(
13512                parsed, expected,
13513                "RestartPolicy::from_wire({wire:?}) must return \
13514                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
13515            );
13516        }
13517    }
13518
13519    #[test]
13520    fn restart_policy_from_wire_round_trips_through_as_str() {
13521        // Fail-before-pass-after pin on the closed round-trip between
13522        // the forward [`RestartPolicy::as_str`] emitter and the
13523        // reverse [`RestartPolicy::from_wire`] parser: for every
13524        // variant in [`RestartPolicy::ALL`], parsing the emitter's
13525        // output must return exactly the same variant. Any per-arm
13526        // divergence — a future arm added to `as_str` but not
13527        // `from_wire`, an accidental copy-paste flip in one but not
13528        // the other — silently splits the emit and parse halves and
13529        // the failure surfaces at consumer parse time far from the
13530        // drift site. The `ALL`-iterating shape means a future arm
13531        // addition picks up the coverage by construction.
13532        //
13533        // Peer of the sibling
13534        // [`restart_strategy_from_wire_round_trips_through_as_str`]
13535        // (4eec29c) round-trip pin on
13536        // [`RestartStrategy::from_wire`] and the M3
13537        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
13538        // (18c7342) round-trip pin on
13539        // [`crate::aplicacao::PlacementStrategy::from_wire`].
13540        for &variant in RestartPolicy::ALL {
13541            let wire = variant.as_str();
13542            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13543                panic!(
13544                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13545                     must be Some({variant:?}) — the two halves of the round-trip \
13546                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
13547                     got None on wire byte-string {wire:?}"
13548                )
13549            });
13550            assert_eq!(
13551                parsed, variant,
13552                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13553                 must round-trip to the same variant; got {parsed:?}"
13554            );
13555        }
13556    }
13557
13558    #[test]
13559    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
13560        // Fail-before-pass-after pin on the closed-set refusal
13561        // discipline of [`RestartPolicy::from_wire`]: every
13562        // byte-string outside the three-arm accept-set returns `None`
13563        // rather than silently collapsing onto the [`Default`]
13564        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
13565        // exercised here sweeps the load-bearing drift shapes: the
13566        // empty string (a stripped serde-attribute drift), all-
13567        // whitespace strings (the canonical text-editor accidental
13568        // padding shape), the kebab-case dispatcher-catalog identities
13569        // (`"permanent"` / `"temporary"` / `"transient"` — the
13570        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
13571        // accept-set, which parses the *other* axis of this enum's
13572        // two-axis split and must not leak into the `from_wire`
13573        // PascalCase-wire accept-set — a lowercase leak here would
13574        // silently accept the operator's kebab-case
13575        // dispatcher-catalog probe under the wire-axis parser and mis-
13576        // route a `:permanent` intent), the padded canonical scalar
13577        // (`" Permanent "`), the trailing-newline shapes
13578        // (`"Permanent\n"`), the uppercase-single-word forms
13579        // (`"PERMANENT"`), and neighboring-but-unknown arms
13580        // (`"Restart"` — the canonical typo direction toward the
13581        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
13582        //
13583        // Peer of the sibling
13584        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
13585        // (4eec29c) +
13586        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13587        // (2aa6d23) +
13588        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
13589        // (18c7342) refusal pins on the peer closed-set typed-enum
13590        // axes.
13591        for bad in [
13592            "",
13593            " ",
13594            "\n",
13595            "\t",
13596            "permanent",
13597            "temporary",
13598            "transient",
13599            "PERMANENT",
13600            "TEMPORARY",
13601            "TRANSIENT",
13602            "Permanents",
13603            "Permanent ",
13604            " Permanent",
13605            " Transient ",
13606            "Permanent\n",
13607            "perma",
13608            "Trans",
13609            "OneForOne",
13610            "Restart",
13611            "?",
13612        ] {
13613            assert!(
13614                RestartPolicy::from_wire(bad).is_none(),
13615                "RestartPolicy::from_wire({bad:?}) must return None — the \
13616                 parser's accept-set is exactly the three RestartPolicy::as_str \
13617                 outputs (Permanent, Temporary, Transient), and this \
13618                 byte-string is outside that closed set"
13619            );
13620        }
13621    }
13622
13623    #[test]
13624    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
13625        // Fail-before-pass-after pin on the fourth path of the four-path
13626        // convergence: `from_wire` (the reverse projection) inverts the
13627        // `Serialize` derive's wire byte-string on every variant.
13628        // Together with the pre-existing three-path convergence
13629        // (`Display` + `as_str` + `Serialize` all resolve to the same
13630        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
13631        // pinned by
13632        // [`restart_policy_display_matches_serialized_wire_byte_string`])
13633        // this closes the round-trip: the wire byte-string the
13634        // `Serialize` derive emits parses back to the same variant
13635        // through `from_wire`, so any future serde-attribute or variant-
13636        // rename drift on the emit half now surfaces as a matched drift
13637        // on the parse half at caixa-core build time — the two halves
13638        // migrate as a unit through the lifted consts on any future
13639        // rename, and the round-trip cannot silently split.
13640        //
13641        // Peer of the sibling
13642        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13643        // (4eec29c) wire-format pin on
13644        // [`RestartStrategy::from_wire`] and the M3
13645        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13646        // (18c7342) wire-format pin on
13647        // [`crate::aplicacao::PlacementStrategy::from_wire`].
13648        for &variant in RestartPolicy::ALL {
13649            let wire = serde_json::to_string(&variant).unwrap();
13650            let unquoted = wire
13651                .strip_prefix('"')
13652                .and_then(|s| s.strip_suffix('"'))
13653                .expect("serialized RestartPolicy is a JSON string");
13654            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
13655                panic!(
13656                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
13657                     Serialize derive's wire byte-string for \
13658                     RestartPolicy::{variant:?} — the four-path convergence \
13659                     (Display + as_str + Serialize + from_wire) resolves through \
13660                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
13661                )
13662            });
13663            assert_eq!(
13664                parsed, variant,
13665                "RestartPolicy::from_wire of the Serialize derive's wire \
13666                 byte-string for RestartPolicy::{variant:?} must round-trip \
13667                 to the same variant; got {parsed:?}"
13668            );
13669        }
13670    }
13671
13672    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
13673    //
13674    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
13675    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
13676    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
13677    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
13678    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
13679    // the peer per-`:upgrade-from :from` axis. The three pins jointly
13680    // brace the accessor against every future silent detour that would
13681    // desynchronize it from the raw `.caixa` field access every consumer
13682    // previously open-coded.
13683
13684    #[test]
13685    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
13686        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
13687        // [`ChildSpec::nome`] must return the `:children :caixa` field
13688        // byte-for-byte across every DNS-1123-label value the upstream
13689        // [`crate::render::require_valid_dns_1123_label`] gate at
13690        // `SupervisorSpec::validate` admits. Peer of the sibling
13691        // `membro_nome_returns_caixa_byte_equal_across_permutations`
13692        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
13693        // substrate-primitive accessor must byte-equal the raw field
13694        // access verbatim across every author-declared value" discipline
13695        // extended to the M2 supervisor-tree per-`:children` arm. Pins
13696        // against a future silent detour that re-normalized the child
13697        // identity (an accidental `.to_lowercase()` — every `:children
13698        // :caixa` is validated as a DNS-1123 label upstream, so any
13699        // re-normalization is redundant + a drift surface between the
13700        // validator and the accessor), a namespace-prefix rewrite (an
13701        // accidental `format!("{namespace}/{caixa}")` per-CR
13702        // fully-qualified rewrite that didn't land on the peer axes), or
13703        // a per-cluster alias stamp the future wasm-operator's
13704        // hierarchical reconciliation scheduler authors on one consumer
13705        // without the others. Five values sweep the accept-set the
13706        // DNS-1123 gate upstream admits (short single-word / dashed /
13707        // v-suffixed / mixed-digit child names).
13708        for name in [
13709            "worker",
13710            "cache-server",
13711            "scratch-job",
13712            "orders-v2",
13713            "session-8080",
13714        ] {
13715            let c = ChildSpec {
13716                caixa: name.into(),
13717                versao: "^0.1".into(),
13718                restart: RestartPolicy::Permanent,
13719            };
13720            assert_eq!(
13721                c.nome(),
13722                name,
13723                "ChildSpec::nome must return :children :caixa verbatim \
13724                 (got {:?}, expected {name:?})",
13725                c.nome(),
13726            );
13727            assert_eq!(
13728                c.nome(),
13729                c.caixa.as_str(),
13730                "ChildSpec::nome must byte-equal the .caixa field access",
13731            );
13732        }
13733    }
13734
13735    #[test]
13736    fn child_spec_nome_borrows_from_caixa_storage() {
13737        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
13738        // `&str` slice that borrows from the typed slot's own [`String`]
13739        // storage — same-address invariant with `c.caixa.as_str()`. Pins
13740        // against a future silent detour that allocated a fresh `String`
13741        // (`self.caixa.clone()` in the body would type-check but silently
13742        // drop the borrow, and every downstream consumer that assumed
13743        // the returned slice outlives `&self` would break on a stale-
13744        // reference use-after-free — the [`crate::render::insert_first_seen`]
13745        // dedup key at [`SupervisorSpec::validate`], the
13746        // [`validate_no_self_supervision`] equality check against the
13747        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
13748        // borrow — each would silently misbehave if this accessor
13749        // produced a detached copy). Peer of the sibling
13750        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
13751        // M3 per-`:membros` axis and the
13752        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
13753        // first M2 slot scalar accessor.
13754        let c = ChildSpec {
13755            caixa: "worker".into(),
13756            versao: "^0.1".into(),
13757            restart: RestartPolicy::Permanent,
13758        };
13759        let name = c.nome();
13760        let caixa_slice = c.caixa.as_str();
13761        assert_eq!(
13762            name.as_ptr(),
13763            caixa_slice.as_ptr(),
13764            "ChildSpec::nome must borrow from the .caixa String's backing \
13765             storage — a fresh allocation here means the accessor no \
13766             longer names the substrate-primitive typed dispatch and \
13767             every downstream consumer would silently carry a detached \
13768             copy",
13769        );
13770        assert_eq!(
13771            name.len(),
13772            caixa_slice.len(),
13773            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
13774             as well as in address",
13775        );
13776    }
13777
13778    #[test]
13779    fn validate_gates_child_nome_through_lifted_accessor() {
13780        // Bilateral coherence pin: every `:children :caixa` that
13781        // [`SupervisorSpec::validate`] accepts is one
13782        // [`crate::render::require_valid_dns_1123_label`] accepts on the
13783        // accessor-projected value, and vice versa on the reject side.
13784        // This closes the "the validator reads through the accessor"
13785        // contract structurally — a future silent detour that made the
13786        // accessor return a different byte-string than the validator
13787        // gates against would surface here as a coverage mismatch, not
13788        // as an apply-time DNS-1123 rejection at
13789        // `metadata.name: Invalid value` far from the caixa.lisp source.
13790        // Peer of the M2 sibling
13791        // `validate_parses_prior_versao_through_lifted_accessor`
13792        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
13793        // `validate_membros` peer discipline.
13794        //
13795        // Accept-set sweep: five DNS-1123-label values the upstream gate
13796        // admits.
13797        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
13798            let s = SupervisorSpec {
13799                children: vec![ChildSpec {
13800                    caixa: ok_name.into(),
13801                    versao: "^0.1".into(),
13802                    restart: RestartPolicy::Permanent,
13803                }],
13804                ..SupervisorSpec::default()
13805            };
13806            s.validate().unwrap_or_else(|e| {
13807                panic!(
13808                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
13809                     (upstream DNS-1123 gate accepts it): got {e:?}",
13810                );
13811            });
13812            let c = ChildSpec {
13813                caixa: ok_name.into(),
13814                versao: "^0.1".into(),
13815                restart: RestartPolicy::Permanent,
13816            };
13817            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
13818                .unwrap_or_else(|()| {
13819                    panic!(
13820                        "require_valid_dns_1123_label must accept the accessor-projected \
13821                     :children :caixa {ok_name:?}",
13822                    );
13823                });
13824        }
13825        // Reject-set sweep: five DNS-1123-label-violating shapes the
13826        // upstream gate refuses (empty / uppercase / underscore / dot /
13827        // leading-hyphen). Every rejection at the validator must
13828        // correspond to a rejection when the accessor's projected value
13829        // is fed back through the shared gate.
13830        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
13831            let s = SupervisorSpec {
13832                children: vec![ChildSpec {
13833                    caixa: bad_name.into(),
13834                    versao: "^0.1".into(),
13835                    restart: RestartPolicy::Permanent,
13836                }],
13837                ..SupervisorSpec::default()
13838            };
13839            let err = s.validate().unwrap_err();
13840            assert!(
13841                matches!(
13842                    err,
13843                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
13844                ),
13845                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
13846                 via the DNS-1123 gate: got {err:?}",
13847            );
13848            let c = ChildSpec {
13849                caixa: bad_name.into(),
13850                versao: "^0.1".into(),
13851                restart: RestartPolicy::Permanent,
13852            };
13853            assert!(
13854                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
13855                    .is_err(),
13856                "require_valid_dns_1123_label must reject the accessor-projected \
13857                 :children :caixa {bad_name:?}",
13858            );
13859        }
13860    }
13861
13862    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
13863    //
13864    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
13865    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
13866    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
13867    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
13868    // trio on the peer per-`:children` `String`-carry axis. The three pins
13869    // jointly brace the accessor against every future silent detour that
13870    // would desynchronize it from the raw `.versao` field access the
13871    // requirement gate + error carrier previously open-coded.
13872    //
13873    // Closes the last unlifted per-`:children` `String`-carry axis: the
13874    // pair (`nome`, `versao_requirement`) now jointly projects the
13875    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
13876    // consumer that fans on per-child identity + version pin reads,
13877    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
13878    // pair discipline verbatim.
13879    #[test]
13880    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
13881        // The canonical per-`:children` child-`:versao`-scalar pin:
13882        // [`ChildSpec::versao_requirement`] must return the `:children
13883        // :versao` field byte-for-byte across every Cargo-shaped semver
13884        // requirement value the upstream
13885        // [`crate::render::require_valid_versao_requirement`] gate admits.
13886        // Peer of the sibling
13887        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
13888        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
13889        // substrate-primitive accessor must byte-equal the raw field
13890        // access verbatim across every author-declared value" discipline
13891        // extended to the M2 supervisor-tree per-`:children` arm. Pins
13892        // against a future silent detour that re-canonicalized the
13893        // requirement (an accidental `.to_string()` via
13894        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
13895        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
13896        // silently drifted the error carrier's quoted requirement away
13897        // from the source `caixa.lisp`, an accidental whitespace trim on
13898        // `"^ 0.1"` that no consumer ever produced from the field-access
13899        // side, an accidental per-cluster lacre-projected concrete-version
13900        // rewrite that didn't land on the peer requirement-gate call).
13901        // Five values sweep the accept-set the shared
13902        // [`crate::render::require_valid_versao_requirement`] gate admits
13903        // (caret / tilde / exact / wildcard / bare-major).
13904        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
13905            let c = ChildSpec {
13906                caixa: "worker".into(),
13907                versao: req.into(),
13908                restart: RestartPolicy::Permanent,
13909            };
13910            assert_eq!(
13911                c.versao_requirement(),
13912                req,
13913                "ChildSpec::versao_requirement must return :children :versao \
13914                 verbatim (got {:?}, expected {req:?})",
13915                c.versao_requirement(),
13916            );
13917            assert_eq!(
13918                c.versao_requirement(),
13919                c.versao.as_str(),
13920                "ChildSpec::versao_requirement must byte-equal the .versao \
13921                 field access",
13922            );
13923        }
13924    }
13925
13926    #[test]
13927    fn child_spec_versao_requirement_borrows_from_versao_storage() {
13928        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
13929        // return a `&str` slice that borrows from the typed slot's own
13930        // [`String`] storage — same-address invariant with
13931        // `c.versao.as_str()`. Pins against a future silent detour that
13932        // allocated a fresh `String` (`self.versao.clone()` in the body
13933        // would type-check but silently drop the borrow, and every
13934        // downstream consumer that assumed the returned slice outlives
13935        // `&self` — the [`crate::render::require_valid_versao_requirement`]
13936        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
13937        // `.to_string()` carrier's byte-length assumption — would silently
13938        // misbehave if this accessor produced a detached copy). Peer of
13939        // the sibling `child_spec_nome_borrows_from_caixa_storage`
13940        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
13941        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
13942        // pin on the peer per-`:membros` `:versao` axis.
13943        let c = ChildSpec {
13944            caixa: "worker".into(),
13945            versao: "^0.1".into(),
13946            restart: RestartPolicy::Permanent,
13947        };
13948        let req = c.versao_requirement();
13949        let versao_slice = c.versao.as_str();
13950        assert_eq!(
13951            req.as_ptr(),
13952            versao_slice.as_ptr(),
13953            "ChildSpec::versao_requirement must borrow from the .versao \
13954             String's backing storage — a fresh allocation here means the \
13955             accessor no longer names the substrate-primitive typed \
13956             dispatch and every downstream consumer would silently carry \
13957             a detached copy",
13958        );
13959        assert_eq!(
13960            req.len(),
13961            versao_slice.len(),
13962            "ChildSpec::versao_requirement and .versao.as_str() must \
13963             byte-equal in length as well as in address",
13964        );
13965    }
13966
13967    #[test]
13968    fn validate_gates_child_versao_through_lifted_accessor() {
13969        // Bilateral coherence pin: every `:children :versao` that
13970        // [`SupervisorSpec::validate`] accepts is one
13971        // [`crate::render::require_valid_versao_requirement`] accepts on
13972        // the accessor-projected value, and vice versa on the reject side.
13973        // This closes the "the validator reads through the accessor"
13974        // contract structurally — a future silent detour that made the
13975        // accessor return a different byte-string than the validator gates
13976        // against would surface here as a coverage mismatch, not as a
13977        // resolver-time semver-parse rejection at lacre-closure time far
13978        // from the caixa.lisp source. Peer of the sibling
13979        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
13980        // the per-`:children :caixa` axis and the M2
13981        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
13982        // on the peer per-`:upgrade-from :from` axis.
13983        //
13984        // Accept-set sweep: five Cargo-shaped semver requirement values
13985        // the upstream gate admits (caret / tilde / exact / wildcard /
13986        // bare-major).
13987        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
13988            let s = SupervisorSpec {
13989                children: vec![ChildSpec {
13990                    caixa: "worker".into(),
13991                    versao: ok_req.into(),
13992                    restart: RestartPolicy::Permanent,
13993                }],
13994                ..SupervisorSpec::default()
13995            };
13996            s.validate().unwrap_or_else(|e| {
13997                panic!(
13998                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
13999                     (upstream versao-requirement gate accepts it): got {e:?}",
14000                );
14001            });
14002            let c = ChildSpec {
14003                caixa: "worker".into(),
14004                versao: ok_req.into(),
14005                restart: RestartPolicy::Permanent,
14006            };
14007            crate::render::require_valid_versao_requirement(
14008                c.versao_requirement(),
14009                || (),
14010                |_reason| (),
14011            )
14012            .unwrap_or_else(|()| {
14013                panic!(
14014                    "require_valid_versao_requirement must accept the accessor-projected \
14015                     :children :versao {ok_req:?}",
14016                );
14017            });
14018        }
14019        // Reject-set sweep: five requirement-violating shapes the upstream
14020        // gate refuses. The empty string closes the empty-first arm of the
14021        // shared [`crate::render::require_valid_versao_requirement`]
14022        // cascade; the four non-empty arms exercise distinct semver-parse
14023        // failure modes the M3 peer per-`:membros` reject-set already pins
14024        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
14025        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
14026        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
14027        // shared parser routing means the same reject-set must fail
14028        // identically at the M2 supervisor-tree per-`:children` accessor
14029        // arm here. Every rejection at the validator must correspond to a
14030        // rejection when the accessor's projected value is fed back
14031        // through the shared gate.
14032        //
14033        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
14034        // `"not-a-semver"` are intentionally *not* in the reject-set: the
14035        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
14036        // and the identifier-tail arm's grammar admits some non-canonical
14037        // shapes — matching what the M3 peer test suite already documents
14038        // as the shared parser's accept-set edges.)
14039        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
14040            let s = SupervisorSpec {
14041                children: vec![ChildSpec {
14042                    caixa: "worker".into(),
14043                    versao: bad_req.into(),
14044                    restart: RestartPolicy::Permanent,
14045                }],
14046                ..SupervisorSpec::default()
14047            };
14048            let err = s.validate().unwrap_err();
14049            assert!(
14050                matches!(
14051                    err,
14052                    SupervisorError::EmptyChildVersion { .. }
14053                        | SupervisorError::ChildVersaoInvalid { .. }
14054                ),
14055                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
14056                 via the versao-requirement gate: got {err:?}",
14057            );
14058            let c = ChildSpec {
14059                caixa: "worker".into(),
14060                versao: bad_req.into(),
14061                restart: RestartPolicy::Permanent,
14062            };
14063            assert!(
14064                crate::render::require_valid_versao_requirement(
14065                    c.versao_requirement(),
14066                    || (),
14067                    |_reason| (),
14068                )
14069                .is_err(),
14070                "require_valid_versao_requirement must reject the accessor-projected \
14071                 :children :versao {bad_req:?}",
14072            );
14073        }
14074    }
14075
14076    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
14077    //
14078    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
14079    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
14080    // already project the `String`-carry `(caixa, versao)` fields; the
14081    // `Copy`-composite-enum `restart` field is the third and final axis).
14082    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
14083    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
14084    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
14085    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
14086    // strategy scalar accessor — same "one typed dispatch on the substrate
14087    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
14088    // extended onto the M2 supervisor-slot per-`:children` restart-decision
14089    // axis. The pin below covers the accessor's byte-equal projection
14090    // against the raw field access across every variant in the closed
14091    // accept-set (`Permanent`, `Transient`, `Temporary`).
14092
14093    #[test]
14094    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
14095        // The canonical per-`:children` restart-decision-policy-scalar
14096        // pin: [`ChildSpec::restart`] must return the `:children :restart`
14097        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
14098        // typed slot's own [`RestartPolicy`] storage across every variant
14099        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
14100        // Pins against a future silent detour that re-derived the policy
14101        // from a peer axis (an accidental fallback to
14102        // `if is_supervisor_child { Permanent } else { Temporary }` that
14103        // collapsed the child's kind axis into the restart discriminator),
14104        // a variant remap the operator authors on one consumer without the
14105        // other, or a stale-derive detour that substituted
14106        // [`RestartPolicy::default`] when the field held any explicit
14107        // variant (which would silently collapse the distinction between
14108        // "author explicitly declared `:restart Permanent`" and "author
14109        // omitted the slot and inherited the default" the future
14110        // per-cluster restart-decision override slot depends on).
14111        //
14112        // Peer of the sibling per-`:supervisor`
14113        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14114        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
14115        // axis and the M3
14116        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14117        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
14118        // — same "the substrate-primitive accessor must byte-equal the raw
14119        // field access verbatim across every author-declared value"
14120        // discipline extended onto the M2 supervisor-slot per-`:children`
14121        // restart-decision-policy axis, closing the last unlifted axis on
14122        // the per-`:children` [`ChildSpec`] type.
14123        for restart in [
14124            RestartPolicy::Permanent,
14125            RestartPolicy::Transient,
14126            RestartPolicy::Temporary,
14127        ] {
14128            let c = ChildSpec {
14129                caixa: "worker".into(),
14130                versao: "^0.1".into(),
14131                restart,
14132            };
14133            assert_eq!(
14134                c.restart(),
14135                restart,
14136                "ChildSpec::restart must return :children :restart \
14137                 verbatim (got {:?}, expected {restart:?})",
14138                c.restart(),
14139            );
14140            assert_eq!(
14141                c.restart(),
14142                c.restart,
14143                "ChildSpec::restart accessor and .restart field access \
14144                 must byte-equal — the accessor is the substrate-primitive \
14145                 typed dispatch every downstream per-child restart-\
14146                 decision consumer must route through",
14147            );
14148        }
14149    }
14150
14151    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
14152    //
14153    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
14154    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
14155    // distribution-strategy accessor discipline onto the M2 supervisor-slot
14156    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
14157    // scalar axis. The two pins below cover (1) the accessor's byte-equal
14158    // projection against the raw field access across every variant in the
14159    // closed accept-set, and (2) the two-consumer coherence between the
14160    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
14161    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
14162    // carrier's `estrategia:` field — peer of the sibling M3
14163    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14164    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
14165    // pair on the per-`:placement` distribution-strategy axis.
14166
14167    #[test]
14168    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
14169        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
14170        // pin: [`SupervisorSpec::estrategia`] must return the
14171        // `:supervisor :estrategia` field verbatim as a
14172        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
14173        // [`RestartStrategy`] storage across every variant in the closed
14174        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
14175        // `SimpleOneForOne`). Pins against a future silent detour that
14176        // re-derived the strategy from a peer axis (an accidental
14177        // fallback to `if children.is_empty() { SimpleOneForOne } else {
14178        // OneForOne }` collapse that read the children-count axis into
14179        // the strategy discriminator), a variant remap the operator
14180        // authors on one consumer without the other, or a stale-derive
14181        // detour that substituted [`RestartStrategy::default`] when the
14182        // field held any explicit variant (which would silently collapse
14183        // the distinction between "author explicitly declared
14184        // `:estrategia OneForOne`" and "author omitted the slot and
14185        // inherited the default" the future per-cluster strategy override
14186        // slot depends on). Peer of the sibling M3
14187        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14188        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
14189        // axis — same "the substrate-primitive accessor must byte-equal
14190        // the raw field access verbatim across every author-declared
14191        // value" discipline extended onto the M2 supervisor-slot
14192        // per-`:supervisor` sibling-restart-strategy axis.
14193        for &estrategia in RestartStrategy::ALL {
14194            // `SimpleOneForOne` requires `children.is_empty()`; the peer
14195            // three strategies require a non-empty static children list.
14196            // Build each shape coherently so the pin's fixture would
14197            // itself pass [`SupervisorSpec::validate`] once fed through
14198            // the sibling coherence pin below — the byte-equal projection
14199            // asserted here is a strictly weaker property (a `Copy` field
14200            // read) that does not depend on `validate` running, but
14201            // keeping the fixture validate-clean means a future extension
14202            // of the pin to exercise `validate` end-to-end does not have
14203            // to re-author the children shape.
14204            //
14205            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
14206            // shape partition through the [`gen_platform::IsVariant`]
14207            // derive-generated
14208            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
14209            // than the raw `matches!(estrategia, RestartStrategy::
14210            // SimpleOneForOne)` open-coded pattern-match — same closed-
14211            // set-typed-enum arm-discriminator dispatch discipline the
14212            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
14213            // convergence (915a934) extended onto its two paired positive
14214            // / negated `matches!` sites and the peer
14215            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
14216            // predicate convergence (766ec63) extended onto the M3 mesh-
14217            // slot per-`:placement` distribution-strategy discriminator
14218            // axis. See the sibling `round_trip_all_strategies` and the
14219            // peer `manifest::tests::
14220            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
14221            // fixture for the two peer sites the same lift closes on.
14222            let children = if estrategia.is_simple_one_for_one() {
14223                Vec::new()
14224            } else {
14225                vec![ChildSpec {
14226                    caixa: "worker".into(),
14227                    versao: "^0.1".into(),
14228                    restart: RestartPolicy::Permanent,
14229                }]
14230            };
14231            let s = SupervisorSpec {
14232                estrategia,
14233                children,
14234                ..SupervisorSpec::default()
14235            };
14236            assert_eq!(
14237                s.estrategia(),
14238                estrategia,
14239                "SupervisorSpec::estrategia must return :supervisor :estrategia \
14240                 verbatim (got {:?}, expected {estrategia:?})",
14241                s.estrategia(),
14242            );
14243            assert_eq!(
14244                s.estrategia(),
14245                s.estrategia,
14246                "SupervisorSpec::estrategia accessor and .estrategia field \
14247                 access must byte-equal — the accessor is the substrate-\
14248                 primitive typed dispatch every downstream sibling-restart-\
14249                 strategy consumer must route through",
14250            );
14251        }
14252    }
14253
14254    #[test]
14255    fn validate_reads_through_lifted_estrategia_accessor() {
14256        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
14257        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
14258        // dispatch (which reads through [`SupervisorSpec::estrategia`]
14259        // to fan across the strategy-arm shape-gate cascades) and the
14260        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
14261        // error carrier's `estrategia:` field (which reads through
14262        // [`SupervisorSpec::estrategia`] to name the strategy the empty
14263        // `:children` list was declared against) must both key off the
14264        // lifted accessor, so any future rebrand on the typed slot's
14265        // reader shape lands at exactly one place. Pins the two-site
14266        // coherence by exercising the `NoChildren` error surface end-to-
14267        // end across every non-`SimpleOneForOne` variant and asserting
14268        // the surfaced `estrategia:` field byte-equals the accessor's
14269        // return. Peer of the sibling M3
14270        // `validate_placement_reads_through_lifted_estrategia_accessor`
14271        // (921fe1b) three-consumer coherence pin on the per-`:placement`
14272        // distribution-strategy axis.
14273        for estrategia in [
14274            RestartStrategy::OneForOne,
14275            RestartStrategy::OneForAll,
14276            RestartStrategy::RestForOne,
14277        ] {
14278            let s = SupervisorSpec {
14279                estrategia,
14280                children: Vec::new(),
14281                ..SupervisorSpec::default()
14282            };
14283            let err = s.validate().unwrap_err();
14284            match err {
14285                SupervisorError::NoChildren { estrategia: e } => {
14286                    assert_eq!(
14287                        e,
14288                        s.estrategia(),
14289                        "NoChildren.estrategia must byte-equal \
14290                         SupervisorSpec::estrategia() — the empty-`:children` \
14291                         refusal reads through the lifted accessor",
14292                    );
14293                    assert_eq!(
14294                        e, estrategia,
14295                        "NoChildren.estrategia must carry the author-declared \
14296                         :supervisor :estrategia variant verbatim (got {e:?}, \
14297                         expected {estrategia:?})",
14298                    );
14299                }
14300                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
14301            }
14302        }
14303    }
14304
14305    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
14306    //
14307    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
14308    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
14309    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
14310    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
14311    // The two pins below cover (1) the accessor's byte-equal projection
14312    // against the raw field access across every representative value in
14313    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
14314    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
14315    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
14316    // zero-floor / cap composition — the validate gate and the accessor
14317    // must route through the same substrate-primitive typed dispatch, so
14318    // any future silent detour that had the accessor perform a
14319    // bounds-collapsing clamp would fail here at caixa-core build time.
14320    // Peer of the sibling M3
14321    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14322    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
14323
14324    #[test]
14325    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
14326        // The canonical per-`:supervisor` restart-budget-count scalar pin:
14327        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
14328        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
14329        // typed slot's own `u32` storage, byte-equal to the raw field
14330        // access across every representative value in the accept-set —
14331        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
14332        // accept-set the surrounding [`SupervisorSpec::validate`] gate
14333        // carves out on the sibling `ZeroMaxRestarts` refusal),
14334        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
14335        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
14336        // (a past-the-guard sentinel that pins the accessor doesn't
14337        // perform a silent bounds-collapse into `1` on the zero arm —
14338        // validate rejects zero but the accessor must ship the raw slot
14339        // verbatim so a validate-time gate regression surfaces at the
14340        // emit boundary rather than being silently absorbed), `u32::MAX`
14341        // (a past-the-guard sentinel that pins the accessor doesn't
14342        // perform a silent bounds-collapse through
14343        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
14344        //
14345        // Peer of the sibling M3
14346        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14347        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
14348        // required-scalar axis — same "the substrate-primitive accessor
14349        // must byte-equal the raw field access verbatim across every
14350        // value in the `u32` accept-set" discipline extended onto the M2
14351        // supervisor-slot per-`:supervisor` restart-budget-count axis.
14352        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
14353            let s = SupervisorSpec {
14354                max_restarts,
14355                ..SupervisorSpec::default()
14356            };
14357            assert_eq!(
14358                s.max_restarts(),
14359                max_restarts,
14360                "SupervisorSpec::max_restarts must return :supervisor \
14361                 :max-restarts verbatim (got {}, expected {max_restarts})",
14362                s.max_restarts(),
14363            );
14364            assert_eq!(
14365                s.max_restarts(),
14366                s.max_restarts,
14367                "SupervisorSpec::max_restarts accessor and .max_restarts \
14368                 field access must byte-equal — the accessor is the \
14369                 substrate-primitive typed dispatch every downstream \
14370                 restart-budget-count consumer must route through",
14371            );
14372        }
14373    }
14374
14375    #[test]
14376    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
14377        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
14378        // zero-floor + upper-cap bracket must key off
14379        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
14380        // field access. Structurally: a `SupervisorSpec { max_restarts:
14381        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
14382        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
14383        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
14384        // (with the offending count carried verbatim from the accessor
14385        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
14386        // lower boundary of the accept-set) plus a `SupervisorSpec {
14387        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
14388        // boundary) must pass validate. The four together jointly pin the
14389        // accessor + validate-gate composition: any future silent detour
14390        // that had the accessor return a fresh `1` on the zero arm (a
14391        // `.max_restarts().max(1)` collapse) would silently absorb the
14392        // `ZeroMaxRestarts` refusal at the accessor boundary and the
14393        // validate gate would accept a struct-literal `SupervisorSpec {
14394        // max_restarts: 0, .. }` — the composition pin catches that at
14395        // caixa-core build time.
14396        //
14397        // Peer of the sibling M3
14398        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
14399        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
14400        // composition axis — same "the validate / shape-gate predicate
14401        // must route through the substrate-primitive typed dispatch"
14402        // discipline extended onto the peer M2 supervisor-slot
14403        // required-`u32` composition axis.
14404        let child = ChildSpec {
14405            caixa: "worker".into(),
14406            versao: "^0.1".into(),
14407            restart: RestartPolicy::Permanent,
14408        };
14409        // Zero-floor arm.
14410        let s = SupervisorSpec {
14411            max_restarts: 0,
14412            children: vec![child.clone()],
14413            ..SupervisorSpec::default()
14414        };
14415        assert_eq!(
14416            s.validate().unwrap_err(),
14417            SupervisorError::ZeroMaxRestarts,
14418            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
14419             — the accessor and the validate gate must route through the \
14420             same substrate-primitive typed dispatch on the zero-floor arm",
14421        );
14422        // Cap arm — the surfaced `max_restarts:` field must byte-equal
14423        // the accessor's return so a future rebrand on the accessor
14424        // lands in the diagnostic without a coordinated rewrite.
14425        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14426        let s = SupervisorSpec {
14427            max_restarts: over_cap,
14428            children: vec![child.clone()],
14429            ..SupervisorSpec::default()
14430        };
14431        match s.validate().unwrap_err() {
14432            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
14433                assert_eq!(
14434                    max_restarts,
14435                    s.max_restarts(),
14436                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
14437                     SupervisorSpec::max_restarts() — the cap-arm refusal \
14438                     reads through the lifted accessor",
14439                );
14440                assert_eq!(
14441                    max_restarts, over_cap,
14442                    "MaxRestartsExceedsCap.max_restarts must carry the \
14443                     author-declared :supervisor :max-restarts value \
14444                     verbatim (got {max_restarts}, expected {over_cap})",
14445                );
14446            }
14447            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
14448        }
14449        // Lower + upper accept-set boundaries.
14450        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
14451            let s = SupervisorSpec {
14452                max_restarts,
14453                children: vec![child.clone()],
14454                ..SupervisorSpec::default()
14455            };
14456            assert!(
14457                s.validate().is_ok(),
14458                "validate must accept max_restarts == {max_restarts} \
14459                 (an accept-set boundary of \
14460                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
14461            );
14462        }
14463    }
14464
14465    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
14466    //
14467    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
14468    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
14469    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
14470    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
14471    // supervisor-slot per-`:supervisor` restart-intensity-denominator
14472    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
14473    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
14474    // per-`:supervisor` scalar-value axis. The three pins below cover
14475    // (1) the accessor's byte-equal projection against the raw field
14476    // access across every representative value in the `Option<Duration>`
14477    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
14478    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
14479    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
14480    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
14481    // `if let Some(w) = self.restart_window() { … }` bracket-arm
14482    // composition — the validate gate and the accessor must route through
14483    // the same substrate-primitive typed dispatch, so any future silent
14484    // detour that had the accessor perform a bounds-collapsing clamp
14485    // would fail here at caixa-core build time, and (3) the accessor's
14486    // by-copy idempotence pin — the returned `Option<Duration>` must
14487    // outlive `&self` and two successive calls must return byte-equal
14488    // values. Peer of the sibling M2
14489    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14490    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
14491    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14492    // (7073d0f) pin on the per-`:politicas :timeout` axis.
14493
14494    #[test]
14495    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
14496        // The canonical per-`:supervisor` restart-intensity-denominator
14497        // scalar pin: [`SupervisorSpec::restart_window`] must return the
14498        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
14499        // `Option<Duration>`, `Copy`-projected from the typed slot's own
14500        // `Option<Duration>` storage, byte-equal to the raw field access
14501        // across every representative value in the accept-set — `None`
14502        // (the "never reset — every restart across the supervisor's
14503        // lifetime counts against the sibling `:max-restarts` budget"
14504        // sentinel the field's own docstring names and the peer
14505        // `validate_accepts_none_restart_window` pin locks in on the
14506        // [`SupervisorSpec::validate`] entry-side),
14507        // `Some(Duration::from_millis(1))` (the structural minimum a
14508        // validated `:restart-window` may carry, the integer-millisecond
14509        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
14510        // everything sub-ms; `Duration::ZERO` is separately rejected by
14511        // [`SupervisorError::RestartWindowZero`]),
14512        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
14513        // surrounding [`SupervisorSpec::validate`] gate carves out on the
14514        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
14515        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
14516        // accessor doesn't perform a silent bounds-collapse into `None` on
14517        // the zero-Duration arm — validate rejects zero but the accessor
14518        // must ship the raw slot verbatim so a validate-time gate
14519        // regression surfaces at the emit boundary rather than being
14520        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
14521        // sentinel that pins the accessor doesn't perform a silent
14522        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
14523        // return path).
14524        //
14525        // Peer of the sibling M2
14526        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14527        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
14528        // sibling M3
14529        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14530        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
14531        // substrate-primitive accessor must byte-equal the raw field
14532        // access verbatim across every value in the `Option<Duration>`
14533        // accept-set" discipline extended onto the M2 supervisor-slot
14534        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
14535        // silent detour that re-derived the restart-window from a peer
14536        // axis (an accidental `.max_restarts.into()` collapse that read
14537        // the restart-budget-count as a duration — the two axes serve
14538        // different halves of the `MaxIntensity / Period` restart-
14539        // intensity ratio, and confusing them silently inverts the
14540        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
14541        // "zero means never reset" collapse (the canonical
14542        // `Option<Duration>` → `Duration` collapse footgun the
14543        // [`SupervisorError::RestartWindowZero`] validate arm guards on
14544        // the peer zero-floor axis; a zero period either trips on the
14545        // first failure or never trips depending on operator
14546        // interpretation, neither of which is the author's "never reset"
14547        // intent that `None` expresses structurally), or a per-arm
14548        // variant swap that landed on one consumer without the other.
14549        for restart_window in [
14550            None,
14551            Some(Duration::from_millis(1)),
14552            Some(SUPERVISOR_RESTART_WINDOW_MAX),
14553            Some(Duration::ZERO),
14554            Some(Duration::MAX),
14555        ] {
14556            let s = SupervisorSpec {
14557                restart_window,
14558                ..SupervisorSpec::default()
14559            };
14560            assert_eq!(
14561                s.restart_window(),
14562                restart_window,
14563                "SupervisorSpec::restart_window must return :supervisor \
14564                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
14565                s.restart_window(),
14566            );
14567            assert_eq!(
14568                s.restart_window(),
14569                s.restart_window,
14570                "SupervisorSpec::restart_window accessor and \
14571                 .restart_window field access must byte-equal — the \
14572                 accessor is the substrate-primitive typed dispatch every \
14573                 downstream restart-intensity-denominator consumer must \
14574                 route through",
14575            );
14576        }
14577    }
14578
14579    #[test]
14580    fn validate_restart_window_bracket_arm_routes_through_accessor() {
14581        // Composition pin: [`SupervisorSpec::validate`]'s
14582        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
14583        // zero-floor + integer-millisecond canonical-form + upper-cap
14584        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
14585        // the raw `.restart_window` field access. Structurally: a
14586        // `SupervisorSpec { restart_window: None, .. }` must pass the
14587        // arm gate structurally (the `if let Some(_)` shape returns
14588        // early on the `None` arm — the accessor and the validate gate
14589        // must agree on `None → skip the bracket cascade` so an authored
14590        // `:restart-window ()` structurally routes through the "never
14591        // reset" sentinel path), a `SupervisorSpec { restart_window:
14592        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
14593        // refusal exactly, a `SupervisorSpec { restart_window:
14594        // Some(Duration::from_micros(1500)), .. }` must surface the
14595        // `RestartWindowNotCanonical` refusal exactly (with the offending
14596        // duration carried verbatim from the accessor return), a
14597        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
14598        // + Duration::from_millis(1)), .. }` must surface the
14599        // `RestartWindowExceedsCap` refusal exactly (with the offending
14600        // duration carried verbatim from the accessor return), and a
14601        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
14602        // .. }` (the lower boundary of the accept-set) plus a
14603        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
14604        // .. }` (the upper boundary) must pass validate. The six together
14605        // jointly pin the accessor + validate-gate composition: any future
14606        // silent detour that had the accessor return a fresh `None` on any
14607        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
14608        // collapse) would silently absorb the `RestartWindowZero` refusal
14609        // at the accessor boundary and the validate gate would accept a
14610        // struct-literal `SupervisorSpec { restart_window:
14611        // Some(Duration::ZERO), .. }` — the composition pin catches that
14612        // at caixa-core build time.
14613        //
14614        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
14615        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
14616        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
14617        // accessor-composition pin on the per-`:politicas :timeout` axis —
14618        // same "the validate / shape-gate predicate must route through
14619        // the substrate-primitive typed dispatch" discipline extended
14620        // onto the peer M2 supervisor-slot optional-`Duration` axis.
14621        let child = ChildSpec {
14622            caixa: "worker".into(),
14623            versao: "^0.1".into(),
14624            restart: RestartPolicy::Permanent,
14625        };
14626        // None arm — must not surface any :restart-window-shaped refusal;
14627        // the `if let Some(_)` bracket returns early on `None` structurally.
14628        let s = SupervisorSpec {
14629            restart_window: None,
14630            children: vec![child.clone()],
14631            ..SupervisorSpec::default()
14632        };
14633        assert!(
14634            s.validate().is_ok(),
14635            "validate must accept restart_window: None (the never-reset \
14636             sentinel) — the `if let Some(_)` bracket returns early on \
14637             the None arm and the accessor must agree",
14638        );
14639        // Zero-floor arm.
14640        let s = SupervisorSpec {
14641            restart_window: Some(Duration::ZERO),
14642            children: vec![child.clone()],
14643            ..SupervisorSpec::default()
14644        };
14645        assert_eq!(
14646            s.validate().unwrap_err(),
14647            SupervisorError::RestartWindowZero,
14648            "validate must reject restart_window == Some(Duration::ZERO) \
14649             with RestartWindowZero — the accessor and the validate gate \
14650             must route through the same substrate-primitive typed \
14651             dispatch on the zero-floor arm",
14652        );
14653        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
14654        // byte-equal the accessor's return so a future rebrand on the
14655        // accessor lands in the diagnostic without a coordinated rewrite.
14656        let sub_ms = Duration::from_micros(1500);
14657        let s = SupervisorSpec {
14658            restart_window: Some(sub_ms),
14659            children: vec![child.clone()],
14660            ..SupervisorSpec::default()
14661        };
14662        match s.validate().unwrap_err() {
14663            SupervisorError::RestartWindowNotCanonical { window } => {
14664                assert_eq!(
14665                    Some(window),
14666                    s.restart_window(),
14667                    "RestartWindowNotCanonical.window must byte-equal \
14668                     SupervisorSpec::restart_window().unwrap() — the \
14669                     non-canonical-arm refusal reads through the lifted \
14670                     accessor",
14671                );
14672                assert_eq!(
14673                    window, sub_ms,
14674                    "RestartWindowNotCanonical.window must carry the \
14675                     author-declared :supervisor :restart-window value \
14676                     verbatim (got {window:?}, expected {sub_ms:?})",
14677                );
14678            }
14679            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
14680        }
14681        // Cap arm — the surfaced `window:` field must byte-equal the
14682        // accessor's return.
14683        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14684        let s = SupervisorSpec {
14685            restart_window: Some(over_cap),
14686            children: vec![child.clone()],
14687            ..SupervisorSpec::default()
14688        };
14689        match s.validate().unwrap_err() {
14690            SupervisorError::RestartWindowExceedsCap { window } => {
14691                assert_eq!(
14692                    Some(window),
14693                    s.restart_window(),
14694                    "RestartWindowExceedsCap.window must byte-equal \
14695                     SupervisorSpec::restart_window().unwrap() — the \
14696                     cap-arm refusal reads through the lifted accessor",
14697                );
14698                assert_eq!(
14699                    window, over_cap,
14700                    "RestartWindowExceedsCap.window must carry the \
14701                     author-declared :supervisor :restart-window value \
14702                     verbatim (got {window:?}, expected {over_cap:?})",
14703                );
14704            }
14705            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
14706        }
14707        // Lower + upper accept-set boundaries.
14708        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
14709            let s = SupervisorSpec {
14710                restart_window: Some(restart_window),
14711                children: vec![child.clone()],
14712                ..SupervisorSpec::default()
14713            };
14714            assert!(
14715                s.validate().is_ok(),
14716                "validate must accept restart_window == Some({restart_window:?}) \
14717                 (an accept-set boundary of \
14718                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
14719            );
14720        }
14721    }
14722
14723    #[test]
14724    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
14725        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
14726        // `Option<Duration>` by copy — `Duration` is `Copy` (so
14727        // `Option<Duration>` is `Copy`) and the accessor must return by
14728        // value, not by reference. Peer of the sibling M2
14729        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
14730        // per-`:limits :wall-clock` axis and the sibling M3
14731        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
14732        // per-`:politicas :timeout` axis, extended onto the peer M2
14733        // supervisor-slot `Option<Duration>` copy-invariant shape — the
14734        // accessor's returned `Option<Duration>` must outlive `&self`
14735        // (multiple calls must return equal values from a dropped-`&self`
14736        // copy, since the returned Option carries no borrow), and calling
14737        // the accessor twice on the same SupervisorSpec must yield the
14738        // same `Option<Duration>` verbatim (idempotent, no side effects
14739        // on `&self`).
14740        //
14741        // Pins against a future silent detour that returned
14742        // `Option<&Duration>` (which would type-check but silently break
14743        // every downstream caller — the future wasm-operator's
14744        // per-supervisor restart-intensity counter consumes `Duration` by
14745        // value and `&Duration` would fold to a detached copy at the call
14746        // site), an accidental `Option::as_ref()` projection
14747        // (`self.restart_window.as_ref()` would also type-check but
14748        // return `Option<&Duration>`), or a one-arm-only accessor that
14749        // reads `Some(*w)` in the Some arm but reads a fresh
14750        // `Default::default()` (which would collapse to `Duration::ZERO`,
14751        // not `None`) in the None arm — a footgun the
14752        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
14753        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
14754        // requires `Period > 0` and `None` structurally expresses "never
14755        // reset" instead.
14756        for restart_window in [
14757            None,
14758            Some(Duration::from_millis(1)),
14759            Some(Duration::from_secs(60)),
14760            Some(SUPERVISOR_RESTART_WINDOW_MAX),
14761        ] {
14762            let s = SupervisorSpec {
14763                restart_window,
14764                ..SupervisorSpec::default()
14765            };
14766            let first = s.restart_window();
14767            let second = s.restart_window();
14768            assert_eq!(
14769                first, second,
14770                "SupervisorSpec::restart_window must be idempotent — two \
14771                 successive calls on the same &self must return the \
14772                 same Option<Duration>",
14773            );
14774            assert_eq!(
14775                first, restart_window,
14776                "SupervisorSpec::restart_window must return :supervisor \
14777                 :restart-window verbatim by copy — got {first:?}, \
14778                 expected {restart_window:?}",
14779            );
14780        }
14781    }
14782
14783    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
14784    //
14785    // The [`SupervisorSpec::children`] accessor lift is the seed of the
14786    // slice-return (`&[T]`) accessor discipline on the substrate — the four
14787    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
14788    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
14789    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
14790    // access at the time of this seed, and inherit this pin family's
14791    // discipline as future compounding runs migrate their consumers. The
14792    // three pins below cover (1) the accessor's byte-equal projection
14793    // against the raw field access across the empty / singleton / cohort
14794    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
14795    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
14796    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
14797    // consumer routing through the accessor on both arms, and (3) the
14798    // per-child validate loop's traversal reading the same slice-view the
14799    // accessor projects. Peer of the sibling M2
14800    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
14801    // two-consumer coherence pin on the per-`:supervisor`
14802    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
14803    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
14804
14805    #[test]
14806    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
14807        // The canonical per-`:supervisor` static-child-list scalar-shape
14808        // pin: [`SupervisorSpec::children`] must return the `:supervisor
14809        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
14810        // slice-view over the same backing buffer the raw
14811        // `self.children.as_slice()` field access borrows from, byte-
14812        // equal across every representative fixture in the accept-set —
14813        // the empty slice (the `SimpleOneForOne`-arm sentinel),
14814        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
14815        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
14816        // with the peer three restart-policy variants in play).
14817        //
14818        // Pins against a future silent detour that returned
14819        // `&Vec<ChildSpec>` (which would type-check but leak the
14820        // storage-side `Vec`'s grow/push/reserve surface no consumer of
14821        // the typed view reaches for), a fresh-allocated
14822        // `Vec<ChildSpec>` copy (which would type-check via a coercion
14823        // but silently break every downstream caller that relied on the
14824        // slice sharing the backing buffer's identity), or an
14825        // out-of-order or length-drifted projection (which would silently
14826        // split the per-child validate loop's traversal input from the
14827        // paired partition-dispatch `.is_empty()` probe's input).
14828        //
14829        // Peer of the sibling
14830        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14831        // (eafb619) `Copy`-composite-enum byte-equal pin on the
14832        // per-`:supervisor` sibling-restart-strategy axis, extended onto
14833        // the per-`:supervisor` static-child-list `Vec`-carry axis.
14834        let fixtures: Vec<Vec<ChildSpec>> = vec![
14835            Vec::new(),
14836            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
14837            vec![
14838                child("worker", "^0.1", RestartPolicy::Permanent),
14839                child("cache-server", "^0.1", RestartPolicy::Transient),
14840            ],
14841            vec![
14842                child("worker", "^0.1", RestartPolicy::Permanent),
14843                child("cache-server", "^0.1", RestartPolicy::Transient),
14844                child("scratch-job", "^0.1", RestartPolicy::Temporary),
14845            ],
14846        ];
14847        for children in fixtures {
14848            let s = SupervisorSpec {
14849                children: children.clone(),
14850                ..SupervisorSpec::default()
14851            };
14852            assert_eq!(
14853                s.children(),
14854                children.as_slice(),
14855                "SupervisorSpec::children must return :supervisor \
14856                 :children verbatim (got {:?}, expected {:?})",
14857                s.children(),
14858                children.as_slice(),
14859            );
14860            assert_eq!(
14861                s.children(),
14862                s.children.as_slice(),
14863                "SupervisorSpec::children accessor and \
14864                 .children.as_slice() field access must byte-equal — \
14865                 the accessor is the substrate-primitive typed \
14866                 dispatch every downstream static-child-list consumer \
14867                 must route through",
14868            );
14869            assert_eq!(
14870                s.children().len(),
14871                s.children.len(),
14872                "SupervisorSpec::children().len() must byte-equal \
14873                 self.children.len() — a length-drift would silently \
14874                 split the paired partition-dispatch `.is_empty()` \
14875                 probe input from the per-child validate loop's \
14876                 traversal input",
14877            );
14878        }
14879    }
14880
14881    #[test]
14882    fn validate_reads_through_lifted_children_accessor() {
14883        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
14884        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
14885        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
14886        // when the accessor projects a non-empty slice under a
14887        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
14888        // `self.children().is_empty()` refusal probe (which must trip
14889        // [`SupervisorError::NoChildren`] when the accessor projects the
14890        // empty slice under any peer estrategia), and the per-child
14891        // validate loop's `for child in self.children()` traversal
14892        // (which must reach every entry in the same order the accessor
14893        // projects) must all key off the lifted accessor, so any future
14894        // rebrand on the typed slot's reader shape lands at exactly one
14895        // place. Pins the three-site coherence by exercising each
14896        // production consumer end-to-end: (1) the
14897        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
14898        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
14899        // refusal under the empty slice + non-`SimpleOneForOne`
14900        // estrategia across every peer variant, and (3) the per-child
14901        // duplicate-detection surface fires on the second entry of a
14902        // two-child cohort that shares a `:caixa` name (which requires
14903        // the loop to reach both entries — a first-entry-only projection
14904        // would silently pass since the dedup HashSet has room for the
14905        // first insert).
14906        //
14907        // Peer of the sibling M2
14908        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
14909        // two-consumer coherence pin on the per-`:supervisor`
14910        // sibling-restart-strategy axis, extended onto the
14911        // per-`:supervisor` static-child-list `Vec`-carry axis.
14912
14913        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
14914        // `SimpleOneForOne` estrategia must trip
14915        // `SimpleOneForOneWithStaticChildren`.
14916        let s = SupervisorSpec {
14917            estrategia: RestartStrategy::SimpleOneForOne,
14918            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
14919            ..SupervisorSpec::default()
14920        };
14921        assert_eq!(
14922            s.validate().unwrap_err(),
14923            SupervisorError::SimpleOneForOneWithStaticChildren,
14924            "SimpleOneForOne + non-empty children must trip \
14925             SimpleOneForOneWithStaticChildren — the accessor projects \
14926             a non-empty slice, and the SimpleOneForOne-arm refusal \
14927             probe reads through the lifted accessor",
14928        );
14929        assert!(
14930            !s.children().is_empty(),
14931            "the SimpleOneForOne-arm refusal input must be a non-empty \
14932             slice per the accessor's projection",
14933        );
14934
14935        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
14936        // under any peer estrategia must trip `NoChildren`.
14937        for estrategia in [
14938            RestartStrategy::OneForOne,
14939            RestartStrategy::OneForAll,
14940            RestartStrategy::RestForOne,
14941        ] {
14942            let s = SupervisorSpec {
14943                estrategia,
14944                children: Vec::new(),
14945                ..SupervisorSpec::default()
14946            };
14947            match s.validate().unwrap_err() {
14948                SupervisorError::NoChildren { estrategia: e } => {
14949                    assert_eq!(
14950                        e, estrategia,
14951                        "NoChildren.estrategia must carry the author-\
14952                         declared :supervisor :estrategia variant \
14953                         verbatim (got {e:?}, expected {estrategia:?})",
14954                    );
14955                }
14956                other => panic!(
14957                    "expected NoChildren, got {other:?} for \
14958                     estrategia={estrategia:?}"
14959                ),
14960            }
14961            assert!(
14962                s.children().is_empty(),
14963                "the non-SimpleOneForOne-arm refusal input must be the \
14964                 empty slice per the accessor's projection",
14965            );
14966        }
14967
14968        // (3) Per-child validate loop: a two-child cohort that shares a
14969        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
14970        // reach both entries through the accessor.
14971        let s = SupervisorSpec {
14972            estrategia: RestartStrategy::OneForOne,
14973            children: vec![
14974                child("worker", "^0.1", RestartPolicy::Permanent),
14975                child("worker", "^0.2", RestartPolicy::Transient),
14976            ],
14977            ..SupervisorSpec::default()
14978        };
14979        match s.validate().unwrap_err() {
14980            SupervisorError::DuplicateChildCaixa { caixa } => {
14981                assert_eq!(
14982                    caixa, "worker",
14983                    "DuplicateChildCaixa.caixa must carry the shared \
14984                     child `:caixa` name verbatim",
14985                );
14986            }
14987            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
14988        }
14989        assert_eq!(
14990            s.children().len(),
14991            2,
14992            "the per-child validate loop's traversal input must be a \
14993             two-element slice per the accessor's projection",
14994        );
14995    }
14996
14997    // Shared helper for the M2 per-`:children` per-slot-gate ≡
14998    // `validate` equivalence pins: builds an `OneForOne`-estrategia
14999    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
15000    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
15001    // bracket all pass cleanly so the sole failing surface is the
15002    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
15003    // pins the two-altitude equivalence on the paired probe.
15004    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
15005        let s = SupervisorSpec {
15006            estrategia: RestartStrategy::OneForOne,
15007            children,
15008            ..SupervisorSpec::default()
15009        };
15010        let via_gate = s.validate_children().unwrap_err();
15011        let via_validate = s.validate().unwrap_err();
15012        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
15013        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
15014        assert_eq!(
15015            via_gate, via_validate,
15016            "per-slot gate ≡ validate() must discriminate the same \
15017             refusal shape",
15018        );
15019    }
15020
15021    #[test]
15022    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
15023        // Fail-before-pass-after equivalence pin on the M2
15024        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
15025        // convergence — sibling of the M3 mesh-slot
15026        // `validate_membros_*` / `validate_contratos_*` /
15027        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
15028        // peer per-entry axes. Sweeps four of the five refusal shapes
15029        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
15030        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
15031        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
15032        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
15033        // duplicate-`:caixa` fan-out. Companion pin
15034        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
15035        // covers `ChildVersaoInvalid` (whose parser-owned reason string
15036        // needs pattern-matching, not equality) and the clean-pass
15037        // canonical fixture; together the two pins guarantee the
15038        // per-slot gate and `validate` discriminate the same set on
15039        // every per-child-covered input.
15040        assert_validate_children_matches_gate(
15041            vec![child("", "^0.1", RestartPolicy::Permanent)],
15042            &SupervisorError::EmptyChildName,
15043        );
15044        assert_validate_children_matches_gate(
15045            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
15046            &SupervisorError::ChildCaixaInvalid {
15047                caixa: "Worker".into(),
15048                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
15049            },
15050        );
15051        assert_validate_children_matches_gate(
15052            vec![child("worker", "", RestartPolicy::Permanent)],
15053            &SupervisorError::EmptyChildVersion {
15054                caixa: "worker".into(),
15055            },
15056        );
15057        assert_validate_children_matches_gate(
15058            vec![
15059                child("worker", "^0.1", RestartPolicy::Permanent),
15060                child("worker", "^0.2", RestartPolicy::Transient),
15061            ],
15062            &SupervisorError::DuplicateChildCaixa {
15063                caixa: "worker".into(),
15064            },
15065        );
15066    }
15067
15068    #[test]
15069    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
15070        // Second half of the two-altitude equivalence pin — covers the
15071        // one refusal shape whose reason string is parser-owned
15072        // (`ChildVersaoInvalid`, whose reason comes from the shared
15073        // [`crate::version::parse_requirement`] impl and may drift) and
15074        // the clean-pass canonical fixture. Sibling pin
15075        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
15076        // covers the four equality-comparable refusal shapes.
15077        let s_bad_versao = SupervisorSpec {
15078            estrategia: RestartStrategy::OneForOne,
15079            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
15080            ..SupervisorSpec::default()
15081        };
15082        let via_gate = s_bad_versao.validate_children().unwrap_err();
15083        let via_validate = s_bad_versao.validate().unwrap_err();
15084        match (&via_gate, &via_validate) {
15085            (
15086                SupervisorError::ChildVersaoInvalid {
15087                    caixa: cg,
15088                    versao: vg,
15089                    ..
15090                },
15091                SupervisorError::ChildVersaoInvalid {
15092                    caixa: cv,
15093                    versao: vv,
15094                    ..
15095                },
15096            ) => {
15097                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
15098                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
15099                assert_eq!(cv, "worker", "validate() :caixa carrier");
15100                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
15101            }
15102            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
15103        }
15104        assert_eq!(
15105            via_gate, via_validate,
15106            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
15107        );
15108
15109        let s_ok = SupervisorSpec {
15110            estrategia: RestartStrategy::OneForOne,
15111            children: vec![
15112                child("worker-a", "^0.1", RestartPolicy::Permanent),
15113                child("worker-b", "~0.2.3", RestartPolicy::Transient),
15114                child("collector", "*", RestartPolicy::Temporary),
15115            ],
15116            ..SupervisorSpec::default()
15117        };
15118        s_ok.validate_children()
15119            .expect("per-slot gate must accept the clean-pass fixture");
15120        s_ok.validate()
15121            .expect("validate() must accept the clean-pass fixture");
15122    }
15123
15124    #[test]
15125    fn validate_children_is_self_contained_on_children_slot() {
15126        // Self-containment pin: [`SupervisorSpec::validate_children`]
15127        // resolves the per-child cascade against `&self` alone, without
15128        // depending on the peer `:estrategia`/`:max-restarts`/
15129        // `:restart-window` gates having run first — same posture the M3
15130        // peer per-slot gates carry (`validate_membros`,
15131        // `validate_contratos`, `validate_entrada`, `validate_placement`,
15132        // routing through their own oracles rather than borrowing state
15133        // threaded down from `validate`). A future consumer that reaches
15134        // the per-slot gate directly on a spec whose peer slots would
15135        // fail `validate` still surfaces the per-child refusal, not the
15136        // peer refusal.
15137        //
15138        // Construct a spec whose `:max-restarts` is `0` (which would
15139        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
15140        // the partition-dispatch) and whose `:children` carries a
15141        // `DuplicateChildCaixa` shape: the per-slot gate called directly
15142        // must surface `DuplicateChildCaixa`, proving it does not depend
15143        // on the peer `:max-restarts` gate running first.
15144        let s = SupervisorSpec {
15145            estrategia: RestartStrategy::OneForOne,
15146            max_restarts: 0,
15147            restart_window: Some(Duration::from_secs(60)),
15148            children: vec![
15149                child("worker", "^0.1", RestartPolicy::Permanent),
15150                child("worker", "^0.2", RestartPolicy::Transient),
15151            ],
15152        };
15153        assert_eq!(
15154            s.validate_children().unwrap_err(),
15155            SupervisorError::DuplicateChildCaixa {
15156                caixa: "worker".into(),
15157            },
15158            "per-slot gate must resolve per-child refusal directly against \
15159             `&self` — a dependency on the peer `:max-restarts` gate \
15160             running first would surface ZeroMaxRestarts here instead",
15161        );
15162        // The peer gate is still the surface `validate` reaches — pin
15163        // the ordering to establish that `validate_children` truly runs
15164        // last in `validate`'s dispatch, so a direct call bypasses the
15165        // peer gates on any spec whose per-child cascade would fail.
15166        assert_eq!(
15167            s.validate().unwrap_err(),
15168            SupervisorError::ZeroMaxRestarts,
15169            "validate() must surface the peer `:max-restarts` gate before \
15170             reaching the per-child cascade — this pins the dispatch \
15171             ordering the per-slot gate's self-containment complements",
15172        );
15173    }
15174
15175    #[test]
15176    fn child_spec_restart_accessor_is_const_fn() {
15177        // The [`ChildSpec::restart`] per-`:children` restart-decision-
15178        // policy `Copy`-return scalar accessor is declared
15179        // `#[must_use] pub const fn` — matching the sibling M2
15180        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
15181        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
15182        // both converted in this commit), the sibling M2
15183        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
15184        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
15185        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
15186        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
15187        // `Copy`-return `pub const fn` scalar accessors on the sibling
15188        // M3 surface. Pin the `const`-eval posture here so a future
15189        // accidental downgrade to non-`const` (an added runtime helper
15190        // reachable only from a non-`const` context, an
15191        // `Option<RestartPolicy>`-shape migration on the per-child
15192        // restart-decision axis once heterogeneous per-cluster
15193        // restart-policy overlays land that would silently drop the
15194        // `const` qualifier, a manual hand-rolled shadow) trips at
15195        // caixa-core build time rather than surfacing as a downstream
15196        // `const`-context regression far from the declaration.
15197        //
15198        // Same shape as the sibling M3
15199        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
15200        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
15201        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
15202        // accessor axis — the load-bearing witness lives in the
15203        // module-scope `const fn` wrapper `restart_via_const_fn` below:
15204        // a body that calls [`ChildSpec::restart`] under a `const fn`
15205        // signature is well-formed only when the callee is itself
15206        // `const fn`, so any future accidental downgrade of
15207        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
15208        // build time (const-eval E0015 `cannot call non-const method`),
15209        // strictly stronger than a runtime `assert!(CONST)` and
15210        // side-stepping the destructor-in-const restriction that
15211        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
15212        // items on `ChildSpec`'s `String` carriers.
15213        //
15214        // The runtime body sweeps every closed-set [`RestartPolicy`]
15215        // arm and asserts the wrapped and direct dispatches agree.
15216        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
15217            c.restart()
15218        }
15219        for restart in [
15220            RestartPolicy::Permanent,
15221            RestartPolicy::Transient,
15222            RestartPolicy::Temporary,
15223        ] {
15224            let c = ChildSpec {
15225                caixa: "worker".into(),
15226                versao: "^0.1".into(),
15227                restart,
15228            };
15229            assert_eq!(
15230                restart_via_const_fn(&c),
15231                c.restart(),
15232                "const-fn-wrapped and direct dispatch on \
15233                 ChildSpec::restart must agree for {restart:?}",
15234            );
15235            assert_eq!(
15236                c.restart(),
15237                restart,
15238                "ChildSpec::restart must return the storage-side \
15239                 RestartPolicy verbatim for {restart:?} (a violation \
15240                 means the accessor stopped being a raw field-return \
15241                 copy)",
15242            );
15243        }
15244    }
15245
15246    #[test]
15247    fn supervisor_spec_estrategia_accessor_is_const_fn() {
15248        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
15249        // sibling-restart-strategy `Copy`-return scalar accessor is
15250        // declared `#[must_use] pub const fn` — matching the sibling M2
15251        // per-`:children` [`ChildSpec::restart`] (pinned by
15252        // [`child_spec_restart_accessor_is_const_fn`] above, both
15253        // converted in this commit), the sibling M2 per-`:supervisor`
15254        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
15255        // accessor already `pub const fn`, and mirroring the peer M3
15256        // mesh-slot per-`:placement`
15257        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
15258        // `pub const fn` scalar accessor whose method-name discipline
15259        // the [`SupervisorSpec::estrategia`] method was authored to
15260        // match. Pin the `const`-eval posture here so a future
15261        // accidental downgrade to non-`const` (an added runtime helper
15262        // reachable only from a non-`const` context, an
15263        // `Option<RestartStrategy>`-shape migration once the substrate
15264        // grows per-cluster strategy overlays that would silently drop
15265        // the `const` qualifier, a manual hand-rolled shadow) trips at
15266        // caixa-core build time rather than surfacing as a downstream
15267        // `const`-context regression far from the declaration.
15268        //
15269        // Same shape as the sibling
15270        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
15271        // load-bearing witness lives in the module-scope `const fn`
15272        // wrapper `estrategia_via_const_fn` below: a body that calls
15273        // [`SupervisorSpec::estrategia`] under a `const fn` signature
15274        // is well-formed only when the callee is itself `const fn`,
15275        // side-stepping the destructor-in-const restriction that would
15276        // otherwise block a direct
15277        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
15278        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
15279        // carriers.
15280        //
15281        // The runtime body sweeps every closed-set [`RestartStrategy`]
15282        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
15283        // direct dispatches agree.
15284        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
15285            s.estrategia()
15286        }
15287        for &estrategia in RestartStrategy::ALL {
15288            let s = SupervisorSpec {
15289                estrategia,
15290                max_restarts: 5,
15291                restart_window: Some(Duration::from_secs(60)),
15292                children: Vec::new(),
15293            };
15294            assert_eq!(
15295                estrategia_via_const_fn(&s),
15296                s.estrategia(),
15297                "const-fn-wrapped and direct dispatch on \
15298                 SupervisorSpec::estrategia must agree for {estrategia:?}",
15299            );
15300            assert_eq!(
15301                s.estrategia(),
15302                estrategia,
15303                "SupervisorSpec::estrategia must return the storage-side \
15304                 RestartStrategy verbatim for {estrategia:?} (a violation \
15305                 means the accessor stopped being a raw field-return \
15306                 copy)",
15307            );
15308        }
15309    }
15310
15311    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
15312    // macro definition (see the paired doc-block above the macro
15313    // definition) — every generated `<ctor>(caixa: &str) -> Self`
15314    // constructor folds the uniform `Self::<Variant> { caixa:
15315    // caixa.to_string() }` one-field struct-literal onto one substrate
15316    // primitive. The three per-variant equivalence pins below
15317    // (fail-before-pass-after by construction — a byte-mismatched macro
15318    // arm would trip its equivalence pin first) lock each generated
15319    // constructor to its struct-literal peer under `PartialEq`, so
15320    // every wire-up in [`SupervisorSpec::validate_children`] and
15321    // [`validate_no_self_supervision`] on that variant produces a
15322    // byte-equal `SupervisorError` to the pre-lift open-coded
15323    // struct-literal. The cross-axis pin that follows (non-default
15324    // caixa name) routes the sole constructor input axis through
15325    // `.to_string()`, so the fold does not silently collapse onto a
15326    // fixed name.
15327    //
15328    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
15329    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
15330    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
15331    // `missing_entry_ctor_matches_struct_literal_wrap` /
15332    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
15333    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
15334    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
15335    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
15336    // on the six sibling ctor families the recent trajectory closed
15337    // on the peer `LayoutError` / `AplicacaoError` envelopes.
15338
15339    #[test]
15340    fn empty_child_version_ctor_matches_struct_literal_wrap() {
15341        assert_eq!(
15342            SupervisorError::empty_child_version("worker"),
15343            SupervisorError::EmptyChildVersion {
15344                caixa: "worker".to_string(),
15345            },
15346            "generated empty_child_version ctor must produce byte-equal \
15347             SupervisorError to the open-coded struct-literal wrap on the \
15348             same &str fixture",
15349        );
15350    }
15351
15352    #[test]
15353    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
15354        assert_eq!(
15355            SupervisorError::duplicate_child_caixa("worker"),
15356            SupervisorError::DuplicateChildCaixa {
15357                caixa: "worker".to_string(),
15358            },
15359            "generated duplicate_child_caixa ctor must produce byte-equal \
15360             SupervisorError to the open-coded struct-literal wrap on the \
15361             same &str fixture",
15362        );
15363    }
15364
15365    #[test]
15366    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
15367        assert_eq!(
15368            SupervisorError::child_supervises_self("orquestra"),
15369            SupervisorError::ChildSupervisesSelf {
15370                caixa: "orquestra".to_string(),
15371            },
15372            "generated child_supervises_self ctor must produce byte-equal \
15373             SupervisorError to the open-coded struct-literal wrap on the \
15374             same &str fixture",
15375        );
15376    }
15377
15378    // Per-variant equivalence pins for the two lifted
15379    // [`SupervisorError::child_caixa_invalid`] /
15380    // [`SupervisorError::child_versao_invalid`] inherent constructors
15381    // (fail-before-pass-after by construction — a byte-mismatched ctor body
15382    // would trip its equivalence pin first). Each pins the ctor output to
15383    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
15384    // in [`SupervisorSpec::validate_children`] on the two variants
15385    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
15386    // struct-literal on the same scalar fixtures. Peers of the sibling
15387    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
15388    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
15389    // the peer `AplicacaoError` envelope's
15390    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
15391
15392    #[test]
15393    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
15394        let caixa = "Worker";
15395        let reason = "sample reason text";
15396        assert_eq!(
15397            SupervisorError::child_caixa_invalid(caixa, reason),
15398            SupervisorError::ChildCaixaInvalid {
15399                caixa: caixa.to_string(),
15400                reason: reason.to_string(),
15401            },
15402            "lifted child_caixa_invalid ctor must produce byte-equal \
15403             SupervisorError to the open-coded struct-literal wrap on the \
15404             same (&str, reason) fixture",
15405        );
15406    }
15407
15408    #[test]
15409    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
15410        let caixa = "worker";
15411        let versao = "not-a-req";
15412        let reason = "sample reason text";
15413        assert_eq!(
15414            SupervisorError::child_versao_invalid(caixa, versao, reason),
15415            SupervisorError::ChildVersaoInvalid {
15416                caixa: caixa.to_string(),
15417                versao: versao.to_string(),
15418                reason: reason.to_string(),
15419            },
15420            "lifted child_versao_invalid ctor must produce byte-equal \
15421             SupervisorError to the open-coded struct-literal wrap on the \
15422             same (&str, &str, reason) fixture",
15423        );
15424    }
15425
15426    #[test]
15427    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
15428        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
15429        // against a `&str`-literal vs. `format!(…)` reason input to pin
15430        // both constructors accept the `impl Into<String>` bound
15431        // uniformly, so neither wire-up site drifts under a per-arm
15432        // wrapper transformation on the caller-side `reason` axis. Peer
15433        // of the sibling
15434        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
15435        // sweep on the peer `AplicacaoError` envelope.
15436        let via_literal = "literal reason text";
15437        let via_format = format!("{} reason text", "literal");
15438        assert_eq!(
15439            SupervisorError::child_caixa_invalid("Worker", via_literal),
15440            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
15441        );
15442        assert_eq!(
15443            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
15444            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
15445        );
15446    }
15447
15448    #[test]
15449    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
15450        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
15451        // &str`) through a non-default fixture name against every
15452        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
15453        // so any wrapper-side lowercase / trim / truncate / re-order on
15454        // the `caixa.to_string()` sole-field construction surfaces
15455        // here rather than at a downstream diagnostic-shape mismatch.
15456        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
15457        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
15458        // through_to_string` / `contrato_target_ctors_route_edge_
15459        // triple_through_verbatim` / `contrato_empty_pair_ctors_
15460        // route_edge_pair_through_verbatim` cross-axis routing pins on
15461        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
15462        // here onto the `SupervisorError` `{ caixa: String }` envelope
15463        // so every substrate-primitive ctor family in caixa-core
15464        // guarantees the sole-field construction routes the caller's
15465        // `&str` through `.to_string()` verbatim.
15466        let name = "cache-v2";
15467        assert_eq!(
15468            SupervisorError::empty_child_version(name),
15469            SupervisorError::EmptyChildVersion {
15470                caixa: name.to_string(),
15471            },
15472        );
15473        assert_eq!(
15474            SupervisorError::duplicate_child_caixa(name),
15475            SupervisorError::DuplicateChildCaixa {
15476                caixa: name.to_string(),
15477            },
15478        );
15479        assert_eq!(
15480            SupervisorError::child_supervises_self(name),
15481            SupervisorError::ChildSupervisesSelf {
15482                caixa: name.to_string(),
15483            },
15484        );
15485    }
15486
15487    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
15488    //
15489    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
15490    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
15491    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
15492    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
15493    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
15494    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
15495    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
15496    // / silent constant-substitution on any one variant surfaces here rather
15497    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
15498    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
15499    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
15500    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
15501    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
15502    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
15503    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
15504    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
15505    #[test]
15506    fn no_children_ctor_matches_struct_literal_wrap() {
15507        let estrategia = RestartStrategy::OneForAll;
15508        assert_eq!(
15509            SupervisorError::no_children(estrategia),
15510            SupervisorError::NoChildren { estrategia },
15511            "generated no_children ctor must produce byte-equal \
15512             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
15513             on the same `Copy`-`RestartStrategy` fixture",
15514        );
15515    }
15516
15517    #[test]
15518    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
15519        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
15520        assert_eq!(
15521            SupervisorError::max_restarts_exceeds_cap(max_restarts),
15522            SupervisorError::MaxRestartsExceedsCap { max_restarts },
15523            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
15524             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
15525             struct-literal wrap on the same `Copy`-`u32` fixture",
15526        );
15527    }
15528
15529    #[test]
15530    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
15531        let window = Duration::from_micros(1_500);
15532        assert_eq!(
15533            SupervisorError::restart_window_not_canonical(window),
15534            SupervisorError::RestartWindowNotCanonical { window },
15535            "generated restart_window_not_canonical ctor must produce \
15536             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
15537             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15538        );
15539    }
15540
15541    #[test]
15542    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
15543        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
15544        assert_eq!(
15545            SupervisorError::restart_window_exceeds_cap(window),
15546            SupervisorError::RestartWindowExceedsCap { window },
15547            "generated restart_window_exceeds_cap ctor must produce \
15548             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
15549             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15550        );
15551    }
15552
15553    #[test]
15554    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
15555        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
15556        // constructor input axis through a non-default `Copy` fixture against
15557        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
15558        // side silent `.into()` / silent constant-substitution / silent field
15559        // re-name away from the canonical `estrategia | max_restarts | window`
15560        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
15561        // axis silently rerouted through some other `Copy` coercion, surfaces
15562        // here rather than at a downstream per-`:supervisor` diagnostic-shape
15563        // drift. Peer of the sibling
15564        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
15565        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
15566        // envelope's per-`:politicas` per-axis ctor family, extended here onto
15567        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
15568        // variant family folded onto a substrate primitive.
15569        //
15570        // Fixtures picked out of each variant's accept-set boundary rather
15571        // than the default value so a silent constant-substitution to a per-
15572        // variant sentinel surfaces here on the structural-equality assertion.
15573        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
15574        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
15575        // isn't the `SimpleOneForOne` arm the sibling
15576        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
15577        // `max_restarts` fixture picks an above-cap magnitude the cap arm
15578        // rejects; the two `Duration` fixtures pick the sub-millisecond and
15579        // above-cap ends of the `:restart-window` canonical-form + cap
15580        // bracket respectively.
15581        let estrategia = RestartStrategy::RestForOne;
15582        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
15583        let sub_ms = Duration::from_micros(1_500);
15584        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
15585        assert_eq!(
15586            SupervisorError::no_children(estrategia),
15587            SupervisorError::NoChildren { estrategia },
15588        );
15589        assert_eq!(
15590            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
15591            SupervisorError::MaxRestartsExceedsCap {
15592                max_restarts: above_cap_restarts,
15593            },
15594        );
15595        assert_eq!(
15596            SupervisorError::restart_window_not_canonical(sub_ms),
15597            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
15598        );
15599        assert_eq!(
15600            SupervisorError::restart_window_exceeds_cap(above_hour),
15601            SupervisorError::RestartWindowExceedsCap { window: above_hour },
15602        );
15603    }
15604
15605    #[test]
15606    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
15607        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
15608        // generated ctor `const fn` so a caller can pin a `SupervisorError`
15609        // at compile time — the same zero-runtime-work property the pre-lift
15610        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
15611        // its `Copy`-pass-through construction path (no `.to_string()` /
15612        // `.into()` allocation, no branching). If any future edit silently
15613        // drops the `const` qualifier from the macro body the per-arm `const`
15614        // bindings below fail to compile, which surfaces the regression at
15615        // the substrate-primitive definition rather than at some downstream
15616        // consumer that had come to rely on the `const`-constructibility.
15617        // Peer of the sibling
15618        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
15619        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
15620        // per-`:politicas` per-axis ctor family.
15621        const NO_CHILDREN: SupervisorError =
15622            SupervisorError::no_children(RestartStrategy::OneForAll);
15623        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
15624        const WINDOW_NC: SupervisorError =
15625            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
15626        const WINDOW_CAP: SupervisorError =
15627            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
15628        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
15629        assert!(matches!(
15630            MAX_RESTARTS_CAP,
15631            SupervisorError::MaxRestartsExceedsCap { .. }
15632        ));
15633        assert!(matches!(
15634            WINDOW_NC,
15635            SupervisorError::RestartWindowNotCanonical { .. }
15636        ));
15637        assert!(matches!(
15638            WINDOW_CAP,
15639            SupervisorError::RestartWindowExceedsCap { .. }
15640        ));
15641    }
15642}