Skip to main content

caixa_core/
supervisor.rs

1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome           "my-app-root"
10//!   :versao         "0.1.0"
11//!   :kind           Supervisor
12//!   :estrategia     OneForOne
13//!   :max-restarts   5
14//!   :restart-window "60s"
15//!   :children       ((:caixa "worker"       :versao "^0.1" :restart Permanent)
16//!                    (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//!                    (:caixa "scratch-job"  :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34    Serialize,
35    Deserialize,
36    Debug,
37    Clone,
38    Copy,
39    PartialEq,
40    Eq,
41    Hash,
42    gen_platform::TypedDispatcher,
43    gen_platform::Discriminant,
44    gen_platform::IsVariant,
45    gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48    /// On child failure, restart only that child. Default; matches
49    /// most "tree of independent workers" use cases.
50    OneForOne,
51    /// On child failure, restart every child. Used when children
52    /// share state and must be in sync.
53    OneForAll,
54    /// On child failure, restart the failed child and every child
55    /// started *after* it (preserving startup order). Used when later
56    /// children depend on earlier ones.
57    RestForOne,
58    /// Dynamic children of the same shape, started on demand. The
59    /// supervisor doesn't know its children at boot; they're added as
60    /// they're needed (e.g. one child per session).
61    SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65    fn default() -> Self {
66        // Route the [`Default for RestartStrategy`] impl through the
67        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68        // `pub const` rather than a raw `Self::OneForOne` arm — one
69        // source of truth for the Erlang/OTP `one_for_one` half of Learn
70        // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71        // supervisor canonical default, paired with the sibling
72        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73        // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74        // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75        SUPERVISOR_ESTRATEGIA_DEFAULT
76    }
77}
78
79impl RestartStrategy {
80    /// Exhaustive iteration surface for every consumer that walks the
81    /// closed four-arm [`RestartStrategy`] discriminator set (the future
82    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83    /// admission-webhook rejection body naming the accepted-`:estrategia`
84    /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85    /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86    /// the future `feira app graph` per-supervisor `:estrategia` column,
87    /// any future round-trip fuzz harness that sweeps every arm). A
88    /// future arm addition (an OTP-`rest_for_all` arm the theory
89    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90    /// might reach for once the four canonical OTP strategies stop
91    /// covering the substrate's discovered load-shape) extends this
92    /// slice as one edit and every consumer picks up the new entry by
93    /// construction; the compiler-checked exhaustiveness on the sibling
94    /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95    /// the build-time guarantee that no arm forgets to grow.
96    ///
97    /// Peer of the sibling closed-set typed enums'
98    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102    /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103    /// typed enum on the caixa surface to converge onto the same
104    /// one-canonical-arm-list-per-enum discipline.
105    pub const ALL: &'static [Self] = &[
106        Self::OneForOne,
107        Self::OneForAll,
108        Self::RestForOne,
109        Self::SimpleOneForOne,
110    ];
111
112    /// Canonical PascalCase discriminator scalar this variant serializes
113    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118    /// constants so every substrate consumer that dispatches on the
119    /// per-supervisor sibling-restart strategy (the future
120    /// wasm-operator's per-supervisor sibling-restart branch, the future
121    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123    /// reconciliation scheduler's per-strategy fan-out) reads the same
124    /// byte-string the `Serialize` derive emits — the pin test in
125    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126    /// asserts the two paths agree, peer of the M3
127    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128    /// distribution-strategy axis.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136        }
137    }
138
139    /// Substrate-canonical reverse projection on the `:supervisor
140    /// :estrategia` closed-set axis — parses the `PascalCase`
141    /// discriminator scalar back to the typed variant, or `None` when
142    /// `s` is outside
143    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144    /// on the same lifted
145    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149    /// constants the [`Self::as_str`] emitter walks, so the parse and
150    /// emit halves of the round-trip migrate through one caixa-core
151    /// edit on any future arm addition.
152    ///
153    /// Prior to this lift the substrate carried only the forward
154    /// `Self → &str` projection on the OTP sibling-restart axis (the
155    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156    /// through it, the `Serialize` derive that emits the same
157    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158    /// plus the kebab-case dispatcher-catalog identity via
159    /// [`Self::discriminant`] — every non-serde consumer that wanted to
160    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163    /// that expressed no compile-time link back to the typed variant's
164    /// canonical lifted constant. A future variant rename or per-arm
165    /// serde-attribute drift would silently split the wire byte-string
166    /// one non-serde consumer parsed from the one the emitter wrote,
167    /// with the failure surfacing at parse time far from the rebrand
168    /// commit.
169    ///
170    /// Distinct axis from the [`std::str::FromStr`] impl the
171    /// [`gen_platform::FromStrKind`] derive already installs on this
172    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175    /// [`Self::discriminant`]), while this method inverts the
176    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177    /// two-axis split lets the dispatcher-catalog identity live in
178    /// kebab-case
179    /// (where every peer catalog identifier already lives) without
180    /// forcing a wire-format rename on the tatara-lisp author surface
181    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184    /// carry on their peer closed-set typed-enum wire round-trips.
185    ///
186    /// Same closed-set-reverse-projection discipline the sibling
187    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190    /// carry on the peer wire-side `str → Self` axes — extended onto
191    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192    /// fifth substrate-side closed-set typed enum to converge on the
193    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196    /// derive already installs on the sibling kebab-case axis. Returns
197    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198    /// shapes: the caller picks the diagnostic form appropriate for
199    /// its use site.
200    #[must_use]
201    pub fn from_wire(s: &str) -> Option<Self> {
202        match s {
203            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207            _ => None,
208        }
209    }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(self.as_str())
280    }
281}
282
283/// Substrate-canonical [`AsRef<str>`] projection on the M2
284/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
285/// enum — routes through the same [`RestartStrategy::as_str`]
286/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
287/// impl and the un-`rename`d [`serde::Serialize`] derive already key
288/// off, so any future consumer that binds a [`RestartStrategy`]
289/// through the standard-library `impl AsRef<str>` bound (a future
290/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
291/// composes the emitted `PascalCase` wire scalar into a
292/// [`std::process::Command::arg`] shell-out of the future
293/// wasm-operator's admission gate, a per-supervisor structured-log
294/// recorder on the future `caixa-operator`'s hierarchical
295/// reconciliation surface that accepts `impl AsRef<str>` at the
296/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
297/// lookup keyed on the estrategia wire byte through
298/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
299/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
300/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
303/// lifted-const through one substrate-primitive dispatch rather
304/// than an open-coded `.as_str()` projection at every wire-up.
305///
306/// Peer of the sibling [`std::fmt::Display`] impl on the same
307/// primitive — both delegate to the shared
308/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
309/// [`format!("{s}")`], `s.as_str()`, and
310/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
311/// byte-string per instance by construction. A future variant rename
312/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
313/// enum reaches every one of the three paths (plus the wire-format
314/// `Serialize` derive that already routes through the same lifted
315/// const) through exactly one caixa-core edit.
316///
317/// Same "route the trait impl through the substrate-primitive
318/// accessor" discipline the sibling [`crate::CaixaVersion`]
319/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
320/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
321/// axis on the caixa typed surface (the first M2 OTP-shape
322/// closed-set typed enum to converge onto the standard-library
323/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
324/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
325/// primitive so a caller who has one has both; before this lift,
326/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
327/// [`AsRef<str>`] impl the convention names.
328///
329/// Pinned load-bearing by
330/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
331/// (byte-parity pin against [`RestartStrategy::as_str`] across the
332/// four-arm closed set) — any future silent detour that routes the
333/// impl through a divergent projection (a per-arm inline
334/// `match self { … }` re-inlining that opens a compile-time link to
335/// the un-lifted arm-literal, a swap onto the kebab-case
336/// [`gen_platform::Discriminant`] catalog identity that would collide
337/// the wire axis with the dispatcher-catalog axis) trips at
338/// caixa-core test time under `assert_eq!` rather than at a
339/// downstream `impl AsRef<str>`-bound consumer's silent split.
340impl AsRef<str> for RestartStrategy {
341    fn as_ref(&self) -> &str {
342        self.as_str()
343    }
344}
345
346/// Per-child restart policy.
347///
348/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
349#[derive(
350    Serialize,
351    Deserialize,
352    Debug,
353    Clone,
354    Copy,
355    PartialEq,
356    Eq,
357    Hash,
358    gen_platform::TypedDispatcher,
359    gen_platform::Discriminant,
360    gen_platform::IsVariant,
361    gen_platform::FromStrKind,
362)]
363pub enum RestartPolicy {
364    /// Always restart the child, regardless of how it died. Used for
365    /// long-running services that must always be up.
366    Permanent,
367    /// Never restart. Used for one-shot work whose completion is
368    /// itself the success signal (`oneShot` triggers map here).
369    Temporary,
370    /// Restart only when the child died *abnormally* (non-zero exit
371    /// or unhandled exception). A clean exit completes the child.
372    Transient,
373}
374
375impl Default for RestartPolicy {
376    fn default() -> Self {
377        // Route the [`Default for RestartPolicy`] impl's return arm through
378        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
379        // `pub const` rather than a raw `Self::Permanent` arm — one source
380        // of truth for the Erlang/OTP-canonical `permanent` worker-child
381        // default across the two production consumers that currently
382        // dispatch on it (this impl at the [`RestartPolicy::default`] call
383        // and the serde-side `#[serde(default)]` on
384        // [`ChildSpec::restart`] that resolves an author-omitted
385        // `:children :restart` slot through `RestartPolicy::default()`).
386        // Peer of the sibling per-`:supervisor` axis
387        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
388        // route (95ffacc) — the two impls now share one substrate-primitive
389        // lift discipline, so any future coherent rebrand of the OTP-shape
390        // supervisor+child default set migrates through typed constants in
391        // lockstep instead of splitting a lifted supervisor half against
392        // an open-coded child half. Pinned by
393        // `restart_policy_default_routes_through_lifted_default` +
394        // `child_spec_serde_default_restart_routes_through_lifted_default`
395        // in the tests module.
396        SUPERVISOR_CHILD_RESTART_DEFAULT
397    }
398}
399
400impl RestartPolicy {
401    /// Exhaustive iteration surface for every consumer that walks the
402    /// closed three-arm [`RestartPolicy`] discriminator set (the future
403    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
404    /// per-child admission-webhook rejection body naming the accepted-
405    /// `:restart` list, a future `feira supervisor --restart …` CLI
406    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
407    /// over the slice, the future `feira app graph` per-child restart
408    /// column, any future round-trip fuzz harness that sweeps every
409    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
410    /// theory
411    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
412    /// might reach for once the three canonical OTP restart policies
413    /// stop covering the substrate's discovered load-shape) extends
414    /// this slice as one edit and every consumer picks up the new entry
415    /// by construction; the compiler-checked exhaustiveness on the
416    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
417    /// is the build-time guarantee that no arm forgets to grow.
418    ///
419    /// Peer of the sibling closed-set typed enums'
420    /// [`RestartStrategy::ALL`] (4eec29c) /
421    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
422    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
423    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
424    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
425    /// surfaces — the sixth (and the third and final M2 OTP-shape)
426    /// closed-set typed enum on the caixa surface to converge onto the
427    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
428    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
429    /// sibling-restart-strategy axis; this closes the per-child
430    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
431    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
432
433    /// Canonical PascalCase discriminator scalar this variant serializes
434    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
435    /// arms return the paired
436    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
437    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
438    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
439    /// constants so every substrate consumer that dispatches on the
440    /// per-child restart-decision policy (the future wasm-operator's
441    /// per-child post-exit restart-decision branch, the future M4
442    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
443    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
444    /// reconciliation scheduler's per-child-policy fan-out) reads the
445    /// same byte-string the `Serialize` derive emits — the pin test in
446    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
447    /// asserts the two paths agree, peer of the M2
448    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
449    /// sibling-restart-strategy axis and the M3
450    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
451    /// per-Aplicacao distribution-strategy axis — the third of three
452    /// OTP-shaped closed-enum discriminator axes on the caixa typed
453    /// surface to converge onto the same three-path-convergence
454    /// (`Serialize` derive → `as_str` helper → lifted constant)
455    /// drift-detection posture.
456    #[must_use]
457    pub const fn as_str(self) -> &'static str {
458        match self {
459            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
460            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
461            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
462        }
463    }
464
465    /// Substrate-canonical reverse projection on the `:children :restart`
466    /// closed-set axis — parses the `PascalCase` discriminator scalar
467    /// back to the typed variant, or `None` when `s` is outside the
468    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
469    /// the same lifted
470    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
471    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
472    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
473    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
474    /// of the round-trip migrate through one caixa-core edit on any
475    /// future arm addition.
476    ///
477    /// Prior to this lift the substrate carried only the forward
478    /// `Self → &str` projection on the OTP per-child restart-policy
479    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
480    /// impl routed through it, the `Serialize` derive that emits the
481    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
482    /// plus the kebab-case dispatcher-catalog identity via
483    /// [`Self::discriminant`] — every non-serde consumer that wanted to
484    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
485    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
486    /// "Transient" => …, _ => … }` cascade that expressed no
487    /// compile-time link back to the typed variant's canonical lifted
488    /// constant. A future variant rename or per-arm serde-attribute
489    /// drift would silently split the wire byte-string one non-serde
490    /// consumer parsed from the one the emitter wrote, with the failure
491    /// surfacing at the operator's reconcile posture (a `:temporary`
492    /// `oneShot` child being restarted on clean exit, treating the
493    /// successful-completion signal as failure and re-running the
494    /// completion-terminal one-shot indefinitely; a `:transient` child
495    /// that clean-exited being restarted, masking the clean-completion
496    /// contract) far from the rebrand commit and with no field naming
497    /// the drift.
498    ///
499    /// Distinct axis from the [`std::str::FromStr`] impl the
500    /// [`gen_platform::FromStrKind`] derive already installs on this
501    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
502    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
503    /// `"transient"` — the inverse of [`Self::discriminant`]), while
504    /// this method inverts the `PascalCase` wire byte-string
505    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
506    /// catalog identity live in kebab-case (where every peer catalog
507    /// identifier already lives) without forcing a wire-format rename
508    /// on the tatara-lisp author surface (`:restart Permanent`,
509    /// `PascalCase`) — the same two-axis distinction the sibling
510    /// [`RestartStrategy::from_wire`] (4eec29c) /
511    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
512    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
513    /// carry on their peer closed-set typed-enum wire round-trips.
514    ///
515    /// Same closed-set-reverse-projection discipline the sibling
516    /// [`RestartStrategy::from_wire`] (4eec29c) /
517    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
518    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
519    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
520    /// carry on the peer wire-side `str → Self` axes — extended onto
521    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
522    /// sixth substrate-side closed-set typed enum (and the third and
523    /// final OTP-shape closed-enum discriminator axis) to converge on
524    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
525    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
526    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
527    /// derive already installs on the sibling kebab-case axis. Returns
528    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
529    /// shapes: the caller picks the diagnostic form appropriate for
530    /// its use site.
531    #[must_use]
532    pub fn from_wire(s: &str) -> Option<Self> {
533        match s {
534            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
535            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
536            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
537            _ => None,
538        }
539    }
540}
541
542/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
543/// pretty-printed byte-string every consumer that formats the policy as
544/// user-facing text lands on (the future wasm-operator's per-child
545/// post-exit restart-decision diagnostic line, the future `feira app
546/// graph` per-child restart column, the future M4
547/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
548/// admission-webhook rejection body) reaches for the same lifted
549/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
550/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
551/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
552/// wire-format `Serialize` derive already emits under
553/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
554/// [`RestartPolicy::as_str`] helper already returns.
555///
556/// Pre-convergence the two paths structurally disagreed — the
557/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
558/// route (now retired here) sent [`std::fmt::Display`] through the
559/// gen-platform discriminant catalog string, which arrives kebab-case as
560/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
561/// (whose variant names each collapse to their own lowercase form under
562/// the kebab-case transform), while the wire format ran as `PascalCase`
563/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
564/// serde derive. Every consumer that formatted the policy for a
565/// diagnostic line, a graph column, or a rejection body under
566/// `format!("{v}")` therefore landed under a different byte-string than
567/// the wire format the operator's per-child-policy dispatch keyed off —
568/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
569/// diagnostic quoting `"permanent"` while the wire scalar the operator
570/// probed was `"Permanent"`) surfaced as a confused correlate at
571/// operator-log time far from the two-declaration site.
572///
573/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
574/// path: every `format!("{v}")` call reaches the same lifted
575/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
576/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
577/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
578/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
579/// byte-string per variant. A future variant rename or
580/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
581/// exactly one place, structurally.
582///
583/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
584/// (from `#[derive(gen_platform::Discriminant)]`) still returns
585/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
586/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
587/// registration keys the catalog off the same kebab identity. The two
588/// naming worlds now live on separate typed methods (`Display` /
589/// `as_str` for the wire byte-string, `discriminant` for the catalog
590/// identity) rather than sharing one `Display` route that structurally
591/// disagrees with the wire format.
592///
593/// Pin tests
594/// [`tests::restart_policy_display_routes_through_as_str_helper`]
595/// and
596/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
597/// assert the three paths agree byte-for-byte on every variant, so a
598/// future variant rename or per-arm serde attribute drift is a build
599/// error visible at caixa-core test time, not a silent per-consumer
600/// dispatch miss at apply / reconcile time.
601///
602/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
603/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
604/// and the sibling [`RestartStrategy`] `Display` impl on the
605/// per-supervisor sibling-restart-strategy axis — same three-path-
606/// convergence discipline, extended to close the third and final of
607/// three OTP-shaped closed-enum discriminator axes on the caixa typed
608/// surface.
609impl std::fmt::Display for RestartPolicy {
610    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
611        f.write_str(self.as_str())
612    }
613}
614
615/// Substrate-canonical [`AsRef<str>`] projection on the M2
616/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
617/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
618/// scalar accessor the paired [`std::fmt::Display`] impl and the
619/// un-`rename`d [`serde::Serialize`] derive already key off, so any
620/// future consumer that binds a [`RestartPolicy`] through the
621/// standard-library `impl AsRef<str>` bound (a future
622/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
623/// composes the emitted `PascalCase` wire scalar into a
624/// [`std::process::Command::arg`] shell-out of the future
625/// wasm-operator's per-child admission gate, a per-child structured-
626/// log recorder on the future `caixa-operator`'s hierarchical
627/// reconciliation surface that accepts `impl AsRef<str>` at the
628/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
629/// lookup keyed on the restart-policy wire byte through
630/// `map.get::<str>(policy.as_ref())` on a future per-policy
631/// dispatch table) reaches the paired
632/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
633/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
634/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
635/// lifted-const through one substrate-primitive dispatch rather
636/// than an open-coded `.as_str()` projection at every wire-up.
637///
638/// Peer of the sibling [`std::fmt::Display`] impl on the same
639/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
640/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
641/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
642/// byte-string per instance by construction. A future variant rename
643/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
644/// enum reaches every one of the three paths (plus the wire-format
645/// `Serialize` derive that already routes through the same lifted
646/// const) through exactly one caixa-core edit.
647///
648/// Same "route the trait impl through the substrate-primitive
649/// accessor" discipline the sibling [`crate::CaixaVersion`]
650/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
651/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
652/// the axis onto the paired per-child-restart-decision-policy
653/// sibling on the same M2 `:supervisor` slot (the second M2
654/// OTP-shape closed-set typed enum to converge onto the standard-
655/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
656/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
657/// primitive so a caller who has one has both; before this lift,
658/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
659/// [`AsRef<str>`] impl the convention names.
660///
661/// Pinned load-bearing by
662/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
663/// (byte-parity pin against [`RestartPolicy::as_str`] across the
664/// three-arm closed set) and
665/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
666/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
667/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
668/// arm) — any future silent detour that routes the impl through a
669/// divergent projection (a per-arm inline `match self { … }`
670/// re-inlining that opens a compile-time link to the un-lifted
671/// arm-literal, a swap onto the kebab-case
672/// [`gen_platform::Discriminant`] catalog identity that would
673/// collide the wire axis with the dispatcher-catalog axis) trips at
674/// caixa-core test time under `assert_eq!` rather than at a
675/// downstream `impl AsRef<str>`-bound consumer's silent split.
676impl AsRef<str> for RestartPolicy {
677    fn as_ref(&self) -> &str {
678        self.as_str()
679    }
680}
681
682// Fleet-wide dispatcher-catalog registrations for caixa's OTP
683// supervisor surface — two more typed shadows over Erlang/OTP
684// primitives the substrate now mechanically tracks (see
685// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
686// theory/TYPED-ABSORPTION.md for the absorption arc).
687gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
688gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
689
690/// One child entry in the supervisor's `:children` list.
691///
692/// Every child references another caixa by `:caixa <nome>` + version
693/// constraint. The supervisor materializes one ComputeUnit per entry.
694#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
695#[serde(rename_all = "camelCase")]
696pub struct ChildSpec {
697    /// The child caixa's `:nome`. Must resolve via the same dependency
698    /// resolution path as `:deps` (caixa-resolver).
699    pub caixa: String,
700
701    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
702    /// [`crate::dep::Dep::versao`].
703    pub versao: String,
704
705    /// Restart policy — an author-omitted slot degrades onto the
706    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
707    /// (`permanent`, the Erlang/OTP worker-child default) through the
708    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
709    /// to.
710    #[serde(default)]
711    pub restart: RestartPolicy,
712}
713
714impl ChildSpec {
715    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
716    /// accessor every consumer that reads the OTP-shape supervised
717    /// child's identity keys off — returns the author-declared
718    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
719    /// from the typed slot's own [`String`] storage.
720    ///
721    /// The `:children :caixa` slot carries the DNS-1123 label — the
722    /// child caixa's `:nome` — that every emitted cluster artifact
723    /// derives its `metadata.name` from verbatim: the rendered
724    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
725    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
726    /// identity, and the per-child K8s Service `metadata.name` the
727    /// future wasm-operator (M3) provisions for inter-child supervision-
728    /// tree wiring. Every downstream consumer that fans on the child's
729    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
730    /// per-child DNS-1123 gate at
731    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
732    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
733    /// [`validate_no_self_supervision`] cross-slot equality check
734    /// against the parent's `:nome`, every `SupervisorError` variant
735    /// carrying the offending child caixa verbatim for `feira lint`
736    /// rendering, the future wasm-operator's hierarchical reconciliation
737    /// scheduler's per-child ComputeUnit-name projection, the future M4
738    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
739    /// admission webhook).
740    ///
741    /// Prior to this lift the `.caixa` byte-string was accessed inline
742    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
743    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
744    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
745    /// carriers' `child.caixa.clone()`, the dedup key's
746    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
747    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
748    /// field-accesses that expressed no compile-time link back to the
749    /// typed slot. A future extension of the `:children :caixa` axis to
750    /// a richer author surface (a per-cluster alias table the operator
751    /// pins through a future `:placement`-scoped slot on the supervisor
752    /// tree, a namespace-qualified rewrite the M4 CR materializer
753    /// applies per-CR, a per-child overlay from the future `:children
754    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
755    /// acknowledges) would have had to be threaded through every
756    /// open-coded copy in lockstep or one consumer would silently
757    /// disagree with the peers on which caixa a given child resolves to
758    /// — a child-set lookup that treated the name as `"cart-worker"`
759    /// while the peer duplicate-detector treated it as
760    /// `"tenant-a/cart-worker"` would silently split the
761    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
762    /// self-supervision detector's parent-equality check, a two-consumer
763    /// split at the validator far from the source `caixa.lisp` with no
764    /// field naming the identity-drift root cause. Lifting the resolution
765    /// rule to a typed method on the substrate primitive means every
766    /// downstream consumer of the Supervisor's per-`:children` identity
767    /// surface reaches for exactly one typed dispatch — the resolver's
768    /// accept-set migrates as a unit on any future axis addition.
769    ///
770    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
771    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
772    /// mesh-slot surface — same "one typed dispatch on the substrate
773    /// primitive, thin projections at each consumer" discipline extended
774    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
775    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
776    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
777    /// accessor discipline for the shared substrate concept "another
778    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
779    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
780    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
781    /// slot family's typed-accessor discipline now spans both the
782    /// upgrade axis (`:upgrade-from`) and the supervision axis
783    /// (`:children`), matching the closed M3 mesh-slot accessor family's
784    /// shape. Named `nome()` to match the tatara-lisp author-surface
785    /// term the field's docstring already reaches for ("The child
786    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
787    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
788    /// discipline the substrate already carries — the accessor's name
789    /// maps directly onto the canonical caixa-identity vocabulary rather
790    /// than shadowing the field's storage-side `caixa` label.
791    #[must_use]
792    pub const fn nome(&self) -> &str {
793        self.caixa.as_str()
794    }
795
796    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
797    /// requirement scalar accessor every consumer that reads the OTP-shape
798    /// supervised child's version pin keys off — returns the author-declared
799    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
800    /// the typed slot's own [`String`] storage.
801    ///
802    /// The `:children :versao` slot carries the Cargo-shaped semver
803    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
804    /// which release of the supervised child caixa the OTP-shape supervisor
805    /// tree materializes against — the same requirement grammar the peer
806    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
807    /// shared [`crate::render::require_valid_versao_requirement`] cascade
808    /// and the shared [`crate::version::parse_requirement`] parser. Every
809    /// downstream consumer that fans on the child's version pin keys off
810    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
811    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
812    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
813    /// for `feira lint` rendering, every future per-cluster version-lock
814    /// overlay the caixa-operator's hierarchical reconciliation scheduler
815    /// pins through a future `:placement`-scoped supervisor-tree slot, the
816    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
817    /// per-child version resolver, the future wasm-operator's per-child
818    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
819    ///
820    /// Prior to this lift the `.versao` byte-string was accessed inline at
821    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
822    /// [`SupervisorSpec::validate`] requirement-gate call
823    /// `require_valid_versao_requirement(&child.versao, …)` and the
824    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
825    /// `versao: child.versao.clone()` — two open-coded field-accesses that
826    /// expressed no compile-time link back to the typed slot. A future
827    /// extension of the `:children :versao` axis to a richer author surface
828    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
829    /// flow, a lacre-projected concrete-version rewrite the operator
830    /// materializes at CR-admission time, a future `:children :versao-lock`
831    /// per-cluster override slot the wasm-operator's hierarchical
832    /// reconciliation scheduler authors per-CR) would have had to be
833    /// threaded through both open-coded copies in lockstep or one consumer
834    /// would silently disagree with the peer on which release constraint a
835    /// given child resolves to — the requirement-gate call reading
836    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
837    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
838    /// the actual gate rejection input, a two-consumer split at the
839    /// validator far from the source `caixa.lisp` with no field naming the
840    /// version-pin drift root cause. Lifting the resolution rule to a typed
841    /// method on the substrate primitive means every downstream
842    /// requirement-facing consumer of the Supervisor's per-`:children`
843    /// version-pin surface reaches for exactly one typed dispatch — the
844    /// resolver's accept-set migrates as a unit on any future axis addition.
845    ///
846    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
847    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
848    /// surface — same "one typed dispatch on the substrate primitive, thin
849    /// projections at each consumer" discipline extended onto the M2
850    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
851    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
852    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
853    /// one accessor discipline for the shared substrate concept "another
854    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
855    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
856    /// `:nome` scalar accessor — the pair
857    /// `(nome(), versao_requirement())` jointly projects the
858    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
859    /// that fans on per-child identity + version pin keys off, closing the
860    /// last unlifted per-`:children` `String`-carry axis so every downstream
861    /// per-`:children` reader now routes through a typed dispatch on the
862    /// substrate primitive. Named `versao_requirement()` rather than
863    /// `versao()` because the field's storage-side `.versao` label is
864    /// already the author-surface term (`:versao`); the accessor's name
865    /// carries the semantic role — the semver *requirement* string the
866    /// shared [`crate::version::parse_requirement`] entry-point consumes —
867    /// so a raw field access and a typed dispatch read differently at every
868    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
869    /// naming discipline verbatim.
870    #[must_use]
871    pub const fn versao_requirement(&self) -> &str {
872        self.versao.as_str()
873    }
874
875    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
876    /// per-child post-exit restart-decision policy scalar accessor every
877    /// consumer that dispatches on the supervised child's post-exit
878    /// reconcile posture keys off — returns the author-declared
879    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
880    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
881    /// storage.
882    ///
883    /// The `:children :restart` slot carries the closed-set OTP-shaped
884    /// per-child restart-decision policy discriminator
885    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
886    /// worker-child default; [`RestartPolicy::Transient`] — restart only
887    /// on abnormal exit, the OTP `transient` clean-completion-aware
888    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
889    /// `temporary` one-shot default) that every downstream consumer of
890    /// the Supervisor's per-child post-exit reconcile branch keys off.
891    /// Every future downstream consumer that fans on the per-child
892    /// restart-decision keys off this scalar (the future `feira app
893    /// graph` per-child restart column, the future wasm-operator's
894    /// per-child post-exit restart-decision branch, the future M4
895    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
896    /// admission webhook, the `caixa-operator`'s hierarchical
897    /// reconciliation scheduler's per-child post-exit reconcile branch,
898    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
899    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
900    /// pin threads through).
901    ///
902    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
903    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
904    /// scalar accessor and the M3 mesh-slot
905    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
906    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
907    /// — same "one typed dispatch on the substrate primitive,
908    /// `Copy`-projected closed-set enum-arm discriminator that partitions
909    /// the downstream renderer's per-arm fan-out" discipline extended
910    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
911    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
912    /// [`ChildSpec`] type — companion to the sibling per-`:children`
913    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
914    /// and the per-`:children` [`ChildSpec::versao_requirement`]
915    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
916    /// on the sibling `String`-carry axes. The triple
917    /// `(nome(), versao_requirement(), restart())` jointly projects the
918    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
919    /// tree consumer that fans on per-child identity + version pin +
920    /// restart-decision keys off, closing the last unlifted per-`:children`
921    /// axis so every downstream per-`:children` reader now routes through
922    /// a typed dispatch on the substrate primitive. Named `restart()` to
923    /// match the storage field's name and the author-surface
924    /// `:children :restart` slot term verbatim; the accessor's identity
925    /// name maps onto the canonical OTP-shape per-child restart-decision-
926    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
927    /// carries.
928    ///
929    /// Declared `pub const fn` to close the last non-`const`
930    /// `Copy`-return raw-field-getter posture on the M2
931    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
932    /// of the sibling M2 per-`:supervisor`
933    /// [`SupervisorSpec::estrategia`] (converted in this commit)
934    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
935    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
936    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
937    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
938    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
939    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
940    /// downstream substrate-side `const`-context consumer of the
941    /// per-`:children` restart-decision-policy scalar (a future
942    /// module-scope `const _:() = assert!(matches!(child.restart(),
943    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
944    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
945    /// admission-webhook `const fn` per-child restart-decision floor
946    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
947    /// composer over the substrate primitive that fans on the per-child
948    /// restart-decision policy at compile time) now reaches through the
949    /// same typed dispatch on the substrate primitive at const-eval
950    /// time as at runtime. A future non-`Copy`-return promotion of the
951    /// scalar (an `Option<RestartPolicy>`-shape migration on the
952    /// per-child restart-decision axis once heterogeneous per-cluster
953    /// restart-policy overlays land, a per-tenant restart-policy-alias
954    /// table the M4 CR materializer resolves per-CR) that would drop
955    /// the `const` qualifier fails the fail-before-pass-after pin
956    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
957    /// build time rather than surfacing as a downstream consumer
958    /// regression.
959    #[must_use]
960    pub const fn restart(&self) -> RestartPolicy {
961        self.restart
962    }
963}
964
965/// Supervisor-typed slots that live alongside the standard Caixa
966/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
967/// the manifest stays a single typed form; this struct exists for
968/// validation + conversion.
969#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
970#[serde(rename_all = "camelCase")]
971pub struct SupervisorSpec {
972    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
973    #[serde(default)]
974    pub estrategia: RestartStrategy,
975
976    /// Max restarts within [`Self::restart_window`] before the
977    /// supervisor itself terminates (and its parent supervisor decides
978    /// what to do). Default 5.
979    #[serde(default = "default_max_restarts")]
980    pub max_restarts: u32,
981
982    /// Sliding window for `max_restarts`. Authored as a duration
983    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
984    /// is rejected by [`Self::validate`] — Erlang/OTP's
985    /// `MaxIntensity / Period` invariant requires a positive window
986    /// (a zero-period supervisor either trips on the first failure or
987    /// never trips, depending on operator interpretation, neither of
988    /// which is the author's intent). Omit the slot to express "no
989    /// reset"; carry a positive duration to express the sliding window.
990    #[serde(
991        default,
992        skip_serializing_if = "Option::is_none",
993        with = "duration_codec"
994    )]
995    pub restart_window: Option<Duration>,
996
997    /// Static children. Empty for `SimpleOneForOne` (children added
998    /// dynamically); required for the other three strategies.
999    #[serde(default)]
1000    pub children: Vec<ChildSpec>,
1001}
1002
1003const fn default_max_restarts() -> u32 {
1004    // Route the private serde-`#[serde(default = "…")]` helper through
1005    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1006    // `pub const` rather than the raw `5` literal — one source of truth
1007    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1008    // default across the two production consumers that currently
1009    // dispatch on it (this helper via `#[serde(default = "…")]` on
1010    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1011    // impl at line 962). Pinned by
1012    // `default_max_restarts_helper_routes_through_lifted_default` +
1013    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1014    // in the tests module; peer of the sibling caixa-core
1015    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1016    // that now routes its author-omitted `:max-restarts` arm through
1017    // the same lifted constant.
1018    SUPERVISOR_MAX_RESTARTS_DEFAULT
1019}
1020
1021/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1022/// count default for the `:supervisor :max-restarts` axis — the
1023/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1024/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1025/// so every substrate-side consumer that resolves "what
1026/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1027/// `:max-restarts` slot degrade onto?" reaches for exactly one
1028/// substrate-primitive `u32`.
1029///
1030/// The `:max-restarts` default axis has two production consumers on the
1031/// substrate side today (both prior to this lift folded onto raw `5`
1032/// literals with no compile-time link back to a shared truth): the
1033/// serde-`#[serde(default = "default_max_restarts")]` helper on
1034/// [`SupervisorSpec::max_restarts`] that every author-omitted
1035/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1036/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1037/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1038/// the composed [`SupervisorSpec`] altitude reaches through
1039/// (`feira app graph`, the future wasm-operator's per-supervisor
1040/// restart-intensity counter, the future M4
1041/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1042/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1043/// A pair of open-coded `5`s across two files that expressed no
1044/// compile-time link back to the shared OTP-canonical default — a
1045/// future rebrand of the default (a tightening to Elixir's
1046/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1047/// the operator pins through a future
1048/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1049/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1050/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1051/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1052/// per-child-cohort roadmap lands) would have had to be threaded
1053/// through both open-coded copies in lockstep or the wire-format
1054/// author-omitted arm and the view-construction author-omitted arm
1055/// would silently disagree on which restart-budget an omitted
1056/// `:max-restarts` resolves to (an author writing `:supervisor
1057/// (:max-restarts ())` would round-trip through serde with the new
1058/// default while `supervisor_view` silently continued to compose the
1059/// stale `5`, or vice versa), a two-consumer split at the composition
1060/// boundary far from the source `caixa.lisp` with no field naming the
1061/// default-drift root cause. Lifting the resolution rule to a typed
1062/// `pub const` on the substrate primitive means every downstream
1063/// consumer of the per-Supervisor default-restart-budget-count surface
1064/// reaches for exactly one substrate-primitive `u32` — the resolver's
1065/// accepted value migrates as a unit on any future axis change.
1066///
1067/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1068/// worker-supervisor default (the closest canonical OTP-shape
1069/// production reference the substrate carries, matching the sibling
1070/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1071/// this constant with on the paired sliding-window axis). Two orders of
1072/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1073/// (the upper bracket on the same axis, sibling of this lower default;
1074/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1075/// axis and now share one accessor discipline on the substrate) and
1076/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1077/// restart floor — the "one restart, then escalate" default is
1078/// deliberately loose enough to absorb a short burst of transient
1079/// child failures without escalating past the supervisor's parent
1080/// while remaining tight enough to trip the `MaxIntensity / Period`
1081/// ratio's escalation on a genuinely-stuck child within the sibling
1082/// `60s` sliding window.
1083///
1084/// Lifted as a typed `pub const` so the bound has exactly one source
1085/// of truth — the serde-side wire-format author-omitted arm at
1086/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1087/// struct-literal default field, and the caixa-core
1088/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1089/// arm all read from one place. Same shape every other typed default
1090/// in this crate carries (the sibling
1091/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1092/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1093/// sibling `:restart-window` axis, and the peer
1094/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1095/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1096/// axes).
1097pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1098
1099/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1100/// validated [`SupervisorSpec::max_restarts`] past
1101/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1102///
1103/// The typed field is `u32` (the zero-floor arm
1104/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1105/// so a programmatic struct literal
1106/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1107/// author-surface form (`:max-restarts 4294967295` or any
1108/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1109/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1110/// runtime substrate consuming the value (Erlang/OTP's
1111/// `MaxIntensity / Period` ratio, the future wasm-operator's
1112/// per-supervisor restart-intensity counter, the M4
1113/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1114/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1115/// escalation threshold is structurally so high that no realistic
1116/// restarts-per-`:restart-window` traffic shape can reach it, the
1117/// supervisor never escalates to its parent, and a bad child can loop
1118/// inside the window indefinitely with the parent supervisor structurally
1119/// never receiving the "this subtree has exceeded its restart budget"
1120/// signal the typed slot is meant to express — the canonical
1121/// "supervisor intensity declared, no escalation" footgun, exactly the
1122/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1123/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1124/// "trip the next-higher protection layer after N events in a rolling
1125/// window" counters with identical degenerate-at-the-high-end shape).
1126///
1127/// The `1000` ceiling matches the sibling
1128/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1129/// peer — same "events-per-window trip threshold" semantics, same `u32`
1130/// type, same no-op-at-the-high-end failure mode) so the M4
1131/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1132/// and the future wasm-operator's per-supervisor restart-intensity
1133/// counter reach for either field knowing the value is in `1..=1000`
1134/// without re-validating at the reconciler layer. The cap sits two
1135/// orders of magnitude above every documented Erlang/OTP production
1136/// playbook recommendation (Learn You Some Erlang's
1137/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1138/// `max_restarts: 3` default, OTP's `supervisor` callback module
1139/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1140/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1141/// default) and below the clearly-pathological "effectively no
1142/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1143/// author can plausibly want at hyperscale (a long-running supervisor
1144/// over a very-flaky pool tolerating thousands of transient restarts
1145/// before escalating), but a hard wall above which the typed policy is
1146/// structurally a no-op carried verbatim on every emitted child-restart
1147/// reconciliation contract.
1148///
1149/// Lifted as a typed `pub const` so the bound has exactly one source of
1150/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1151/// materializer's admission webhook and the wasm-operator-side
1152/// per-supervisor restart-intensity reconciler read from one place. Same
1153/// shape every other typed upper bound in this crate carries
1154/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1155/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1156/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1157/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1158/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1159/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1160pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1161
1162/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1163/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1164/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1165/// (inclusive on both ends, integer-millisecond magnitudes by the
1166/// canonical-form gate immediately preceding).
1167///
1168/// The typed field is `Option<Duration>` (the zero-floor arm
1169/// [`SupervisorError::RestartWindowZero`] already rejects
1170/// `Some(Duration::ZERO)`, and the canonical-form arm
1171/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1172/// sub-millisecond residue), so a programmatic struct literal
1173/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1174/// .. }` — 24h) and the equivalent author-surface form
1175/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1176/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1177/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1178/// A `:restart-window` value far above the documented Erlang/OTP
1179/// `MaxIntensity / Period` production-playbook band (Learn You Some
1180/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1181/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1182/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1183/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1184/// degenerates the supervisor's restart-intensity counter into a
1185/// lifetime counter: the rolling failure-counting window is structurally
1186/// so long that transient restarts are never forgotten, so the
1187/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1188/// supervisor when the child has exceeded its restart budget *within
1189/// the recent window*" to "trip the parent when the child has exceeded
1190/// its restart budget *over its lifetime*" — every transient restart
1191/// counts against the budget forever, the supervisor's reset semantic
1192/// never reaches the child, and the typed `:restart-window` slot
1193/// becomes a no-op rolling window carried on every emitted hierarchical
1194/// reconciliation contract. The canonical
1195/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1196/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1197/// `:politicas :circuit-breaker :window` axis with identical shape (both
1198/// are "rolling failure-counting window with a per-`Period` reset" Duration
1199/// axes whose lifetime-counter degenerate at the high end is the same
1200/// "the reset semantic never fires" CSE invariant violation).
1201///
1202/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1203/// the shared duration codec emits (`"<n>h"` for any integer-hour
1204/// magnitude) — every value in the canonical authoring form's
1205/// `<integer><unit>` grammar at or below this cap renders to a clean
1206/// canonical string — and matches the three sibling typed-`Duration`
1207/// caps already lifted to this surface
1208/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1209/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1210/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1211/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1212/// per-supervisor `:supervisor :restart-window` — now share a single
1213/// uniform top edge at the codec's largest emitted unit so the next
1214/// typed-slot wiring (the future wasm-operator's per-supervisor
1215/// `MaxIntensity / Period` reconciler, the M4
1216/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1217/// webhook, the `caixa-operator`'s hierarchical reconciliation
1218/// scheduler) reaches for any of the four knowing the value is in
1219/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1220/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1221/// Riak Core / RabbitMQ production-playbook recommendation band
1222/// (`5s..=300s`) and below the clearly-pathological "rolling window
1223/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1224/// a value the author can plausibly want for a very-low-traffic
1225/// long-tail failure-restart window over a hyperscale-flaky child pool,
1226/// but a hard wall above which the rolling-window contract is
1227/// structurally a lifetime-counter contract.
1228///
1229/// Lifted as a typed `pub const` so the bound has exactly one source
1230/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1231/// materializer's admission webhook, the wasm-operator-side
1232/// per-supervisor `MaxIntensity / Period` reconciler, and the
1233/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1234/// from one place. Same shape every other typed upper bound in this
1235/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1236/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1237/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1238/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1239/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1240/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1241/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1242/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1243/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1244pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1245
1246/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1247/// default for the `:supervisor :restart-window` axis — the canonical
1248/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1249/// worker-supervisor default, extracted as a typed `pub const` so every
1250/// substrate-side consumer that resolves "what
1251/// [`SupervisorSpec::restart_window`] value does an author-omitted
1252/// `:restart-window` slot degrade onto?" reaches for exactly one
1253/// substrate-primitive [`Duration`].
1254///
1255/// The `:restart-window` default axis has one production consumer on the
1256/// substrate side today: the [`Default for SupervisorSpec`] impl's
1257/// struct-literal `restart_window` field, which prior to this lift folded
1258/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1259/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1260/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1261/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1262/// *not* fall back to this default on the sibling `:restart-window` axis
1263/// — an author-omitted `:supervisor :restart-window` composes to
1264/// `restart_window: None` (the shared codec's soft-swallow shape),
1265/// keeping author-declared intent ("no reset — never escalate on rolling
1266/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1267/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1268/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1269/// default was split across two files with no compile-time link between
1270/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1271/// `MaxIntensity` half at the substrate primitive while the `Period`
1272/// half rode as an open-coded literal at the composition site, so a
1273/// future coherent rebrand of the paired canonical (a tightening to
1274/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1275/// per-cluster overlay the operator pins through a future
1276/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1277/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1278/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1279/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1280/// roadmap lands) would have had to migrate the `MaxIntensity` half
1281/// through the lifted constant and the `Period` half through a raw
1282/// literal in lockstep or the two halves of the same OTP-canonical
1283/// default would silently drift out of pairing. Lifting the resolution
1284/// rule to a typed `pub const` on the substrate primitive means the
1285/// paired OTP-canonical default migrates as one unit on any future
1286/// axis change.
1287///
1288/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1289/// worker-supervisor default (the closest canonical OTP-shape
1290/// production reference the substrate carries, matching the paired
1291/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1292/// constant is the `Period` denominator of on the same
1293/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1294/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1295/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1296/// this lower default; both are typed [`Duration`] const bounds on the
1297/// `:supervisor :restart-window` axis and now share one accessor
1298/// discipline on the substrate) and above the OTP-`supervisor`
1299/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1300/// rolling window" default is deliberately loose enough to absorb a
1301/// short burst of transient child failures without escalating past the
1302/// supervisor's parent while remaining tight enough for the paired
1303/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1304/// stuck child within a human-scale observation window.
1305///
1306/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1307/// exactly one source of truth on each half — the sibling
1308/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1309/// `Period` `60s` half now share the same substrate-primitive lift
1310/// discipline. Same shape every other typed default in this crate
1311/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1312/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1313/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1314/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1315/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1316/// caixa-flux / caixa-helm rendering axes).
1317pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1318
1319/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1320/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1321/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1322/// worker-supervisor default, extracted as a typed `pub const` so every
1323/// substrate-side consumer that resolves "what
1324/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1325/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1326/// primitive [`RestartStrategy`].
1327///
1328/// The `:estrategia` default axis has three production consumers on the
1329/// substrate side today: the [`Default for RestartStrategy`] impl's
1330/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1331/// `estrategia` field, and the
1332/// [`crate::manifest::Caixa::supervisor_view`] fold's
1333/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1334/// collapse arm — three entry points onto the same OTP-canonical
1335/// `one_for_one` value that prior to this lift folded onto a raw
1336/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1337/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1338/// with no compile-time link back to the paired
1339/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1340/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1341/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1342/// triple was split across three altitudes with no compile-time link
1343/// between the halves: the `MaxIntensity` half rode through the lifted
1344/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1345/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1346/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1347/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1348/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1349/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1350/// intensity/period; an OTP `rest_for_one` widening once the substrate
1351/// discovers startup-order-coupled child cohorts as the more common
1352/// worker-supervisor default; a per-cluster overlay the operator pins
1353/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1354/// §III.2 supervision-canary roadmap acknowledges) would have had to
1355/// migrate the `MaxIntensity` + `Period` halves through the lifted
1356/// constants and the `one_for_one` half through an open-coded arm in
1357/// lockstep or the three halves of the same OTP-canonical default would
1358/// silently drift out of pairing. Lifting the resolution rule to a typed
1359/// `pub const` on the substrate primitive means the paired OTP-canonical
1360/// worker-supervisor default migrates as one unit on any future axis
1361/// change.
1362///
1363/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1364/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1365/// closest canonical OTP-shape production reference the substrate
1366/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1367/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1368/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1369/// failed child, leaving siblings untouched — is the default for tree-of-
1370/// independent-workers use cases the substrate's [`RestartStrategy`]
1371/// discriminator's own docstring already carries as the default arm; it
1372/// composes with the `{5, 60}` restart-intensity ratio to name the same
1373/// substrate-canonical "canonical worker-supervisor" shape the paired
1374/// halves close on their respective axes.
1375///
1376/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1377/// exactly one source of truth on each of its three halves — the sibling
1378/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1379/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1380/// this `one_for_one` strategy half now share the same substrate-
1381/// primitive lift discipline. Same shape every other typed default in
1382/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1383/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1384/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1385/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1386/// upper caps on the paired sibling axes, and the peer
1387/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1388/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1389pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1390
1391/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1392/// default for the `:children :restart` axis — the OTP `permanent`
1393/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1394/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1395/// `pub const` so every substrate-side consumer that resolves "what
1396/// [`ChildSpec::restart`] variant does an author-omitted `:children
1397/// :restart` slot degrade onto?" reaches for exactly one substrate-
1398/// primitive [`RestartPolicy`].
1399///
1400/// Completes the OTP-shape supervisor-tree default set at the substrate
1401/// primitive. The per-`:supervisor` axis already carries all three of its
1402/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1403/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1404/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1405/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1406/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1407/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1408/// the M2 `:supervisor` slot family. The split mattered because the two
1409/// axes resolve *together* on every author-omitted supervisor: a
1410/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1411/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1412/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1413/// `permanent` through an open-coded enum arm, so a future coherent
1414/// rebrand of the OTP-shape default set (an Elixir-shaped
1415/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1416/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1417/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1418/// once the substrate discovers clean-completion-aware children as the
1419/// more common child shape) would have had to migrate three halves
1420/// through typed constants and the fourth through a raw enum arm in
1421/// lockstep or the supervisor-level and child-level defaults would
1422/// silently drift apart.
1423///
1424/// The `:children :restart` default axis has two production consumers on
1425/// the substrate side today: the [`Default for RestartPolicy`] impl's
1426/// return arm, and the serde-side `#[serde(default)]` on
1427/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1428/// :restart` slot through that same impl. Both now key off this one
1429/// substrate primitive, so the future wasm-operator's per-child post-exit
1430/// restart-decision branch, the future M4
1431/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1432/// admission webhook, and the `caixa-operator`'s hierarchical
1433/// reconciliation scheduler's per-child fan-out all reach for one typed
1434/// identifier when they resolve an omitted per-child restart posture.
1435///
1436/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1437/// worker-child restart type — always restart the child regardless of how
1438/// it died, the canonical posture for long-running services that must
1439/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1440/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1441/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1442/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1443/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1444/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1445/// one-shot / clean-completion-aware postures an author declares
1446/// explicitly, never a posture an omitted slot should silently assume.
1447pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1448
1449/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1450/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1451/// `pub const fn` constructor rather than a struct-literal cascade over
1452/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1453/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1454/// lifted consts — one source of truth for the Erlang/OTP-canonical
1455/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1456/// paths every downstream consumer already reaches through (the
1457/// hand-authored-until-now [`Default::default`] the
1458/// `..SupervisorSpec::default()` struct-update-syntax on every
1459/// one-axis-under-test fixture in this crate's test module rests on,
1460/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1461/// every `const`-context consumer reaches through).
1462///
1463/// Extends the [`Default`]-through-const-ctor fold discipline the
1464/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1465/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1466/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1467/// and [`crate::BehaviorSpec`]
1468/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1469/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1470/// typed-slot spec family — extended here onto the M2 supervisor-slot
1471/// [`SupervisorSpec`] whose canonical baseline is not "everything
1472/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1473/// supervisor triple. The `empty()` peer's naming did not fit
1474/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1475/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1476/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1477/// the sibling `Option`-only slots fold to), so this peer is named
1478/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1479/// existing per-arm pin tests
1480/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1481/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1482/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1483/// already reach for. Pinned load-bearing by
1484/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1485/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1486/// [`PartialEq`], sharpening the sibling
1487/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1488/// pins from a per-field lift into a whole-struct one-source-of-truth
1489/// pin — the derived-until-now [`Default::default`] and the
1490/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1491/// construction, not by coincidence).
1492impl Default for SupervisorSpec {
1493    #[inline]
1494    fn default() -> Self {
1495        Self::otp_canonical()
1496    }
1497}
1498
1499impl SupervisorSpec {
1500    /// `const`-context peer of the [`Default for SupervisorSpec`]
1501    /// impl (which routes through this constructor) — returns the
1502    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1503    /// baseline this crate reaches for in every fixture-builder
1504    /// `..SupervisorSpec::default()` struct-update expression and
1505    /// every downstream `SupervisorSpec::default()` seed.
1506    ///
1507    /// Each field routes through the same substrate-canonical
1508    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1509    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1510    /// per-arm pin tests
1511    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1512    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1513    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1514    /// already assert, so a future coherent rebrand of the OTP-canonical
1515    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1516    /// cluster overlay via a future `:restart-window-overrides` slot, a
1517    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1518    /// absorption roadmap acknowledges) migrates through three typed
1519    /// constants in lockstep, and the paired [`Default`] impl inherits
1520    /// every future extension by construction.
1521    ///
1522    /// `pub const fn` rather than the derived-style `Default::default`
1523    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1524    /// [`Default::default`] is not `const` on stable Rust, and
1525    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1526    /// every consumer through a [`Clone::clone`]. The `pub const fn`
1527    /// discipline lets `const`-context callers construct the OTP-
1528    /// canonical baseline at compile time without runtime dispatch on
1529    /// the derived [`Default::default`], the same posture the sibling
1530    /// [`crate::LimitsSpec::empty`] (9739971) /
1531    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1532    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1533    /// spec `pub const fn` constructors carry on the sibling
1534    /// "everything `None`" baseline axis.
1535    ///
1536    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1537    /// of the derived-style [`Default`]" family — sibling of the
1538    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1539    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1540    /// baseline" trio, extended here onto the M2 supervisor-slot
1541    /// [`SupervisorSpec`] whose canonical baseline is not "everything
1542    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1543    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1544    /// than `empty()` to name the actual invariant the return value
1545    /// pins — the same phrasing already used in the per-arm pin tests
1546    /// on this file. Pinned load-bearing by
1547    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1548    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1549    #[must_use]
1550    pub const fn otp_canonical() -> Self {
1551        Self {
1552            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1553            max_restarts: default_max_restarts(),
1554            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1555            children: Vec::new(),
1556        }
1557    }
1558
1559    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1560    /// sibling-restart-strategy scalar accessor every consumer that
1561    /// dispatches on the supervisor's per-sibling restart-decision shape
1562    /// keys off — returns the author-declared `:supervisor :estrategia`
1563    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1564    /// the typed slot's own [`RestartStrategy`] storage.
1565    ///
1566    /// The `:supervisor :estrategia` slot carries the closed-set
1567    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1568    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1569    /// [`RestartStrategy::OneForAll`] — restart every child on any child
1570    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1571    /// [`RestartStrategy::RestForOne`] — restart the failed child and
1572    /// every child started after it, the Erlang/OTP `rest_for_one`
1573    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1574    /// dynamic children of the same shape, the Erlang/OTP
1575    /// `simple_one_for_one` per-session default) that every downstream
1576    /// consumer of the Supervisor's per-sibling restart-decision fan-out
1577    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1578    /// paired coherently with the sibling `:children` axis
1579    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1580    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1581    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1582    /// downstream consumer that reads the strategy keys off this scalar
1583    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1584    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1585    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1586    /// `estrategia:` field, the future `feira app graph` per-Supervisor
1587    /// strategy print line, the future wasm-operator's per-supervisor
1588    /// sibling-restart-strategy branch, the future M4
1589    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1590    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1591    /// reconciliation scheduler's per-strategy fan-out).
1592    ///
1593    /// Prior to this lift the `.estrategia` field was accessed inline at
1594    /// two production sites in `caixa-core/src/supervisor.rs` — the
1595    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1596    /// `match self.estrategia { … }` partition dispatch, and the
1597    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1598    /// carrier at `estrategia: self.estrategia` — two open-coded
1599    /// field-accesses that expressed no compile-time link back to the
1600    /// typed slot. A future extension of the `:supervisor :estrategia`
1601    /// axis to a richer author surface (a per-cluster strategy override
1602    /// the operator pins through a future `:supervisor :estrategia-overrides`
1603    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1604    /// acknowledges, a per-tenant strategy-alias table the M4 CR
1605    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1606    /// derivation the future adaptive-supervision engine computes from
1607    /// child-failure-history topology, a per-child-cohort strategy split
1608    /// the future `RestForCohort` extension acknowledged by the
1609    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1610    /// would have had to be threaded through every open-coded copy in
1611    /// lockstep — one consumer reading the raw variant while a peer read
1612    /// the operator-resolved variant would silently split the
1613    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1614    /// the actual partition-dispatch input the empty-children refusal
1615    /// arm reached under, a two-consumer split at the validator far from
1616    /// the source `caixa.lisp` with no field naming the strategy-drift
1617    /// root cause. Lifting the resolution rule to a typed method on the
1618    /// substrate primitive means every downstream consumer of the
1619    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1620    /// reaches for exactly one typed dispatch — the resolver's accept-set
1621    /// migrates as a unit on any future axis addition.
1622    ///
1623    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1624    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1625    /// per-`:placement` distribution-strategy axis — same "one typed
1626    /// dispatch on the substrate primitive, thin projections at each
1627    /// consumer" discipline extended onto the M2 supervisor-slot
1628    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1629    /// scalar axis. The two typed axes (`Placement::estrategia` on the
1630    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1631    /// Supervisor side) now share one accessor discipline for the shared
1632    /// substrate concept "a `Copy`-projected closed-set enum-arm
1633    /// discriminator that partitions the downstream renderer's per-arm
1634    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1635    /// `SupervisorSpec` type — companion to the sibling per-`:children`
1636    /// [`crate::ChildSpec::nome`] (57c61d0) /
1637    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1638    /// scalar accessors on the sibling per-`:children` `String`-carry
1639    /// axes. Named `estrategia()` to match the storage field's name and
1640    /// the peer [`crate::Placement::estrategia`] method-name discipline
1641    /// verbatim; the accessor's identity name maps onto the canonical
1642    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1643    /// docstring already carries.
1644    ///
1645    /// Declared `pub const fn` to close the M2 supervisor-slot
1646    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1647    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1648    /// (converted in this commit) `Copy`-composite-enum accessor, peer
1649    /// of the sibling M2 per-`:supervisor`
1650    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1651    /// already lifted, and mirror of the peer M3 mesh-slot
1652    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1653    /// `Copy`-return `pub const fn` scalar accessor whose method-name
1654    /// discipline this accessor was authored to match. Every downstream
1655    /// substrate-side `const`-context consumer of the per-`:supervisor`
1656    /// sibling-restart-strategy scalar (a future module-scope `const
1657    /// _:() = assert!(matches!(sup.estrategia(),
1658    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1659    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1660    /// admission-webhook `const fn` per-supervisor strategy-arm floor
1661    /// over a typed [`SupervisorSpec`], any future `const fn`
1662    /// supervisor-tree composer over the substrate primitive that fans
1663    /// on the sibling-restart-strategy at compile time) now reaches
1664    /// through the same typed dispatch on the substrate primitive at
1665    /// const-eval time as at runtime. A future non-`Copy`-return
1666    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1667    /// migration once the substrate grows per-cluster strategy overlays
1668    /// the [`SupervisorSpec`] docstring already anticipates, a
1669    /// per-tenant strategy-alias table the M4 CR materializer resolves
1670    /// per-CR) that would drop the `const` qualifier fails the
1671    /// fail-before-pass-after pin
1672    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1673    /// caixa-core build time rather than surfacing as a downstream
1674    /// consumer regression.
1675    #[must_use]
1676    pub const fn estrategia(&self) -> RestartStrategy {
1677        self.estrategia
1678    }
1679
1680    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1681    /// `MaxIntensity` restart-budget scalar accessor every consumer that
1682    /// reads the supervisor's per-`:restart-window` restart-budget count
1683    /// keys off — returns the author-declared `:supervisor :max-restarts`
1684    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1685    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1686    /// borrow of `&self` past the call). Non-optional (the `u32` field
1687    /// carries the restart-budget count as a required axis with a
1688    /// [`default_max_restarts`]-supplied default; the zero-floor arm
1689    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1690    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1691    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1692    ///
1693    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1694    /// `MaxIntensity` restart-budget count that pairs with the sibling
1695    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1696    /// restart-intensity ratio the supervisor trips its own escalation on
1697    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1698    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1699    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1700    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1701    /// upper-cap bracket at
1702    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1703    /// wasm-operator's per-supervisor restart-intensity counter's
1704    /// budget-vs-count comparator, the future M4
1705    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1706    /// webhook, the `caixa-operator`'s hierarchical reconciliation
1707    /// scheduler's per-supervisor escalation-decision branch, every
1708    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1709    /// offending count verbatim for `feira lint` rendering).
1710    ///
1711    /// Prior to this lift the `.max_restarts` field was accessed inline at
1712    /// one production site in `caixa-core/src/supervisor.rs` — the
1713    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1714    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1715    /// that expressed no compile-time link back to the typed slot. A
1716    /// future extension of the `:max-restarts` axis to a richer author
1717    /// surface (a per-cluster restart-budget override the operator pins
1718    /// through a future `:supervisor :max-restarts-overrides` slot the
1719    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1720    /// a per-tenant restart-budget-alias table the M4 CR materializer
1721    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
1722    /// the future adaptive-supervision engine computes from child-failure-
1723    /// history topology, a promotion of the plain `u32` count to a richer
1724    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1725    /// budget-partition slot comes into scope) would have had to be
1726    /// threaded through every open-coded copy in lockstep or the validate
1727    /// gate and the future M4 emit path would silently disagree on which
1728    /// restart-budget count a given supervisor resolves to — an author's
1729    /// `:max-restarts 5` would satisfy validate while the emit path
1730    /// silently read a drifted other value (a `:max-restarts 10000`
1731    /// no-op supervisor at the emit boundary would carry the author's
1732    /// declared `5` verbatim in `feira lint` output while the future
1733    /// wasm-operator's restart-intensity counter operated under the
1734    /// drifted count), a two-consumer split at the validator far from the
1735    /// source `caixa.lisp` with no field naming the restart-budget-drift
1736    /// root cause. Lifting the resolution rule to a typed method on the
1737    /// substrate primitive means every downstream consumer of the
1738    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1739    /// for exactly one typed dispatch — the resolver's accept-set migrates
1740    /// as a unit on any future axis addition.
1741    ///
1742    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1743    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1744    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1745    /// outlier-detection trip-threshold axis — same "one typed dispatch on
1746    /// the substrate primitive, thin projections at each consumer"
1747    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1748    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1749    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1750    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1751    /// one accessor discipline for the shared substrate concept "a
1752    /// `Copy`-projected required `u32` count that trips the next-higher
1753    /// protection layer after N events in a rolling window" — both are
1754    /// counters with identical degenerate-at-the-high-end shape and share
1755    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1756    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1757    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1758    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1759    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1760    /// the storage field's name verbatim and the peer
1761    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1762    /// accessor's identity maps onto the canonical OTP-shape supervision
1763    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1764    /// already carries.
1765    #[must_use]
1766    pub const fn max_restarts(&self) -> u32 {
1767        self.max_restarts
1768    }
1769
1770    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1771    /// `Period` sliding-window scalar accessor every consumer of the
1772    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1773    /// keys off — returns the author-declared `:supervisor :restart-window`
1774    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1775    /// the typed slot's own `Option<Duration>` storage (`Duration` is
1776    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1777    /// value; no borrow of `&self` past the call). `None` when the slot is
1778    /// absent (the canonical "never reset — every restart across the
1779    /// supervisor's lifetime counts against the sibling `:max-restarts`
1780    /// budget" sentinel the field's own docstring names and the peer
1781    /// `validate_accepts_none_restart_window` pin locks in on the
1782    /// [`SupervisorSpec::validate`] entry-side).
1783    ///
1784    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1785    /// `Period` sliding-observation-interval that pairs with the sibling
1786    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1787    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1788    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1789    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1790    /// default). The typed slot's `Option<Duration>` accept-set —
1791    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1792    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1793    /// `Period > 0`; a zero period either trips on the first failure or
1794    /// never trips depending on operator interpretation, neither of which
1795    /// is the author's intent — omit the slot to express "no reset";
1796    /// carry a positive duration to express the sliding window),
1797    /// integer-millisecond canonical form enforced through
1798    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1799    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1800    /// future wasm-operator's per-supervisor restart-intensity counter
1801    /// quantizes at milliseconds), upper-bounded by
1802    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1803    /// supervisor rolling window any operationally-reachable supervisor
1804    /// can honor without spanning multiple scheduler epochs the
1805    /// hierarchical-reconciliation scheduler treats as independent) —
1806    /// maps onto the future wasm-operator (M3) per-supervisor
1807    /// restart-intensity counter's rolling-observation-interval, the
1808    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1809    /// per-`spec.restartWindow` admission webhook, and the sibling
1810    /// `duration_codec`-serialized wire scalar every downstream consumer
1811    /// of the supervisor's per-`:supervisor` restart-intensity denominator
1812    /// keys off.
1813    ///
1814    /// Prior to this lift the `.restart_window` field was accessed inline
1815    /// at one production site in `caixa-core/src/supervisor.rs` — the
1816    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1817    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1818    /// open-coded field-access that expressed no compile-time link back to
1819    /// the typed slot. A future extension of the `:restart-window` axis to
1820    /// a richer author surface (a per-cluster restart-window override the
1821    /// operator pins through a future `:supervisor :restart-window-overrides`
1822    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1823    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
1824    /// materializer resolves per-CR, a per-supervisor dynamic
1825    /// restart-window derivation the future adaptive-supervision engine
1826    /// computes from child-failure-history topology, a promotion of the
1827    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
1828    /// pair once Erlang/OTP's per-child-cohort observation-interval-
1829    /// partition slot comes into scope) would have had to be threaded
1830    /// through every open-coded copy in lockstep or the validate gate and
1831    /// the future M4 emit path would silently disagree on which
1832    /// restart-window a given supervisor resolves to — an author's
1833    /// `:restart-window "60s"` would satisfy validate while the emit path
1834    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
1835    /// authored slot at the emit boundary would carry the author's
1836    /// declared window verbatim in `feira lint` output while the future
1837    /// wasm-operator's restart-intensity counter operated under a
1838    /// drifted window, or vice versa: an author's `:restart-window ()`
1839    /// would carry the "never reset" sentinel through validate while the
1840    /// emit path silently substituted a default sliding window), a
1841    /// two-consumer split at the validator far from the source
1842    /// `caixa.lisp` with no field naming the restart-window-drift root
1843    /// cause. Lifting the resolution rule to a typed method on the
1844    /// substrate primitive means every downstream consumer of the
1845    /// Supervisor's per-`:supervisor` restart-intensity-denominator
1846    /// surface reaches for exactly one typed dispatch — the resolver's
1847    /// accept-set migrates as a unit on any future axis addition.
1848    ///
1849    /// Third `Copy`-return accessor on the M2 supervisor-slot
1850    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
1851    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
1852    /// payload rather than a `Copy`-scalar, and the per-`:children`
1853    /// [`crate::ChildSpec::nome`] (57c61d0) /
1854    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1855    /// scalar accessors already close the per-element `String`-carry
1856    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
1857    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
1858    /// per-outermost-call wall-clock-deadline axis and the peer M3
1859    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
1860    /// accessor on the `:politicas` slot's per-call-deadline axis — all
1861    /// three share the shared substrate concept "a `Copy`-projected
1862    /// optional `Duration` that carries a positive integer-millisecond
1863    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
1864    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
1865    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
1866    /// bracket-helper the three axes each route through. Named
1867    /// `restart_window()` to match the storage field's name verbatim and
1868    /// the peer [`crate::LimitsSpec::wall_clock`] /
1869    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
1870    /// accessor's identity maps onto the canonical OTP-shape supervision
1871    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
1872    /// already carries.
1873    #[must_use]
1874    pub const fn restart_window(&self) -> Option<Duration> {
1875        self.restart_window
1876    }
1877
1878    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
1879    /// static-child-list slice accessor every consumer that walks the
1880    /// supervisor's declared child set keys off — returns the author-
1881    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
1882    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
1883    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
1884    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
1885    /// through). Non-optional: an empty slice is the load-bearing
1886    /// "author declared `:children ()`" sentinel every consumer of the
1887    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
1888    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
1889    /// three strategies require a non-empty slice — the paired
1890    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
1891    /// [`SupervisorError::NoChildren`] refusal cascade pins the
1892    /// partition on both arms).
1893    ///
1894    /// The `:supervisor :children` slot carries the OTP-shaped static
1895    /// child list the supervisor materializes one ComputeUnit per
1896    /// entry from — the Erlang/OTP `supervisor:init/1`'s
1897    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
1898    /// through the tatara-lisp `:children` author surface onto a typed
1899    /// `Vec<ChildSpec>` whose per-element `(nome(),
1900    /// versao_requirement(), restart)` triple the per-child
1901    /// [`SupervisorSpec::validate`] loop already gates through the
1902    /// lifted [`ChildSpec::nome`] (57c61d0) /
1903    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
1904    /// Every downstream consumer that fans on the static child list
1905    /// keys off this slice (the [`SupervisorSpec::validate`]
1906    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
1907    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
1908    /// per-child DNS-1123 / semver-requirement / duplicate-detection
1909    /// fan-out loop, every future wasm-operator (M3) per-supervisor
1910    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
1911    /// materialization loop, the future M4
1912    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1913    /// admission-webhook fan-out, the future `feira app graph`
1914    /// per-supervisor tree-print traversal).
1915    ///
1916    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
1917    /// inline at three production sites in `caixa-core/src/supervisor.rs`
1918    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
1919    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
1920    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
1921    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
1922    /// validate loop's `for child in &self.children` traversal head —
1923    /// three open-coded field-accesses that expressed no compile-time
1924    /// link back to the typed slot. A future extension of the
1925    /// `:supervisor :children` axis to a richer author surface (a
1926    /// per-cluster child-set overlay the operator pins through a future
1927    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
1928    /// supervision-canary roadmap acknowledges, a per-tenant
1929    /// child-set-alias table the M4 CR materializer resolves per-CR,
1930    /// a per-supervisor dynamic-child derivation the future adaptive-
1931    /// supervision engine computes from child-failure-history topology,
1932    /// a promotion of the plain `Vec<ChildSpec>` to a richer
1933    /// `{static, dynamic}` partition once Erlang/OTP's
1934    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
1935    /// would have had to be threaded through all three open-coded copies
1936    /// in lockstep or one consumer would silently disagree with the
1937    /// peers on which child-set a given supervisor resolves to — the
1938    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
1939    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
1940    /// would silently split the partition-dispatch's two-arm coherence
1941    /// (a supervisor that satisfies neither arm's precondition, or that
1942    /// satisfies both, at the cost of the paired
1943    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
1944    /// silently drifting from the per-child validate loop's actual
1945    /// traversal input), a three-consumer split at the validator far
1946    /// from the source `caixa.lisp` with no field naming the
1947    /// child-set-drift root cause. Lifting the resolution rule to a
1948    /// typed method on the substrate primitive means every downstream
1949    /// consumer of the Supervisor's per-`:supervisor` static-child-list
1950    /// surface reaches for exactly one typed dispatch — the resolver's
1951    /// accept-set migrates as a unit on any future axis addition.
1952    ///
1953    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
1954    /// — the seed for the same "one typed dispatch on the substrate
1955    /// primitive, thin projections at each consumer" discipline the
1956    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
1957    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
1958    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
1959    /// onto the first `Vec`-carry axis on the substrate. The four peer
1960    /// `Vec`-carry axes still unlifted at the time of this seed —
1961    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
1962    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
1963    /// (`Vec<Membro>` per-Aplicacao member list),
1964    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
1965    /// per-Aplicacao WIT-typed edge list),
1966    /// [`crate::UpgradeFromEntry::instructions`]
1967    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
1968    /// — inherit this accessor's discipline as future compounding runs
1969    /// migrate their consumers onto the shared slice-return shape.
1970    /// Fourth (and final) accessor on the M2 supervisor-slot
1971    /// `SupervisorSpec` type, sibling to the three `Copy`-return
1972    /// [`SupervisorSpec::estrategia`] (eafb619) /
1973    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
1974    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
1975    /// the last unlifted per-`:supervisor` field axis (the
1976    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
1977    /// per-`:supervisor` reader now routes through a typed dispatch on
1978    /// the substrate primitive. Named `children()` to match the storage
1979    /// field's name verbatim and the tatara-lisp author-surface term
1980    /// (`:children`) the field's own docstring already carries; the
1981    /// accessor's identity maps onto the canonical OTP-shape
1982    /// supervision vocabulary the [`SupervisorSpec::children`] field's
1983    /// docstring already reaches for ("Static children ..."). Returns
1984    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
1985    /// consumer of the child list treats it as a read-only sequence —
1986    /// the slice-view is the narrowest borrow that supports every
1987    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
1988    /// index, `.len()`) without leaking the backing `Vec`'s
1989    /// grow/push/reserve surface that no consumer of the typed view
1990    /// reaches for (the storage-side `Vec` remains reachable through
1991    /// the `pub children` field for the mutation-carrying
1992    /// `Caixa::supervisor_view` fold-in path in
1993    /// `manifest.rs:supervisor_view`).
1994    #[must_use]
1995    pub const fn children(&self) -> &[ChildSpec] {
1996        self.children.as_slice()
1997    }
1998
1999    /// Validate the supervisor's typed shape — strategy ↔ children
2000    /// invariants, max_restarts > 0, restart_window > 0 when set,
2001    /// per-child non-empty + duplicate-free names.
2002    ///
2003    /// Mirrors the value-shape discipline applied to every other
2004    /// typed slot:
2005    ///
2006    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2007    ///     same "0 means the opposite of what you think" footgun
2008    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2009    ///     timeout as `infinite`), `:politicas :circuit-breaker
2010    ///     :window`, and `:limits :wall-clock`. The
2011    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2012    ///     `supervisor` requires `Period > 0`; a zero period either
2013    ///     trips on the first failure or never trips depending on
2014    ///     operator interpretation, neither of which is the
2015    ///     author's intent. Omit `:restart-window` to express "no
2016    ///     reset"; carry a positive duration to express the window.
2017    ///   - duplicate `:children` `:caixa` names are the same
2018    ///     graph-node-set / multiset distinction closed for
2019    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2020    ///     and `:entrada :paths` (eb3456d). Two children with the
2021    ///     same `:caixa` materialize as two ComputeUnits with the
2022    ///     same name in the cluster's HelmRelease values, one
2023    ///     silently overwriting the other. Erlang/OTP's
2024    ///     `child_spec.id` is required-unique per supervisor;
2025    ///     pleme-io enforces the same set-not-multiset shape on
2026    ///     `:caixa` (the load-bearing identity in our renderer).
2027    pub fn validate(&self) -> Result<(), SupervisorError> {
2028        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2029        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2030        // error carrier's `estrategia:` field through the lifted
2031        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2032        // `self.estrategia` field access — the two production consumers
2033        // of the per-`:supervisor` sibling-restart-strategy scalar now
2034        // key off exactly one typed dispatch on the substrate primitive,
2035        // so any future rebrand on the axis (a per-cluster strategy
2036        // override the operator pins through a future `:supervisor
2037        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2038        // the M4 CR materializer resolves per-CR) migrates as a single
2039        // caixa-core edit rather than a coordinated rewrite of the two
2040        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2041        // (921fe1b) four-consumer migration on the per-`:placement`
2042        // distribution-strategy axis.
2043        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2044        // dispatch's paired `.is_empty()` cross-slot refusal probes
2045        // (the `SimpleOneForOne`-arm
2046        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2047        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2048        // refusal) through the lifted [`SupervisorSpec::children`]
2049        // slice-return accessor rather than the raw `self.children`
2050        // field access — the two paired production consumers of the
2051        // per-`:supervisor` static-child-list scalar-shape now key off
2052        // exactly one typed dispatch on the substrate primitive, so any
2053        // future rebrand on the axis (a per-cluster child-set overlay
2054        // the operator pins through a future `:supervisor
2055        // :children-overrides` slot, a per-tenant child-set-alias table
2056        // the M4 CR materializer resolves per-CR) migrates as a single
2057        // caixa-core edit rather than a coordinated rewrite of the
2058        // paired arms — first slice-return migration on any typed slot,
2059        // seed for the peer per-`:placement :clusters`,
2060        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2061        // :instructions` `Vec`-carry axes.
2062        match self.estrategia() {
2063            RestartStrategy::SimpleOneForOne => {
2064                // SimpleOneForOne: children added at runtime. Static
2065                // list must be empty (one shape declared elsewhere).
2066                if !self.children().is_empty() {
2067                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2068                }
2069            }
2070            _ => {
2071                if self.children().is_empty() {
2072                    return Err(SupervisorError::no_children(self.estrategia()));
2073                }
2074            }
2075        }
2076        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2077        // axis. See [`crate::render::require_positive_bounded_u32`] for
2078        // the ordering discipline (zero-floor arm strictly precedes cap
2079        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2080        // diagnostic with its counter-axis remediation directly named,
2081        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2082        // cap-arm miss). Until this bracket landed the top edge ran all
2083        // the way to `u32::MAX` and a struct-literal
2084        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2085        // equivalent author-surface `:max-restarts 100000` /
2086        // `:max-restarts 4294967295` typo landing in the slot) silently
2087        // passed validate. The runtime substrate consuming the value
2088        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2089        // wasm-operator's per-supervisor restart-intensity counter, the
2090        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2091        // admission webhook) then turned a typed `:max-restarts`
2092        // policy into a no-op supervisor: the escalation threshold is
2093        // structurally so high that no realistic
2094        // restarts-per-`:restart-window` traffic shape can reach it,
2095        // the supervisor never escalates to its parent, and a bad
2096        // child can loop inside the window indefinitely with the
2097        // parent supervisor structurally never receiving the "this
2098        // subtree has exceeded its restart budget" signal the typed
2099        // slot is meant to express. The bracket set is
2100        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2101        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2102        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2103        // both are "trip the next-higher protection layer after N
2104        // events in a rolling window" counters with identical
2105        // degenerate-at-the-high-end shape and now share one canonical
2106        // bracket helper. The bracket precedes the sibling
2107        // `:restart-window` zero-floor / canonical-millisecond arms so
2108        // an over-cap `max_restarts` paired with a structurally invalid
2109        // window surfaces the bracket diagnostic first, mirroring the
2110        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2111        // ordering on the peer `:politicas :circuit-breaker` slot.
2112        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2113        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2114        // accessor rather than the raw `self.max_restarts` field access —
2115        // the one production consumer of the per-`:supervisor`
2116        // restart-budget-count scalar now keys off exactly one typed
2117        // dispatch on the substrate primitive, so any future rebrand on
2118        // the axis (a per-cluster restart-budget override the operator
2119        // pins through a future `:supervisor :max-restarts-overrides`
2120        // slot, a per-tenant restart-budget-alias table the M4 CR
2121        // materializer resolves per-CR) migrates as a single caixa-core
2122        // edit rather than a coordinated rewrite — sibling of the peer M3
2123        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2124        // the per-`:politicas :circuit-breaker :max-failures` axis.
2125        crate::render::require_positive_bounded_u32(
2126            self.max_restarts(),
2127            SUPERVISOR_MAX_RESTARTS_MAX,
2128            || SupervisorError::ZeroMaxRestarts,
2129            SupervisorError::max_restarts_exceeds_cap,
2130        )?;
2131        // Route the [`SupervisorSpec::validate`] `:restart-window`
2132        // zero-floor + integer-millisecond canonical-form + upper-cap
2133        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2134        // accessor rather than the raw `self.restart_window` field access —
2135        // the one production consumer of the per-`:supervisor`
2136        // restart-intensity-denominator scalar now keys off exactly one
2137        // typed dispatch on the substrate primitive, so any future rebrand
2138        // on the axis (a per-cluster restart-window override the operator
2139        // pins through a future `:supervisor :restart-window-overrides`
2140        // slot, a per-tenant restart-window-alias table the M4 CR
2141        // materializer resolves per-CR) migrates as a single caixa-core
2142        // edit rather than a coordinated rewrite — sibling of the peer M2
2143        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2144        // on the per-`:limits :wall-clock` axis and the peer M3
2145        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2146        // per-`:politicas :timeout` axis.
2147        if let Some(w) = self.restart_window() {
2148            // Zero-floor + integer-millisecond canonical-form +
2149            // upper-cap bracket on the typed `:restart-window` axis.
2150            // See
2151            // [`crate::render::require_positive_canonical_bounded_duration`]
2152            // for the full three-arm ordering discipline (zero-floor
2153            // strictly precedes canonical-form so `Duration::ZERO`
2154            // surfaces the self-locating `RestartWindowZero`
2155            // diagnostic; canonical-form strictly precedes the cap arm
2156            // so a sub-millisecond above-cap value surfaces the more
2157            // fundamental round-trip-shape diagnostic first) and the
2158            // three peer typed-`Duration` sites that share this
2159            // canonical bracket ([`crate::MeshPolicy::timeout`],
2160            // [`crate::CircuitBreaker::window`],
2161            // [`crate::LimitsSpec::wall_clock`]). Every validated
2162            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2163            // (1ms..=1h), integer-millisecond granularity.
2164            crate::render::require_positive_canonical_bounded_duration(
2165                w,
2166                SUPERVISOR_RESTART_WINDOW_MAX,
2167                || SupervisorError::RestartWindowZero,
2168                SupervisorError::restart_window_not_canonical,
2169                SupervisorError::restart_window_exceeds_cap,
2170            )?;
2171        }
2172        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2173        // detection fan-out loop through the lifted named per-slot gate
2174        // [`SupervisorSpec::validate_children`] rather than an inline
2175        // three-per-child cascade — every future consumer that wants to
2176        // re-check only the `:children` slot's per-entry axes (the M4
2177        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2178        // admission webhook re-validating one added/renamed child, the
2179        // future wasm-operator's per-child dynamic-add re-validator on
2180        // the `SimpleOneForOne` runtime-add path once dynamic-children
2181        // graduate to a typed slot, a future partial re-validator on a
2182        // per-`:children`-entry patch) reaches every per-entry axis
2183        // through one dispatch rather than re-inlining the three-arm
2184        // cascade in lockstep with `validate` or paying the peer
2185        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2186        // reach one entry check. Sibling of the peer M3 mesh-slot
2187        // per-slot gate family (`validate_membros` — the exact peer on
2188        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2189        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2190        // `validate_placement`; `validate_politicas` routing through
2191        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2192        // per-slot gate discipline now spans both the M3 mesh-slot
2193        // family and the M2 `:children` per-child-cascade axis on one
2194        // shape: one named per-slot gate per typed per-entry loop.
2195        self.validate_children()?;
2196        Ok(())
2197    }
2198
2199    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2200    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2201    /// gate, and duplicate-`:caixa` dedup arm into one call every
2202    /// consumer that wants to re-validate one `:children` entry (or the
2203    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2204    /// admits reaches through.
2205    ///
2206    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2207    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2208    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2209    /// duplicate-`:caixa` dedup), lifted to one named substrate
2210    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2211    /// materializer's admission webhook re-checking one added or renamed
2212    /// child, the future wasm-operator's per-child dynamic-add
2213    /// re-validator on the `SimpleOneForOne` runtime-add path once
2214    /// dynamic-children graduate to a typed slot, a future partial
2215    /// re-validator on a per-`:children`-entry patch — each reaches the
2216    /// three per-entry axes through this one dispatch rather than
2217    /// re-inlining the three-arm cascade in lockstep with `validate`
2218    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2219    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2220    /// reach one entry check.
2221    ///
2222    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2223    /// through [`SupervisorSpec::children`] rather than borrowing one
2224    /// threaded down from `validate`, the same posture the peer M3
2225    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2226    /// [`crate::AplicacaoSpec::validate_contratos`],
2227    /// [`crate::AplicacaoSpec::validate_entrada`],
2228    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2229    /// consumer that reaches this gate directly (without first calling
2230    /// `validate`) still runs the full per-child cascade — pinned by
2231    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2232    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2233    /// + `validate_children_is_self_contained_on_children_slot`.
2234    ///
2235    /// The three per-entry arms run in the same canonical order the
2236    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2237    /// the diagnostic every author-declared per-`:children` entry surfaces
2238    /// through `validate` is byte-equal to the diagnostic this gate
2239    /// surfaces when called directly — the equivalence-pin pair
2240    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2241    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2242    /// asserts the two altitudes discriminate the same set on every
2243    /// per-entry-covered input.
2244    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2245        let mut seen = std::collections::HashSet::new();
2246        for child in self.children() {
2247            // Every emitted cluster artifact's `metadata.name` for a
2248            // supervised child derives from this `:children :caixa` value
2249            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2250            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2251            // label value on every child's pod identity, and the per-
2252            // child K8s [`Service`][svc] `metadata.name` the future
2253            // wasm-operator (M3) provisions for inter-child supervision
2254            // tree wiring. Each apiserver-side schema on each landing
2255            // site enforces the DNS-1123 label rule on admission; a
2256            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2257            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2258            // UUID-shaped mistaken-identity slug) silently passes the
2259            // prior empty-/duplicate-only gate and the failure surfaces
2260            // at `kubectl apply` time as a `metadata.name: Invalid value`
2261            // rejection, far from the source caixa.lisp, with no field
2262            // naming the offending `:children` entry. Lifting the gate
2263            // to caixa-build time mirrors the `:membros :caixa` value-
2264            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2265            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2266            // identifier axis — the supervisor tree's child names —
2267            // through the lifted
2268            // [`crate::render::require_valid_dns_1123_label`] gate the
2269            // seven peer name axes (`:membros :caixa`, `:placement
2270            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2271            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2272            // route through, so drift between the eight axes' accepted
2273            // DNS-1123-label sets is structurally impossible.
2274            //
2275            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2276            crate::render::require_valid_dns_1123_label(
2277                child.nome(),
2278                || SupervisorError::EmptyChildName,
2279                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2280            )?;
2281            // The author surface for `:children :versao` is the same
2282            // Cargo-shaped semver requirement string `:deps :versao` and
2283            // `:membros :versao` carry — and the lacre pipeline resolves
2284            // all three axes through the same
2285            // [`crate::version::parse_requirement`] entry-point. The
2286            // shared [`crate::render::require_valid_versao_requirement`]
2287            // helper brackets the empty-first + parse cascade both peer
2288            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2289            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2290            // :versao`) route through, so drift between the three axes'
2291            // accepted requirement sets is structurally impossible and
2292            // the parse-side no-op the empty-first arm closes (semver's
2293            // empty parse yields an implicit `*`) lives in exactly one
2294            // predicate. Every `ChildSpec::versao` past validate is
2295            // round-trippable through [`crate::parse_requirement`]
2296            // without re-checking at the resolver layer, and the three
2297            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2298            // are now structurally equivalent by construction.
2299            crate::render::require_valid_versao_requirement(
2300                child.versao_requirement(),
2301                || SupervisorError::empty_child_version(child.nome()),
2302                |reason| {
2303                    SupervisorError::child_versao_invalid(
2304                        child.nome(),
2305                        child.versao_requirement(),
2306                        reason,
2307                    )
2308                },
2309            )?;
2310            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2311                SupervisorError::duplicate_child_caixa(child.nome())
2312            })?;
2313        }
2314        Ok(())
2315    }
2316}
2317
2318/// Cross-slot coherence gate on the supervision tree: no
2319/// `:children :caixa` entry may name the supervisor's own `:nome`.
2320///
2321/// A supervisor that lists itself as a child is a degenerate self-parent
2322/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2323/// specs reference *distinct* child processes; a supervisor is never its
2324/// own child), and the wasm-operator's hierarchical reconciliation would
2325/// otherwise be handed a node that is its own parent: a one-node cycle it
2326/// either rejects far from the source `caixa.lisp` or recurses on. Because
2327/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2328/// lacre closure root), a child whose `:caixa` equals the supervisor's
2329/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2330///
2331/// Lives outside [`SupervisorSpec::validate`] because the typed view
2332/// carries the children but not the parent `:nome`; mirrors the
2333/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2334/// (which likewise reads one slot against another at the
2335/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2336/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2337/// node to itself is structurally not a tree/mesh edge" discipline, here
2338/// on the supervision-tree axis.
2339pub fn validate_no_self_supervision(
2340    children: &[ChildSpec],
2341    parent_nome: &str,
2342) -> Result<(), SupervisorError> {
2343    for child in children {
2344        if child.nome() == parent_nome {
2345            return Err(SupervisorError::child_supervises_self(parent_nome));
2346        }
2347    }
2348    Ok(())
2349}
2350
2351#[derive(Debug, Error, PartialEq, Eq)]
2352pub enum SupervisorError {
2353    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2354    NoChildren { estrategia: RestartStrategy },
2355    #[error(
2356        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2357    )]
2358    SimpleOneForOneWithStaticChildren,
2359    #[error(":max-restarts must be > 0")]
2360    ZeroMaxRestarts,
2361    #[error(
2362        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2363         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2364         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2365         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2366         can reach it, so the supervisor never escalates to its parent and a bad child can \
2367         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2368         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2369         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2370         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2371         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2372         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2373         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2374         band) or restructure the supervision tree (split the flaky child into its own \
2375         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2376    )]
2377    MaxRestartsExceedsCap { max_restarts: u32 },
2378    #[error(
2379        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2380         requires Period > 0; a zero window either trips on the first failure or \
2381         never trips depending on operator interpretation. Omit :restart-window to \
2382         express `never reset`; carry a positive duration to express the window."
2383    )]
2384    RestartWindowZero,
2385    #[error(
2386        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2387         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2388         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2389         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2390         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2391    )]
2392    RestartWindowNotCanonical { window: Duration },
2393    #[error(
2394        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2395         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2396         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2397         failure-counting window is structurally so long that transient restarts are never \
2398         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2399         when the child has exceeded its restart budget within the recent window` to `trip the \
2400         parent when the child has exceeded its restart budget over its lifetime`, and the \
2401         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2402         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2403         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2404         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2405         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2406         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2407         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2408         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2409         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2410         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2411         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2412         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2413         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2414         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2415         hiding it behind a rolling-window declaration the cap arm rejects)"
2416    )]
2417    RestartWindowExceedsCap { window: Duration },
2418    #[error("child entry has empty :caixa name")]
2419    EmptyChildName,
2420    #[error(
2421        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2422         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2423         name / label value the child name lands in — the per-child \
2424         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2425         label value, and the future wasm-operator per-child Service `metadata.name` \
2426         — each apiserver-side schema rejects names that don't match; use a \
2427         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2428    )]
2429    ChildCaixaInvalid { caixa: String, reason: String },
2430    #[error("child {caixa:?} has empty :versao constraint")]
2431    EmptyChildVersion { caixa: String },
2432    #[error(
2433        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2434         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2435         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2436         `:membros :versao` carry; the lacre pipeline resolves all three \
2437         through the same parser)"
2438    )]
2439    ChildVersaoInvalid {
2440        caixa: String,
2441        versao: String,
2442        reason: String,
2443    },
2444    #[error(
2445        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2446         child_spec.id per supervisor; duplicate children materialize as duplicate \
2447         ComputeUnits in the rendered chart, one silently overwriting the other)"
2448    )]
2449    DuplicateChildCaixa { caixa: String },
2450    #[error(
2451        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2452         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2453         OTP child specs reference distinct child processes). Since every :nome is a \
2454         globally-unique substrate identity, a child naming the supervisor's own :nome \
2455         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2456         self-referential :children entry or rename it to the actual child caixa."
2457    )]
2458    ChildSupervisesSelf { caixa: String },
2459}
2460
2461// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2462// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2463// and [`validate_no_self_supervision`] onto one substrate primitive per
2464// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2465// `LayoutError`-envelope constructor families the peer
2466// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2467// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2468// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2469// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2470// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2471// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2472// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2473// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2474// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2475// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2476// variants on `{ de, para }`) already at that discipline on the peer
2477// `AplicacaoError` envelopes.
2478//
2479// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2480// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2481// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2482// self-supervision arm) opened the identical
2483// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2484// the exact "same block re-inlined at every consumer" shape the PRIME
2485// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2486// `AplicacaoError` families each closed on their sibling envelopes. The
2487// three variants share one `{ caixa: String }` shape, so the fold routes
2488// each wire-up site through one dispatch per typed variant.
2489//
2490// The macro below generates one static constructor per variant of shape
2491// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2492// collapses onto one dispatch:
2493// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2494// struct-literal on the same `&str` fixture. The uniform one-field
2495// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2496// macro — rather than at every wire-up site. Every constructor is
2497// `#[must_use]` so a caller who mistakenly discards the constructed error
2498// trips a compile warning at the wire-up site.
2499//
2500// Every future consumer that wants to construct one of these three
2501// variants outside `SupervisorSpec::validate_children` /
2502// `validate_no_self_supervision` — a deferred
2503// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2504// webhook re-checking one added/renamed child, a future
2505// `feira validate --supervisor` per-caixa admission verb, a per-child
2506// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2507// once dynamic-children graduate to a typed slot, a per-Supervisor
2508// overlay resolver rejecting a duplicate/self-supervising child against
2509// a cluster-local snapshot — now reaches each variant through one call
2510// rather than re-inlining the three-line struct-literal in lockstep
2511// with the three in-crate wire-up sites.
2512macro_rules! supervisor_caixa_only_ctors {
2513    ($($ctor:ident => $variant:ident),* $(,)?) => {
2514        impl SupervisorError {
2515            $(
2516                #[doc = concat!(
2517                    "Construct a [`SupervisorError::",
2518                    stringify!($variant),
2519                    "`] naming the offending `:children :caixa` (or ",
2520                    "supervisor `:nome`, on the self-supervision arm). ",
2521                    "Folds the uniform `Self::",
2522                    stringify!($variant),
2523                    " { caixa: caixa.to_string() }` one-field ",
2524                    "struct-literal onto one substrate primitive so ",
2525                    "every [`SupervisorSpec::validate_children`] / ",
2526                    "[`validate_no_self_supervision`] wire-up on this ",
2527                    "variant reads through one dispatch rather than the ",
2528                    "pre-lift open-coded struct-literal block."
2529                )]
2530                #[must_use]
2531                pub fn $ctor(caixa: &str) -> Self {
2532                    Self::$variant { caixa: caixa.to_string() }
2533                }
2534            )*
2535        }
2536    };
2537}
2538
2539supervisor_caixa_only_ctors! {
2540    empty_child_version => EmptyChildVersion,
2541    duplicate_child_caixa => DuplicateChildCaixa,
2542    child_supervises_self => ChildSupervisesSelf,
2543}
2544
2545// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2546// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2547// one substrate primitive per typed variant — the M2 supervisor-side siblings
2548// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2549// already lifted through the sibling
2550// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2551// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2552// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2553// String }` two-slot shape the peer seven-variant
2554// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2555// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2556// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2557// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2558// variant carries the `{ caixa: String, versao: String, reason: String }`
2559// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2560// carries on the same `:versao` value-shape.
2561//
2562// Each of the two wire-up sites opened the same closure-shaped
2563// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2564// [versao: child.versao_requirement().to_string(),] reason }` block inside
2565// the paired [`crate::render::require_valid_dns_1123_label`] and
2566// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2567// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2568// as a bug, on the same altitude the peer `AplicacaoError` /
2569// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2570// families already closed on their sibling envelopes.
2571//
2572// The two `#[must_use]` inherent constructors below fold each wire-up onto
2573// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2574// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2575// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2576// The uniform per-field `.to_string()` / `.into()` construction is spelled
2577// once — inside each ctor body — rather than at every wire-up site. The
2578// `reason: impl Into<String>` bound accepts both `&str` literals and
2579// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2580// diagnostic shape at the lift, matching the peer
2581// [`aplicacao_field_reason_ctors!`] and
2582// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2583// sibling envelopes.
2584//
2585// Every future consumer that wants to construct one of these two variants
2586// outside `SupervisorSpec::validate_children` — a deferred
2587// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2588// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2589// `feira validate --supervisor` per-caixa admission verb, a per-child
2590// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2591// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2592// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2593// cluster-local snapshot — now reaches each variant through one call rather
2594// than re-inlining the per-shape struct-literal block in lockstep with the
2595// two in-crate wire-up sites.
2596impl SupervisorError {
2597    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2598    /// offending `:children :caixa` value under the given `reason`. Folds
2599    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2600    /// reason: reason.into() }` two-slot struct-literal onto one substrate
2601    /// primitive so every wire-up on this variant reads through one
2602    /// dispatch, matching the peer
2603    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2604    /// sibling `AplicacaoError { caixa: String, reason: String }`
2605    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2606    /// outputs through the `impl Into<String>` bound.
2607    #[must_use]
2608    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2609        Self::ChildCaixaInvalid {
2610            caixa: caixa.to_string(),
2611            reason: reason.into(),
2612        }
2613    }
2614
2615    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2616    /// offending `:children :caixa` and its `:versao` requirement under
2617    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2618    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2619    /// reason.into() }` three-slot struct-literal onto one substrate
2620    /// primitive so every wire-up on this variant reads through one
2621    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2622    /// { caixa, versao, reason }` three-slot axis on the peer
2623    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2624    /// and `format!(…)` outputs through the `impl Into<String>` bound.
2625    #[must_use]
2626    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2627        Self::ChildVersaoInvalid {
2628            caixa: caixa.to_string(),
2629            versao: versao.to_string(),
2630            reason: reason.into(),
2631        }
2632    }
2633}
2634
2635// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2636// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2637// three bracket-arms — one struct-literal at the `:children`-empty
2638// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2639// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2640// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2641// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2642// [`crate::render::require_positive_canonical_bounded_duration`]
2643// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2644// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2645// primitive per typed variant, matching the sibling
2646// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2647// variants on the same `{ <field>: Duration | u32 }` shape) at that
2648// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2649// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2650// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2651// wire-up site through one dispatch per typed variant without a runtime-
2652// work delta.
2653//
2654// Each of the four wire-up sites opened the identical
2655// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
2656// exact "same block re-inlined at every consumer" shape the PRIME
2657// DIRECTIVE names as a bug, on the same altitude the peer
2658// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
2659// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
2660// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
2661// the fold routes each wire-up site through one dispatch per typed
2662// variant.
2663//
2664// The macro below generates one static constructor per variant of shape
2665// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
2666// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
2667// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
2668// fixture — as a direct call at the [`SupervisorSpec::validate`]
2669// `:children`-empty refusal, or as a bare function pointer in the
2670// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
2671// [`crate::render::require_positive_bounded_u32`] /
2672// [`crate::render::require_positive_canonical_bounded_duration`] gate
2673// carries — rather than the pre-lift open-coded one-line closure over
2674// the same one-field struct-literal. `const fn` preserves the `Copy`-
2675// pass-through's zero-runtime-work property verbatim. Every constructor
2676// is `#[must_use]` so a caller who mistakenly discards the constructed
2677// error trips a compile warning at the wire-up site.
2678//
2679// Every future consumer that wants to construct one of these four
2680// variants outside `SupervisorSpec::validate` — a deferred
2681// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2682// webhook re-checking one edited `:estrategia` / `:max-restarts` /
2683// `:restart-window` slot against the cap + canonical-form cascade, a
2684// future `feira validate --supervisor` per-caixa admission verb re-
2685// running the shape gates on demand, a per-Supervisor overlay resolver
2686// rejecting an author-supplied slot against a cluster-local snapshot —
2687// now reaches each variant through one call rather than re-inlining the
2688// per-shape struct-literal block in lockstep with the four in-crate
2689// wire-up sites.
2690macro_rules! supervisor_scalar_ctors {
2691    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2692        impl SupervisorError {
2693            $(
2694                #[doc = concat!(
2695                    "Construct a [`SupervisorError::",
2696                    stringify!($variant),
2697                    "`] naming the offending per-`:supervisor` `",
2698                    stringify!($field),
2699                    "` scalar. Folds the uniform `Self::",
2700                    stringify!($variant),
2701                    " { ",
2702                    stringify!($field),
2703                    " }` one-field `Copy`-pass-through struct-literal onto ",
2704                    "one substrate primitive so every per-axis wire-up on ",
2705                    "this variant reads through one dispatch — as a direct ",
2706                    "call (`SupervisorError::",
2707                    stringify!($ctor),
2708                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
2709                    "the same `Copy`-`",
2710                    stringify!($ty),
2711                    "` fixture) or as a bare function pointer in the ",
2712                    "`impl FnOnce(",
2713                    stringify!($ty),
2714                    ") -> SupervisorError` bracket-closure slot every ",
2715                    "`crate::render::require_positive_bounded_*` / ",
2716                    "`crate::render::require_positive_canonical_bounded_*` ",
2717                    "gate carries — rather than the pre-lift open-coded ",
2718                    "one-line closure over the same one-field struct-",
2719                    "literal. `const fn` preserves the `Copy`-pass-through's ",
2720                    "zero-runtime-work property verbatim."
2721                )]
2722                #[must_use]
2723                pub const fn $ctor($field: $ty) -> Self {
2724                    Self::$variant { $field }
2725                }
2726            )*
2727        }
2728    };
2729}
2730
2731supervisor_scalar_ctors! {
2732    no_children => NoChildren { estrategia: RestartStrategy },
2733    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
2734    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
2735    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
2736}
2737
2738/// Shared duration string codec for the typed slots that take a
2739/// duration (`restart_window`, `MeshPolicy::timeout`,
2740/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2741/// reuse it without duplicating the parser.
2742pub mod duration_codec {
2743    use super::Duration;
2744    use serde::{Deserializer, Serializer};
2745
2746    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2747        // Route through the canonical [`crate::render::serialize_option_via_str`]
2748        // — the substrate-side single-owner primitive for the forward
2749        // arm of the typed-magnitude codec family. See its docstring
2750        // for the full sibling roster.
2751        crate::render::serialize_option_via_str(v, s, render)
2752    }
2753
2754    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2755        // Route through the canonical [`crate::render::deserialize_option_via_str`]
2756        // — the substrate-side single-owner primitive for the reverse
2757        // arm of the typed-magnitude codec family. See its docstring
2758        // for the full sibling roster.
2759        crate::render::deserialize_option_via_str(d, parse)
2760    }
2761
2762    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2763        // Paired whitespace-rejection arm — same canonical-form
2764        // render-determinism discipline as the peer
2765        // `limits::parse_byte_size` / `limits::parse_duration` /
2766        // `limits::parse_millicores` /
2767        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2768        // byte-scan closes the WhatWG-conformant whitespace bytes
2769        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2770        // `char::is_whitespace` scan closes the strictly-complementary
2771        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2772        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2773        // codepoints) that `str::trim` at parse entry silently strips.
2774        // Either drift class would round-trip through `render` to a
2775        // *different* canonical form on next emit — breaking the
2776        // THEORY.md Part V render-determinism contract on three typed-
2777        // duration slots at once (`:supervisor :restart-window`,
2778        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2779        // via the shared codec.
2780        //
2781        // Routed through the lifted [`crate::render::reject_whitespace`]
2782        // primitive — the substrate-side single-owner paired-arm gate
2783        // every typed-magnitude codec in caixa-core shares.
2784        crate::render::reject_whitespace::<String, _, _>(
2785            s,
2786            |b| {
2787                format!(
2788                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2789                 authoring form for the typed duration slots routed through this shared codec \
2790                 (`:supervisor :restart-window`, `:politicas :timeout`, \
2791                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2792                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2793                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2794                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2795                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2796                 Part V render-determinism contract every typed slot carries. Strip every \
2797                 whitespace byte (write `\"30s\"` verbatim)"
2798                )
2799            },
2800            |ch| {
2801                format!(
2802                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2803                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2804                 duration slots routed through this shared codec (`:supervisor \
2805                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2806                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2807                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2808                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2809                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2810                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2811                 `White_Space` property, strictly wider than the ASCII byte set) silently \
2812                 strips it at parse entry, and the value round-trips through `render` to \
2813                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2814                 the THEORY.md Part V render-determinism contract every typed slot \
2815                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2816                 verbatim with only ASCII bytes)",
2817                    cp = ch as u32
2818                )
2819            },
2820        )?;
2821        let s = s.trim();
2822        // Routed through the lifted
2823        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
2824        // the single-owner split every ASCII-alphabetic-unit typed-
2825        // magnitude codec in caixa-core (`limits::parse_byte_size` /
2826        // `limits::parse_duration` / this shared duration codec) shares.
2827        // See its docstring for the full sibling roster on the same
2828        // primitive altitude.
2829        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
2830        let num_trim = num_part.trim();
2831        // The canonical authoring form for every typed slot routed
2832        // through this shared codec — `:supervisor :restart-window`,
2833        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
2834        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
2835        // non-negative integer with no decimal point and no leading
2836        // sign, so the parser's accepted set must match for
2837        // serialize/deserialize to round-trip without canonical-form
2838        // drift. Until this gate landed the parser accepted any
2839        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
2840        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
2841        // tripped the value to a *different* canonical string on the
2842        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
2843        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
2844        // — breaking the THEORY.md Part V render-determinism contract
2845        // on three typed slots at once. Same canonical-form discipline
2846        // `crate::limits::parse_duration` (818dd38, the immediate
2847        // predecessor on the peer `:limits :wall-clock` codec) applies;
2848        // this gate lifts the discipline onto the shared codec that
2849        // backs the remaining three typed-duration slots in caixa-core.
2850        //
2851        // Strict canonical form: every byte of the magnitude is an
2852        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
2853        // inputs the gate distinguishes "non-canonical-but-numeric"
2854        // (parses as f64 or i64 — surfaced with a self-locating
2855        // diagnostic naming the canonical authoring form, the
2856        // round-trip drift each rejected shape would produce on first
2857        // serialize, and the canonical-form remediation) from
2858        // "garbage" (parses as neither — surfaced with the existing
2859        // narrower "bad duration magnitude" wording so its diagnostic
2860        // shape remains stable for the parser-shape footgun case).
2861        // The pre-existing `num < 0.0` arm is now unreachable — the
2862        // digit-only gate strictly precedes magnitude parsing, and a
2863        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
2864        // non-canonical-but-numeric branch with the `-30` named
2865        // verbatim in the diagnostic rather than the prior
2866        // value-laundered "negative duration in \"-30s\"" wording.
2867        //
2868        // Routed through the lifted
2869        // [`crate::render::is_digit_only_magnitude`] predicate — the
2870        // same source of truth the four peer typed-magnitude codec
2871        // sites share.
2872        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
2873        if !digit_only {
2874            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
2875            if numeric {
2876                return Err(format!(
2877                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
2878                     canonical authoring form for the typed duration slots routed through \
2879                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2880                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2881                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
2882                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
2883                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
2884                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
2885                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
2886                     THEORY.md Part V render-determinism contract every typed slot carries. \
2887                     Pick an integer magnitude in the unit that divides cleanly (write \
2888                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
2889                ));
2890            }
2891            return Err(format!("bad duration magnitude in {s:?}"));
2892        }
2893        // Leading-zero arm — peer with the `rate_limit_codec` leading-
2894        // zero arm (4f46830) on the same canonical-form render-
2895        // determinism axis. The digit-only gate accepts `"030s"`,
2896        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
2897        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
2898        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
2899        // *different* canonical string on the next emit, breaking the
2900        // THEORY.md Part V render-determinism contract the same way
2901        // `"+30s"` did before the leading-`+` arm landed. The single-
2902        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
2903        // losslessly through `render` (`render(Duration::ZERO)` emits
2904        // `"0s"`) — the downstream semantic-zero gates (e.g.
2905        // `SupervisorError::ZeroRestartWindow` on
2906        // `:supervisor :restart-window`,
2907        // `AplicacaoError::PolicyTimeoutZero` /
2908        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
2909        // duration slots) refuse zero-magnitude authoring at the typed-
2910        // validate layer above, so the single-byte `"0"` stays in the
2911        // accepted set at this codec layer and the diagnostic
2912        // partitioning between canonical-form drift (this arm) and
2913        // semantic-zero (the downstream gates) remains stable.
2914        // Peer with the future leading-zero arms on the two remaining
2915        // typed-magnitude codecs the trajectory acknowledges:
2916        // `limits::parse_duration` backing `:limits :wall-clock`,
2917        // `limits::parse_byte_size` backing `:limits :memory` — each
2918        // carries the same canonical-form-drift class today; this
2919        // gate lands the discipline on the shared duration codec
2920        // first because the `rate_limit_codec` predecessor on the
2921        // same canonical-form-drift axis is the closest peer on the
2922        // trajectory.
2923        //
2924        // Routed through the lifted
2925        // [`crate::render::is_leading_zero_padded_magnitude`]
2926        // predicate — the same source of truth the four peer
2927        // typed-magnitude codec sites share.
2928        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
2929            return Err(format!(
2930                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
2931                 canonical authoring form for the typed duration slots routed through \
2932                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2933                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2934                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
2935                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
2936                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
2937                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
2938                 serialize — breaking the THEORY.md Part V render-determinism contract \
2939                 every typed slot carries. Strip the leading zeros (write \
2940                 `\"30s\"` instead of `\"030s\"`)"
2941            ));
2942        }
2943        // The digit-only gate guarantees every byte is `[0-9]`, and
2944        // the leading-zero arm above guarantees the magnitude is
2945        // either the single byte `"0"` or starts with `[1-9]`, so
2946        // the only way `u64::from_str` can fail here is overflow (the
2947        // magnitude exceeds `u64::MAX`). Surface that with an
2948        // overflow-shaped wording so the diagnostic names the offending
2949        // magnitude verbatim rather than collapsing onto the
2950        // non-canonical arm. The codec now operates on `u64` end-to-end
2951        // — every accepted magnitude is integer-exact; no f64 mantissa
2952        // drift between author-supplied magnitude and the consumer's
2953        // `Duration` value. Same shape `crate::limits::parse_duration`
2954        // (818dd38) carries on the peer `:limits :wall-clock` axis.
2955        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
2956            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
2957        })?;
2958        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
2959        // unit-arm dispatch through the canonical
2960        // [`crate::render::duration_from_integer_magnitude_and_unit`]
2961        // primitive — the substrate-side single-owner unit-dispatch
2962        // table every typed-duration codec in caixa-core routes
2963        // through (peer: `crate::limits::parse_duration` backing
2964        // `:limits :wall-clock`). Every unit conversion is integer-
2965        // exact for an integer magnitude; overflow surfaces via the
2966        // typed `DurationUnitError::Overflow { multiplier }`
2967        // discriminant so this arm reconstructs the pre-lift
2968        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
2969        // wording verbatim from `num` / `unit_trim` / the returned
2970        // `multiplier`, and the unknown-unit arm reconstructs the
2971        // pre-lift `"unknown duration unit \"<other>\""` wording from
2972        // the caller-scoped `unit_trim`. Load-bearing pinned by
2973        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
2974        let unit_trim = unit.trim();
2975        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
2976            |e| match e {
2977                crate::render::DurationUnitError::Overflow { multiplier } => format!(
2978                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
2979                ),
2980                crate::render::DurationUnitError::UnknownUnit => {
2981                    format!("unknown duration unit {unit_trim:?}")
2982                }
2983            },
2984        )?;
2985        Ok(dur)
2986    }
2987
2988    /// Render a [`Duration`] in the canonical pleme-io duration string
2989    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
2990    /// caixa typed-duration slot serializes to and the same form K8s
2991    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
2992    /// EnvoyConfig per-route timeouts both expect (an integer
2993    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
2994    /// `+`). Lifted to `pub` so caixa-side renderers
2995    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
2996    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
2997    /// emitter, the future caixa-otel collector pipeline emitter) can
2998    /// consume the same canonical formatter without re-inlining the
2999    /// magnitude/unit decision tree (and inheriting the same drift
3000    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3001    /// downstream apply-time parsing in non-obvious ways).
3002    pub fn render(d: Duration) -> String {
3003        let total_ms = d.as_millis();
3004        if total_ms == 0 {
3005            return "0s".into();
3006        }
3007        if total_ms.is_multiple_of(3600 * 1000) {
3008            return format!("{}h", total_ms / (3600 * 1000));
3009        }
3010        if total_ms.is_multiple_of(60 * 1000) {
3011            return format!("{}m", total_ms / (60 * 1000));
3012        }
3013        if total_ms.is_multiple_of(1000) {
3014            return format!("{}s", total_ms / 1000);
3015        }
3016        format!("{total_ms}ms")
3017    }
3018
3019    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3020    ///
3021    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3022    /// largest divisor unit, so any sub-millisecond residue
3023    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3024    /// §V.2.7 render-determinism contract:
3025    ///
3026    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3027    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3028    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3029    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3030    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3031    ///     on every typed-`Duration` slot then rejects on re-validate.
3032    ///
3033    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3034    /// the codec's round-trippable accepted set lives in exactly one place —
3035    /// every typed-`Duration` slot that routes through this shared codec
3036    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3037    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3038    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3039    /// every typed-`Duration` slot whose own codec shares the same
3040    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3041    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3042    /// pair) calls this predicate from its `validate()` to bracket the
3043    /// accepted set against the codec's accepted set, structurally. Drift
3044    /// between the codec's granularity and any typed slot's accepted set is
3045    /// then a single-source-of-truth edit at this predicate rather than a
3046    /// silent round-trip break the next consumer discovers at apply time.
3047    ///
3048    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3049    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3050    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3051    /// family — same "typed-slot's valid set matches its codec's accepted
3052    /// set, structurally" discipline carried at the codec layer.
3053    #[must_use]
3054    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3055        d.subsec_nanos().is_multiple_of(1_000_000)
3056    }
3057}
3058
3059/// Required-Duration variant for fields that aren't Option<Duration>.
3060pub mod duration_codec_required {
3061    use super::Duration;
3062    use serde::{Deserialize, Deserializer, Serializer};
3063
3064    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3065        s.serialize_str(&super::duration_codec::render(*v))
3066    }
3067
3068    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3069        let s = String::deserialize(d)?;
3070        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3071    }
3072}
3073
3074#[cfg(test)]
3075mod tests {
3076    use super::*;
3077
3078    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3079        ChildSpec {
3080            caixa: name.into(),
3081            versao: ver.into(),
3082            restart,
3083        }
3084    }
3085
3086    #[test]
3087    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3088        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3089        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3090        // posture. Each accessor projects the per-`:children :caixa`
3091        // / per-`:children :versao` [`String`] storage through the
3092        // `pub const fn` [`String::as_str`] (const-stable since Rust
3093        // 1.87, well within the workspace MSRV) — any future
3094        // accidental downgrade to non-`const` fails the corresponding
3095        // `<name>_via_const_fn` wrapper at caixa-core build time with
3096        // E0015 (`cannot call non-const method`), strictly stronger
3097        // than a runtime `assert!`. Sibling of the peer
3098        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3099        // family pins on the sibling `const`-eval-surface passes
3100        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3101        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3102        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3103        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3104        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3105        // [`crate::aplicacao::Entrada::destination`] at the M3
3106        // ingress axis,
3107        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3108        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3109        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3110        // axis, and the per-`:contratos`
3111        // [`crate::aplicacao::WitContract::source`] /
3112        // [`crate::aplicacao::WitContract::destination`] /
3113        // [`crate::aplicacao::WitContract::world_ref`] trio the
3114        // sibling pin at 279823b already anchors).
3115        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3116            c.nome()
3117        }
3118        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3119            c.versao_requirement()
3120        }
3121        for (caixa, versao) in [
3122            ("worker-a", "^0.1"),
3123            ("worker-b", "~0.2.3"),
3124            ("collector", "*"),
3125        ] {
3126            let c = child(caixa, versao, RestartPolicy::Permanent);
3127            assert_eq!(nome_via_const_fn(&c), c.nome());
3128            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3129            assert_eq!(c.nome(), caixa);
3130            assert_eq!(c.versao_requirement(), versao);
3131        }
3132    }
3133
3134    #[test]
3135    fn supervisor_children_slice_return_accessor_is_const_fn() {
3136        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3137        // `const`-eval-surface posture. The accessor destructures the
3138        // per-`:children` `Vec<ChildSpec>` storage through the
3139        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3140        // 1.66, well within the workspace MSRV) — any future
3141        // accidental downgrade to non-`const` fails
3142        // `children_via_const_fn` at caixa-core build time with E0015
3143        // (`cannot call non-const method`), strictly stronger than a
3144        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3145        // `Vec → &[T]` slice-return accessor family pin
3146        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3147        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3148        // per-`:membros` / per-`:contratos` slice-return axes, and of
3149        // the peer M2 upgrade-appup axis pin
3150        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3151        // on the per-`:upgrade-from :instructions` slice-return axis.
3152        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3153            s.children()
3154        }
3155        // Sweep both the empty-children (leaf-supervisor with no
3156        // static children — the `SimpleOneForOne` dynamic-child
3157        // arm's canonical shape) and the populated-children
3158        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3159        // arm's canonical shape) axes so the accessor carries a
3160        // const-dispatch pin on both arms.
3161        let s_empty = SupervisorSpec {
3162            estrategia: RestartStrategy::SimpleOneForOne,
3163            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3164            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3165            children: vec![],
3166        };
3167        assert!(children_via_const_fn(&s_empty).is_empty());
3168        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3169        let s_full = SupervisorSpec {
3170            estrategia: RestartStrategy::OneForOne,
3171            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3172            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3173            children: vec![
3174                child("worker-a", "^0.1", RestartPolicy::Permanent),
3175                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3176                child("collector", "*", RestartPolicy::Temporary),
3177            ],
3178        };
3179        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3180        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3181    }
3182
3183    #[test]
3184    fn default_has_one_for_one_and_5_restarts_in_60s() {
3185        let s = SupervisorSpec::default();
3186        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3187        assert_eq!(s.max_restarts, 5);
3188        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3189        assert!(s.children.is_empty());
3190    }
3191
3192    #[test]
3193    fn validate_one_for_one_requires_children() {
3194        let mut s = SupervisorSpec::default();
3195        s.children = vec![];
3196        assert!(matches!(
3197            s.validate().unwrap_err(),
3198            SupervisorError::NoChildren { .. }
3199        ));
3200        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3201        s.validate().unwrap();
3202    }
3203
3204    #[test]
3205    fn validate_simple_one_for_one_forbids_static_children() {
3206        let mut s = SupervisorSpec {
3207            estrategia: RestartStrategy::SimpleOneForOne,
3208            ..SupervisorSpec::default()
3209        };
3210        s.children
3211            .push(child("w", "^0.1", RestartPolicy::Permanent));
3212        assert_eq!(
3213            s.validate().unwrap_err(),
3214            SupervisorError::SimpleOneForOneWithStaticChildren
3215        );
3216        s.children.clear();
3217        s.validate().unwrap();
3218    }
3219
3220    #[test]
3221    fn validate_rejects_zero_max_restarts() {
3222        let s = SupervisorSpec {
3223            max_restarts: 0,
3224            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3225            ..SupervisorSpec::default()
3226        };
3227        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3228    }
3229
3230    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3231    //
3232    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3233    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3234    // `:supervisor :max-restarts` axis — both fields are "trip the
3235    // next-higher protection layer after N events in a rolling window"
3236    // counters with identical degenerate-at-the-high-end shape, so the
3237    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3238    // exactly as it lies in `1..=1000` on the breaker side.
3239
3240    #[test]
3241    fn validate_rejects_max_restarts_above_cap() {
3242        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3243        // 1` is structurally one past the cap and silently passed
3244        // validate on every pre-gate codebase because the typed slot's
3245        // only check was the zero-floor arm. The no-op-supervisor vector
3246        // only surfaced at the runtime substrate (Erlang/OTP
3247        // MaxIntensity/Period ratio, the future wasm-operator's
3248        // per-supervisor restart-intensity counter) far from the source
3249        // caixa.lisp with no field naming the offending supervisor.
3250        let s = SupervisorSpec {
3251            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3252            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3253            ..SupervisorSpec::default()
3254        };
3255        assert_eq!(
3256            s.validate().unwrap_err(),
3257            SupervisorError::MaxRestartsExceedsCap {
3258                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3259            }
3260        );
3261    }
3262
3263    #[test]
3264    fn validate_rejects_max_restarts_far_above_cap() {
3265        // The `u32::MAX` worst case — the four-billion-restart
3266        // threshold a typo (`:max-restarts 4294967295`) or a
3267        // struct-literal copy-paste lands in the slot. Pin the cap
3268        // arm's coverage explicitly across the full `u32` overflow so
3269        // a future relaxation that drops the upper bound surfaces
3270        // here. Same shape every other typed-cap arm on this surface
3271        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3272        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3273        let s = SupervisorSpec {
3274            max_restarts: u32::MAX,
3275            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3276            ..SupervisorSpec::default()
3277        };
3278        assert_eq!(
3279            s.validate().unwrap_err(),
3280            SupervisorError::MaxRestartsExceedsCap {
3281                max_restarts: u32::MAX,
3282            }
3283        );
3284    }
3285
3286    #[test]
3287    fn validate_accepts_max_restarts_at_cap() {
3288        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3289        // must validate. The cap is inclusive on the top edge,
3290        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3291        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3292        // discipline on the sibling capped axes. Pin the boundary
3293        // explicitly so a future off-by-one tightening
3294        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3295        // here as a test failure rather than a silent contract
3296        // narrowing.
3297        let s = SupervisorSpec {
3298            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3299            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3300            ..SupervisorSpec::default()
3301        };
3302        s.validate()
3303            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3304    }
3305
3306    #[test]
3307    fn validate_accepts_max_restarts_typical_values() {
3308        // The documented production-playbook band positive-control
3309        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3310        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3311        // through the hyperscale band (200, 500, 1000) the cap
3312        // accepts. Pin the inclusive validated set explicitly so a
3313        // future tightening of the ceiling surfaces here.
3314        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3315            let s = SupervisorSpec {
3316                max_restarts: n,
3317                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3318                ..SupervisorSpec::default()
3319            };
3320            s.validate()
3321                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3322        }
3323    }
3324
3325    #[test]
3326    fn zero_max_restarts_takes_precedence_over_cap() {
3327        // The cross-arm ordering pin: `0` is structurally outside
3328        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3329        // (cap), but the zero-floor diagnostic is the more
3330        // self-locating one (it directly names the counter-axis
3331        // remediation), so the validate gate must fire on zero first.
3332        // Same shape every other zero-then-shape ordering on this
3333        // surface uses (PolicyRetriesZero then
3334        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3335        // PolicyBreakerMaxFailuresExceedsCap).
3336        let s = SupervisorSpec {
3337            max_restarts: 0,
3338            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3339            ..SupervisorSpec::default()
3340        };
3341        assert_eq!(
3342            s.validate().unwrap_err(),
3343            SupervisorError::ZeroMaxRestarts,
3344            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3345        );
3346    }
3347
3348    #[test]
3349    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3350        // The cross-arm ordering pin between the cap and the sibling
3351        // `:restart-window` gates (zero-window, canonical-window). A
3352        // supervisor carrying both an over-cap `max_restarts` AND a
3353        // structurally invalid window (zero, sub-ms) must surface the
3354        // cap diagnostic first — the cap arm is wired immediately
3355        // after the zero-restart arm and strictly before the window
3356        // arms, so the offending value the diagnostic names matches
3357        // the order the author would discover the gates by reading
3358        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3359        // order so a future refactor that reorders the arms surfaces
3360        // here as a test failure rather than a silent diagnostic
3361        // regression. Peer of
3362        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3363        // on the sibling `:politicas :circuit-breaker` slot.
3364        let s = SupervisorSpec {
3365            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3366            restart_window: Some(Duration::ZERO),
3367            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3368            ..SupervisorSpec::default()
3369        };
3370        assert_eq!(
3371            s.validate().unwrap_err(),
3372            SupervisorError::MaxRestartsExceedsCap {
3373                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3374            },
3375            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3376        );
3377    }
3378
3379    #[test]
3380    fn max_restarts_cap_diagnostic_carries_offending_value() {
3381        // The diagnostic-shape pin: the offending `u32` is carried
3382        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3383        // variant so the surfaced error message names the value the
3384        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3385        // supervisor-policy ceiling …"`), not just the cap. Same
3386        // self-locating diagnostic shape every other typed-cap arm on
3387        // this surface carries
3388        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3389        // the offending failure count verbatim,
3390        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3391        // retries count verbatim).
3392        let s = SupervisorSpec {
3393            max_restarts: 50_000,
3394            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3395            ..SupervisorSpec::default()
3396        };
3397        let err = s.validate().unwrap_err();
3398        assert!(
3399            matches!(
3400                err,
3401                SupervisorError::MaxRestartsExceedsCap {
3402                    max_restarts: 50_000
3403                }
3404            ),
3405            "got {err:?}"
3406        );
3407        let msg = err.to_string();
3408        assert!(
3409            msg.contains("50000"),
3410            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3411        );
3412    }
3413
3414    #[test]
3415    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3416        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3417        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3418        // half of Learn You Some Erlang's worker-supervisor default,
3419        // sibling of the `60s` `Period` half that the paired
3420        // [`Default for SupervisorSpec`] impl already pins on the
3421        // sibling `restart_window` axis. Pinning the literal here
3422        // surfaces a future rebrand (a tightening to Elixir's `3`,
3423        // a widening to a per-cluster overlay the operator pins
3424        // through a future `:max-restarts-overrides` slot) as a
3425        // deliberate test edit, not a silent contract migration.
3426        // Peer of the sibling
3427        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3428        // upper-bracket pin on the same axis.
3429        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3430    }
3431
3432    #[test]
3433    fn default_max_restarts_helper_routes_through_lifted_default() {
3434        // Composition pin: the private `default_max_restarts()`
3435        // serde-`#[serde(default = "…")]` helper on
3436        // [`SupervisorSpec::max_restarts`] must route through the
3437        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3438        // typed `pub const` rather than a raw `5` literal. Prior to
3439        // the lift the helper carried an inline `5` with no compile-
3440        // time link back to the shared default, so the wire-format
3441        // author-omitted arm and the caixa-core
3442        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3443        // arm could silently split on any future default rebrand.
3444        // Byte-parity against the lifted constant closes the split.
3445        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3446    }
3447
3448    #[test]
3449    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3450        // Composition pin: the [`Default for SupervisorSpec`] impl's
3451        // struct-literal `max_restarts` field must route through the
3452        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3453        // typed `pub const` (via the private helper this test's
3454        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3455        // already pins onto the constant). Structurally: every
3456        // `SupervisorSpec::default()` call must yield a
3457        // `max_restarts` field byte-equal to the lifted constant
3458        // (the two paired defaults — the serde-side wire-format arm
3459        // and the struct-literal default arm — cannot silently split
3460        // on any future default rebrand). Peer of the sibling
3461        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3462        // — this pin closes the byte-parity arm on the two paired
3463        // altitude entry points onto the shared substrate constant.
3464        assert_eq!(
3465            SupervisorSpec::default().max_restarts(),
3466            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3467        );
3468    }
3469
3470    #[test]
3471    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3472        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3473        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3474        // Learn You Some Erlang's worker-supervisor default, paired
3475        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3476        // `MaxIntensity` half this constant is the sliding-window
3477        // denominator of on the same `MaxIntensity / Period`
3478        // restart-intensity ratio. Pinning the literal here surfaces a
3479        // future coherent rebrand of the paired default (Elixir's
3480        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3481        // the operator pins through a future
3482        // `:restart-window-overrides` slot) as a deliberate test edit,
3483        // not a silent contract migration. Peer of the sibling
3484        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3485        // paired-half pin on the same OTP-canonical default and the
3486        // [`supervisor_restart_window_cap_pins_canonical_value`]
3487        // upper-bracket pin on the same axis.
3488        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3489    }
3490
3491    #[test]
3492    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3493        // Composition pin: the [`Default for SupervisorSpec`] impl's
3494        // struct-literal `restart_window` field must route through the
3495        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3496        // typed `pub const` rather than a raw
3497        // `Duration::from_secs(60)` literal. Prior to this lift the
3498        // paired `{intensity, 5, 60}` OTP-canonical default was split
3499        // across two altitudes with no compile-time link between the
3500        // halves — the `MaxIntensity` half rode through the lifted
3501        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3502        // `Period` half rode as an open-coded literal at the
3503        // composition site, so a future coherent rebrand of the paired
3504        // canonical would have had to migrate one half through the
3505        // constant and the other through a raw literal in lockstep.
3506        // Byte-parity against the lifted constant on the `Period` half
3507        // closes the split — the paired OTP-canonical default now
3508        // migrates as one unit on any future axis change. Peer of the
3509        // sibling
3510        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3511        // byte-parity pin on the paired `MaxIntensity` half.
3512        assert_eq!(
3513            SupervisorSpec::default().restart_window(),
3514            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3515        );
3516    }
3517
3518    #[test]
3519    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3520        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3521        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3522        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3523        // canonical default, paired with the sibling
3524        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3525        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3526        // this constant is the strategy discriminator of on the same
3527        // OTP-canonical worker-supervisor default. Pinning the arm here
3528        // surfaces a future coherent rebrand of the paired triple (Elixir's
3529        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3530        // intensity/period axes leaving this strategy arm untouched, an OTP
3531        // `rest_for_one` widening once the substrate discovers startup-
3532        // order-coupled child cohorts as the more common worker-supervisor
3533        // shape, a per-cluster overlay the operator pins through a future
3534        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3535        // supervision-canary roadmap acknowledges) as a deliberate test
3536        // edit, not a silent contract migration. Peer of the sibling
3537        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3538        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3539        // paired-half pins on the same OTP-canonical default.
3540        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3541    }
3542
3543    #[test]
3544    fn restart_strategy_default_routes_through_lifted_default() {
3545        // Composition pin: the [`Default for RestartStrategy`] impl's
3546        // return arm must route through the substrate-canonical
3547        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3548        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3549        // an inline `Self::OneForOne` with no compile-time link back to
3550        // the shared OTP-canonical `one_for_one` strategy the paired
3551        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3552        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3553        // `.unwrap_or_default()` (now
3554        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3555        // so a future rebrand of the OTP-canonical strategy default (an
3556        // OTP `rest_for_one` widening once the substrate discovers
3557        // startup-order-coupled child cohorts as the more common worker-
3558        // supervisor shape, a per-cluster overlay the operator pins
3559        // through a future `:estrategia-overrides` slot) would have had to
3560        // be threaded through the `Default` impl and the two peer routes
3561        // in lockstep or the three consumers would silently split. Byte-
3562        // parity against the lifted constant closes the split. Peer of
3563        // the sibling
3564        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3565        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3566        // composition pins on the paired `MaxIntensity` + `Period` halves.
3567        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3568    }
3569
3570    #[test]
3571    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3572        // Composition pin: the [`Default for SupervisorSpec`] impl's
3573        // struct-literal `estrategia` field must route through the
3574        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3575        // `pub const` (either directly, or via the
3576        // [`RestartStrategy::default`] impl that the sibling
3577        // `restart_strategy_default_routes_through_lifted_default` pin
3578        // already routes onto the constant). Structurally: every
3579        // `SupervisorSpec::default()` call must yield an `estrategia`
3580        // field byte-equal to the lifted constant (the three paired
3581        // defaults — the [`Default for RestartStrategy`] impl arm, the
3582        // struct-literal default arm here, and the
3583        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3584        // silently split on any future default rebrand). Peer of the
3585        // sibling
3586        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3587        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3588        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3589        // of the same `SupervisorSpec::default()` composed altitude.
3590        assert_eq!(
3591            SupervisorSpec::default().estrategia(),
3592            SUPERVISOR_ESTRATEGIA_DEFAULT,
3593        );
3594    }
3595
3596    #[test]
3597    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
3598        // Composition pin: the [`Default for SupervisorSpec`] impl must
3599        // route through the substrate-canonical
3600        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
3601        // rather than a re-hand-authored struct-literal cascade. Sharpens
3602        // the sibling per-arm
3603        // `supervisor_spec_default_*_routes_through_lifted_default` pins
3604        // from a per-field lift into a whole-struct one-source-of-truth
3605        // pin — the derived-until-now [`Default::default`] and the
3606        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3607        // construction, not by coincidence.
3608        //
3609        // A future extension of the OTP-canonical baseline (a fifth
3610        // `restart_intensity` field the Erlang/OTP `#supervisor` record
3611        // grows, a per-child-cohort split of the `restart_window` /
3612        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
3613        // CR materializer's admission-time overlay pass) reaches both
3614        // paths through exactly one edit on
3615        // [`SupervisorSpec::otp_canonical`] — the derived path could
3616        // silently disagree with the constructor's shape on any new
3617        // field whose [`Default::default`] resolves to a different arm
3618        // than the OTP-canonical baseline the constructor names, while
3619        // this delegated impl reaches the constructor directly and
3620        // picks up every future extension by construction.
3621        //
3622        // Fourth peer on the M2 / M3 typed-slot-spec
3623        // [`Default`]-through-const-ctor fold family — sibling of the
3624        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3625        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
3626        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
3627        // (91641a4), and [`crate::BehaviorSpec`]
3628        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
3629        // per-`Option`-only-typed-slot folds — extended here onto the
3630        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
3631        // is not "everything `None`" but the Erlang/OTP-canonical
3632        // `{one_for_one, 5, 60}` worker-supervisor triple.
3633        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
3634    }
3635
3636    #[test]
3637    fn supervisor_spec_otp_canonical_byte_equals_default() {
3638        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
3639        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
3640        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
3641        // pin already asserts against the [`Default::default`] path.
3642        // Sharpens the pair-invariant into a per-constructor pin so a
3643        // future extension of [`SupervisorSpec`] with a fifth field
3644        // whose OTP-canonical shape is non-`Default::default`-equivalent
3645        // trips at caixa-core test time rather than at a downstream
3646        // consumer that composed [`SupervisorSpec::otp_canonical`] with
3647        // [`SupervisorSpec::validate`] as its "canonical baseline
3648        // seed".
3649        let canonical = SupervisorSpec::otp_canonical();
3650        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
3651        assert_eq!(canonical.max_restarts, 5);
3652        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
3653        assert!(canonical.children.is_empty());
3654    }
3655
3656    #[test]
3657    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
3658        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
3659        // remain callable from a `const`-bound position so downstream
3660        // `const`-context callers wanting a canonical OTP-baseline seed
3661        // can construct one at compile time without runtime dispatch on
3662        // the derived [`Default::default`]. Peer of the sibling
3663        // `pub const fn` [`crate::LimitsSpec::empty`] /
3664        // [`crate::aplicacao::MeshPolicy::empty`] /
3665        // [`crate::BehaviorSpec::empty`] constructors on the sibling
3666        // typed-slot-spec `pub const fn` axis. If a future edit breaks
3667        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
3668        // (a non-`const` field-default helper, a non-`const`-stable
3669        // container type promotion), this evaluation fails at
3670        // build time on this file rather than at a downstream
3671        // `const`-context call site.
3672        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
3673        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
3674        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
3675        assert_eq!(
3676            CANONICAL.restart_window,
3677            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3678        );
3679        assert!(CANONICAL.children.is_empty());
3680    }
3681
3682    #[test]
3683    fn supervisor_child_restart_default_pins_otp_canonical_value() {
3684        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3685        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3686        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3687        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3688        // half of the same OTP-shape supervisor-tree default set whose
3689        // per-`:supervisor` halves the sibling
3690        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3691        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3692        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3693        // arm here surfaces a future rebrand of the per-child default (an
3694        // OTP-`transient` widening once the substrate discovers clean-
3695        // completion-aware children as the more common child shape, a
3696        // per-cluster overlay the operator pins through a future
3697        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3698        // supervision-canary roadmap acknowledges) as a deliberate test
3699        // edit, not a silent contract migration. Peer of the sibling
3700        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3701        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3702        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3703        // value pins on the per-`:supervisor` halves.
3704        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3705    }
3706
3707    #[test]
3708    fn restart_policy_default_routes_through_lifted_default() {
3709        // Composition pin: the [`Default for RestartPolicy`] impl's return
3710        // arm must route through the substrate-canonical
3711        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3712        // than a raw `Self::Permanent` arm. Prior to the lift the impl
3713        // carried an inline `Self::Permanent` with no compile-time link
3714        // back to the OTP-shape supervisor-tree default set whose three
3715        // per-`:supervisor` halves already rode through lifted constants
3716        // — so a future coherent rebrand of the set would have had to
3717        // migrate three halves through typed constants and this fourth
3718        // through a raw enum arm in lockstep or the supervisor-level and
3719        // child-level defaults would silently drift apart. Byte-parity
3720        // against the lifted constant closes the split. Peer of the
3721        // sibling
3722        // [`restart_strategy_default_routes_through_lifted_default`]
3723        // composition pin on the per-`:supervisor` `:estrategia` axis.
3724        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3725    }
3726
3727    #[test]
3728    fn child_spec_serde_default_restart_routes_through_lifted_default() {
3729        // Composition pin: the serde-side `#[serde(default)]` on
3730        // [`ChildSpec::restart`] — the wire-format author-omitted
3731        // `:children :restart` arm — must resolve onto the substrate-
3732        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3733        // (via the [`Default for RestartPolicy`] impl the sibling
3734        // `restart_policy_default_routes_through_lifted_default` pin
3735        // already routes onto the constant). Structurally: a `ChildSpec`
3736        // deserialized from a payload that omits the `restart` key must
3737        // yield a `restart` field byte-equal to the lifted constant, so
3738        // the wire-format author-omitted arm and the
3739        // [`RestartPolicy::default`] impl arm cannot silently split on any
3740        // future default rebrand. Peer of the sibling
3741        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3742        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3743        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3744        // byte-parity pins on the per-`:supervisor` halves of the same
3745        // author-omitted-slot resolution surface.
3746        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3747            .expect("ChildSpec must deserialize with the restart key omitted");
3748        assert_eq!(
3749            omitted.restart(),
3750            SUPERVISOR_CHILD_RESTART_DEFAULT,
3751            "an author-omitted :children :restart slot must degrade onto \
3752             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3753             {:?}, expected {:?})",
3754            omitted.restart(),
3755            SUPERVISOR_CHILD_RESTART_DEFAULT,
3756        );
3757    }
3758
3759    #[test]
3760    fn supervisor_max_restarts_cap_pins_canonical_value() {
3761        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3762        // 1000 — the same ceiling the peer
3763        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3764        // `:politicas :circuit-breaker :max-failures` axis (both are
3765        // "trip the next-higher protection layer after N events in a
3766        // rolling window" counters with identical
3767        // degenerate-at-the-high-end shape; uniform top edge so the
3768        // M4 CR materializers and the wasm-operator reconciler reach
3769        // for either field knowing the value is in `1..=1000`). Two
3770        // orders of magnitude above every documented Erlang/OTP /
3771        // Elixir / Riak Core / RabbitMQ production-playbook
3772        // recommendation band and below the clearly-pathological
3773        // "effectively no escalation" floor (10_000, 100_000,
3774        // u32::MAX). Pinning the literal value here surfaces a future
3775        // drift (a relaxation to 10_000, a tightening to 100) as a
3776        // deliberate test edit, not a silent contract narrowing.
3777        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3778    }
3779
3780    #[test]
3781    fn validate_rejects_empty_child_name() {
3782        let s = SupervisorSpec {
3783            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3784            ..SupervisorSpec::default()
3785        };
3786        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3787    }
3788
3789    #[test]
3790    fn validate_rejects_empty_child_version() {
3791        let s = SupervisorSpec {
3792            children: vec![child("w", "", RestartPolicy::Permanent)],
3793            ..SupervisorSpec::default()
3794        };
3795        assert!(matches!(
3796            s.validate().unwrap_err(),
3797            SupervisorError::EmptyChildVersion { .. }
3798        ));
3799    }
3800
3801    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3802
3803    #[test]
3804    fn validate_rejects_invalid_child_versao_requirement() {
3805        // The fail-before-pass-after pin: a non-empty but malformed
3806        // semver requirement (`"^bad-version"`) silently passed
3807        // `validate()` on every pre-gate codebase because the prior
3808        // shape only refused the empty string. The parse failure
3809        // surfaced far downstream at lacre-resolve time with a
3810        // `semver::Error` that didn't name which `:children` entry
3811        // carried the typo. The new gate moves the check to caixa-build
3812        // time at the source caixa.lisp — the third `:versao` typed
3813        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3814        // structural parity.
3815        let s = SupervisorSpec {
3816            children: vec![
3817                child("worker", "^0.1", RestartPolicy::Permanent),
3818                child("cache", "^bad-version", RestartPolicy::Transient),
3819            ],
3820            ..SupervisorSpec::default()
3821        };
3822        let err = s.validate().unwrap_err();
3823        assert!(
3824            matches!(
3825                err,
3826                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3827                    if caixa == "cache" && versao == "^bad-version"
3828            ),
3829            "got {err:?}"
3830        );
3831    }
3832
3833    #[test]
3834    fn validate_rejects_child_versao_with_double_caret_typo() {
3835        // `"^^0.1"` is the canonical doubled-caret typo — looks
3836        // Cargo-shaped on first glance but fails the parser because
3837        // semver doesn't accept stacked operators. Pin this
3838        // adjacent-shape footgun explicitly so a future relaxation that
3839        // accepts "looks-canonical-but-isn't" forms surfaces here.
3840        let s = SupervisorSpec {
3841            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
3842            ..SupervisorSpec::default()
3843        };
3844        let err = s.validate().unwrap_err();
3845        assert!(
3846            matches!(
3847                err,
3848                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3849                    if caixa == "worker" && versao == "^^0.1"
3850            ),
3851            "got {err:?}"
3852        );
3853    }
3854
3855    #[test]
3856    fn validate_rejects_child_versao_with_v_prefixed_tag() {
3857        // `"v0.1"` is the canonical "git-tag-shape leaking into the
3858        // semver requirement slot" typo — an author copies the
3859        // publish-side git-tag string verbatim into `:versao`, but
3860        // Cargo's semver parser rejects the leading `v`. Same
3861        // adjacent-shape footgun pinned for `:membros :versao`
3862        // (9888b13).
3863        let s = SupervisorSpec {
3864            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
3865            ..SupervisorSpec::default()
3866        };
3867        let err = s.validate().unwrap_err();
3868        assert!(
3869            matches!(
3870                err,
3871                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3872                    if caixa == "worker" && versao == "v0.1"
3873            ),
3874            "got {err:?}"
3875        );
3876    }
3877
3878    #[test]
3879    fn validate_accepts_canonical_child_versao_forms() {
3880        // The Cargo-shaped requirement forms `:deps :versao` and
3881        // `:membros :versao` already accept via
3882        // `crate::parse_requirement` must pass the children gate
3883        // without re-validating at the resolver layer. Pin every leg so
3884        // a future tightening of the canonical set surfaces here as a
3885        // test failure.
3886        for form in [
3887            "^0.1",      // caret — minor-range pin (the most common shape)
3888            "~0.1.2",    // tilde — patch-range pin
3889            "0.1.0",     // exact — single-version pin
3890            "*",         // wildcard — any version (semver::VersionReq::STAR)
3891            ">=0.1, <2", // multi-range — comma-separated comparators
3892        ] {
3893            let s = SupervisorSpec {
3894                children: vec![child("worker", form, RestartPolicy::Permanent)],
3895                ..SupervisorSpec::default()
3896            };
3897            s.validate()
3898                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3899        }
3900    }
3901
3902    #[test]
3903    fn child_versao_empty_takes_precedence_over_invalid() {
3904        // Order pin: the existing `EmptyChildVersion` diagnostic (which
3905        // doesn't try to parse) fires before the new
3906        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
3907        // `:versao` keeps its narrower error message —
3908        // `parse_requirement` would also reject `""`, but the
3909        // empty-string arm is the more self-locating diagnostic for the
3910        // author. Same ordering discipline as
3911        // `membro_versao_empty_takes_precedence_over_invalid` in
3912        // aplicacao.rs.
3913        let s = SupervisorSpec {
3914            children: vec![child("worker", "", RestartPolicy::Permanent)],
3915            ..SupervisorSpec::default()
3916        };
3917        let err = s.validate().unwrap_err();
3918        assert!(
3919            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
3920            "got {err:?}"
3921        );
3922    }
3923
3924    #[test]
3925    fn child_versao_invalid_fires_before_duplicate_check() {
3926        // Order pin: a malformed requirement on a non-duplicate entry
3927        // surfaces *its own* diagnostic (which names the offending
3928        // `:versao` string), even when a later entry would otherwise
3929        // collapse onto an earlier name. The per-entry shape gate runs
3930        // inline before the duplicate-key insert — parallel to
3931        // `membro_versao_invalid_fires_before_duplicate_check` in
3932        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
3933        let s = SupervisorSpec {
3934            children: vec![
3935                child("worker", "^bad", RestartPolicy::Permanent),
3936                child("cache", "^0.1", RestartPolicy::Transient),
3937                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3938            ],
3939            ..SupervisorSpec::default()
3940        };
3941        let err = s.validate().unwrap_err();
3942        assert!(
3943            matches!(
3944                err,
3945                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
3946            ),
3947            "got {err:?}"
3948        );
3949    }
3950
3951    #[test]
3952    fn child_versao_invalid_diagnostic_carries_offending_versao() {
3953        // The diagnostic-shape pin: the error names the offending
3954        // `:versao` value verbatim so the author can grep their
3955        // caixa.lisp without re-running the build, and carries a
3956        // non-empty `reason` from `semver::VersionReq::parse` so the
3957        // parser's own wording flows through to the diagnostic.
3958        let s = SupervisorSpec {
3959            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
3960            ..SupervisorSpec::default()
3961        };
3962        let err = s.validate().unwrap_err();
3963        let SupervisorError::ChildVersaoInvalid {
3964            caixa,
3965            versao,
3966            reason,
3967        } = err
3968        else {
3969            panic!("expected ChildVersaoInvalid, got other variant");
3970        };
3971        assert_eq!(caixa, "worker");
3972        assert_eq!(versao, "not-a-req");
3973        assert!(
3974            !reason.is_empty(),
3975            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
3976        );
3977    }
3978
3979    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
3980
3981    #[test]
3982    fn validate_rejects_child_caixa_with_uppercase() {
3983        // The canonical "I copied the Servico's display name verbatim"
3984        // typo — child caixa names are lowercase per K8s DNS-1123 label
3985        // rule. The diagnostic names the offending name and suggests the
3986        // lower-cased fix in one edit, mirroring the
3987        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
3988        let s = SupervisorSpec {
3989            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
3990            ..SupervisorSpec::default()
3991        };
3992        let err = s.validate().unwrap_err();
3993        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3994            panic!("expected ChildCaixaInvalid, got other variant");
3995        };
3996        assert_eq!(caixa, "Worker");
3997        assert!(
3998            reason.contains("uppercase"),
3999            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4000        );
4001        assert!(
4002            reason.contains("\"worker\""),
4003            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4004        );
4005    }
4006
4007    #[test]
4008    fn validate_rejects_child_caixa_with_underscore() {
4009        // The canonical "I'm thinking of a Python module / Postgres
4010        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4011        // label schema. K8s rejects `metadata.name: my_worker` at
4012        // admission time with an opaque `field is invalid` (no source-
4013        // citing diagnostic). The gate moves it to caixa-build time.
4014        let s = SupervisorSpec {
4015            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4016            ..SupervisorSpec::default()
4017        };
4018        let err = s.validate().unwrap_err();
4019        assert!(
4020            matches!(
4021                err,
4022                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4023                    if caixa == "my_worker" && reason.contains('_')
4024            ),
4025            "got {err:?}"
4026        );
4027    }
4028
4029    #[test]
4030    fn validate_rejects_child_caixa_with_dot() {
4031        // A `:children :caixa` entry is a single DNS-1123 label, not a
4032        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4033        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4034        // (3f9d7a0) on the peer name axis.
4035        let s = SupervisorSpec {
4036            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4037            ..SupervisorSpec::default()
4038        };
4039        let err = s.validate().unwrap_err();
4040        assert!(
4041            matches!(
4042                err,
4043                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4044                    if caixa == "team.worker" && reason.contains('.')
4045            ),
4046            "got {err:?}"
4047        );
4048    }
4049
4050    #[test]
4051    fn validate_rejects_child_caixa_with_leading_hyphen() {
4052        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4053        // with an alphanumeric. The K8s apiserver rejects `-worker`
4054        // outright; the renderer would emit a `metadata.name: "-worker"`
4055        // that fails admission far from the source caixa.lisp.
4056        let s = SupervisorSpec {
4057            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4058            ..SupervisorSpec::default()
4059        };
4060        let err = s.validate().unwrap_err();
4061        assert!(
4062            matches!(
4063                err,
4064                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4065                    if caixa == "-worker" && reason.contains("start and end")
4066            ),
4067            "got {err:?}"
4068        );
4069    }
4070
4071    #[test]
4072    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4073        // The symmetric arm of the boundary rule. Pin separately so
4074        // both ends of the label are covered against a future relaxation
4075        // that only checks one boundary.
4076        let s = SupervisorSpec {
4077            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4078            ..SupervisorSpec::default()
4079        };
4080        let err = s.validate().unwrap_err();
4081        assert!(
4082            matches!(
4083                err,
4084                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4085                    if caixa == "worker-"
4086            ),
4087            "got {err:?}"
4088        );
4089    }
4090
4091    #[test]
4092    fn validate_rejects_child_caixa_with_unicode() {
4093        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4094        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4095        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4096        // by the first byte that fails the `[a-z0-9-]` predicate.
4097        let s = SupervisorSpec {
4098            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4099            ..SupervisorSpec::default()
4100        };
4101        let err = s.validate().unwrap_err();
4102        assert!(
4103            matches!(
4104                err,
4105                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4106                    if caixa == "café"
4107            ),
4108            "got {err:?}"
4109        );
4110    }
4111
4112    #[test]
4113    fn validate_rejects_child_caixa_with_whitespace() {
4114        // Whitespace is the canonical "I pasted from a sketch / doc"
4115        // footgun. The apiserver rejects every `metadata.name` value
4116        // carrying whitespace; pin the gate fires at the right boundary.
4117        let s = SupervisorSpec {
4118            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4119            ..SupervisorSpec::default()
4120        };
4121        let err = s.validate().unwrap_err();
4122        assert!(
4123            matches!(
4124                err,
4125                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4126                    if caixa == "my worker"
4127            ),
4128            "got {err:?}"
4129        );
4130    }
4131
4132    #[test]
4133    fn validate_rejects_child_caixa_too_long() {
4134        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4135        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4136        // axis over the limit at admission time. The diagnostic names
4137        // both the cap and the actual length so the author can shorten
4138        // in one edit, mirroring `rejects_membro_caixa_too_long`
4139        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4140        let too_long = "a".repeat(64);
4141        let s = SupervisorSpec {
4142            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4143            ..SupervisorSpec::default()
4144        };
4145        let err = s.validate().unwrap_err();
4146        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4147            panic!("expected ChildCaixaInvalid, got other variant");
4148        };
4149        assert_eq!(caixa, too_long);
4150        assert!(
4151            reason.contains("63"),
4152            "diagnostic must name the 63-byte cap (got: {reason:?})"
4153        );
4154        assert!(
4155            reason.contains("64"),
4156            "diagnostic must name the actual length (got: {reason:?})"
4157        );
4158    }
4159
4160    #[test]
4161    fn child_caixa_max_length_validates() {
4162        // The 63-byte boundary control pin — exactly-at-the-cap is
4163        // accepted, mirroring `membro_caixa_max_length_validates`
4164        // (3f9d7a0) and `placement_cluster_max_length_validates`
4165        // (6cbb900). Pinned separately so a future off-by-one tightening
4166        // surfaces here.
4167        let max_label = "a".repeat(63);
4168        let s = SupervisorSpec {
4169            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4170            ..SupervisorSpec::default()
4171        };
4172        s.validate().unwrap();
4173    }
4174
4175    #[test]
4176    fn validate_accepts_canonical_child_caixa_forms() {
4177        // The realistic shapes a supervised child's `:caixa` carries —
4178        // single-word `worker`, version-suffixed `cache-v2`, single-char
4179        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4180        // `payment-retry`, all-digit `0`. Pin every leg so a future
4181        // tightening (e.g. requiring a leading lowercase letter) surfaces
4182        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4183        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4184        // (6cbb900).
4185        for form in [
4186            "worker",
4187            "cache-v2",
4188            "a",
4189            "db",
4190            "2-pool",
4191            "payment-retry",
4192            "0",
4193        ] {
4194            let s = SupervisorSpec {
4195                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4196                ..SupervisorSpec::default()
4197            };
4198            s.validate()
4199                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4200        }
4201    }
4202
4203    #[test]
4204    fn child_caixa_empty_takes_precedence_over_invalid() {
4205        // Order pin: the existing `EmptyChildName` diagnostic (which
4206        // doesn't try to parse the DNS-1123 shape) fires before the new
4207        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4208        // its narrower error message — `is_dns_1123_label` would reject
4209        // the empty string too (boundary check on the first byte), but
4210        // the empty-string arm is the more self-locating diagnostic for
4211        // the author. Same ordering discipline as
4212        // `membro_caixa_empty_takes_precedence_over_invalid` in
4213        // aplicacao.rs.
4214        let s = SupervisorSpec {
4215            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4216            ..SupervisorSpec::default()
4217        };
4218        let err = s.validate().unwrap_err();
4219        assert_eq!(err, SupervisorError::EmptyChildName);
4220    }
4221
4222    #[test]
4223    fn child_caixa_invalid_fires_before_versao_check() {
4224        // Order pin: the per-axis shape gate runs inline before the
4225        // per-entry versao check, so a malformed `:caixa` on an entry
4226        // whose `:versao` would also fail surfaces the more self-
4227        // locating name-axis diagnostic first. Parallel to
4228        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4229        // and `placement_cluster_invalid_fires_before_duplicate_check`
4230        // (6cbb900).
4231        let s = SupervisorSpec {
4232            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4233            ..SupervisorSpec::default()
4234        };
4235        let err = s.validate().unwrap_err();
4236        assert!(
4237            matches!(
4238                err,
4239                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4240            ),
4241            "got {err:?}"
4242        );
4243    }
4244
4245    #[test]
4246    fn child_caixa_invalid_fires_before_duplicate_check() {
4247        // Order pin: a malformed name on a non-duplicate entry surfaces
4248        // its own diagnostic, even when a later entry would otherwise
4249        // collapse onto an earlier name. The per-entry shape gate runs
4250        // inline before the duplicate-key HashSet insert, mirroring
4251        // `placement_cluster_invalid_fires_before_duplicate_check`
4252        // (6cbb900).
4253        let s = SupervisorSpec {
4254            children: vec![
4255                child("Worker", "^0.1", RestartPolicy::Permanent),
4256                child("cache", "^0.1", RestartPolicy::Transient),
4257                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4258            ],
4259            ..SupervisorSpec::default()
4260        };
4261        let err = s.validate().unwrap_err();
4262        assert!(
4263            matches!(
4264                err,
4265                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4266            ),
4267            "got {err:?}"
4268        );
4269    }
4270
4271    #[test]
4272    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4273        // The diagnostic-shape pin: the error names the offending
4274        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4275        // the author can grep their caixa.lisp without re-running the
4276        // build. Mirrors the diagnostic-shape sweep on every prior
4277        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4278        let s = SupervisorSpec {
4279            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4280            ..SupervisorSpec::default()
4281        };
4282        let err = s.validate().unwrap_err();
4283        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4284            panic!("expected ChildCaixaInvalid, got other variant");
4285        };
4286        assert_eq!(caixa, "My_Worker");
4287        assert!(
4288            !reason.is_empty(),
4289            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4290        );
4291    }
4292
4293    // ── value-shape: zero restart_window + duplicate child names ──────────
4294
4295    #[test]
4296    fn validate_accepts_none_restart_window() {
4297        // Omitted `:restart-window` is the "never reset" sentinel —
4298        // valid by design. Mirrors :limits axes where None = unbounded.
4299        let s = SupervisorSpec {
4300            restart_window: None,
4301            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4302            ..SupervisorSpec::default()
4303        };
4304        s.validate().unwrap();
4305    }
4306
4307    #[test]
4308    fn validate_rejects_zero_restart_window() {
4309        // Same "0 means the opposite of what you think" footgun closed
4310        // for :politicas :timeout (Envoy treats 0s as infinite) and
4311        // :limits :wall-clock (wasmtime traps before the call starts).
4312        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4313        let s = SupervisorSpec {
4314            restart_window: Some(Duration::ZERO),
4315            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4316            ..SupervisorSpec::default()
4317        };
4318        assert_eq!(
4319            s.validate().unwrap_err(),
4320            SupervisorError::RestartWindowZero
4321        );
4322    }
4323
4324    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4325    //
4326    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4327    // the integer-millisecond canonical-form gate — peer with
4328    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4329    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4330    // path is already gated at the shared codec layer (see
4331    // `restart_window_serde_rejects_fractional_seconds`); this arm
4332    // closes the programmatic-struct-literal path the codec gate can't
4333    // see.
4334
4335    #[test]
4336    fn validate_rejects_sub_millisecond_restart_window() {
4337        // The fail-before-pass-after pin: a programmatic
4338        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4339        // `validate` on every pre-gate codebase, then truncated to
4340        // `as_millis() == 1` on first serialize — the shared codec
4341        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4342        // 1_000_000 ns, the typed `restart_window` no longer matches
4343        // its rendered form.
4344        let s = SupervisorSpec {
4345            restart_window: Some(Duration::from_micros(1500)),
4346            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4347            ..SupervisorSpec::default()
4348        };
4349        match s.validate().unwrap_err() {
4350            SupervisorError::RestartWindowNotCanonical { window } => {
4351                assert_eq!(window, Duration::from_micros(1500));
4352            }
4353            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4354        }
4355    }
4356
4357    #[test]
4358    fn validate_rejects_one_nanosecond_restart_window() {
4359        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4360        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4361        // so the shared codec emits the literal `"0s"` — the next
4362        // serde round-trip would parse back to `Duration::ZERO`, which
4363        // the `RestartWindowZero` arm then rejects on re-validate. The
4364        // canonical-form gate at this layer surfaces a self-locating
4365        // diagnostic naming the offending Duration verbatim rather
4366        // than a downstream `RestartWindowZero` whose remediation
4367        // points at omitting the slot.
4368        let s = SupervisorSpec {
4369            restart_window: Some(Duration::from_nanos(1)),
4370            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4371            ..SupervisorSpec::default()
4372        };
4373        match s.validate().unwrap_err() {
4374            SupervisorError::RestartWindowNotCanonical { window } => {
4375                assert_eq!(window, Duration::from_nanos(1));
4376            }
4377            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4378        }
4379    }
4380
4381    #[test]
4382    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4383        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4384        // 1_000_001 ns is structurally past the integer-ms granularity
4385        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4386        // trip would truncate to `1ms` and the consumer would observe
4387        // a 1-ns drift on every emit. Same boundary the peer
4388        // `validate_rejects_nanosecond_past_canonical_boundary` test
4389        // in limits.rs pins for the `:limits :wall-clock` axis.
4390        let w = Duration::from_nanos(1_000_001);
4391        let s = SupervisorSpec {
4392            restart_window: Some(w),
4393            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4394            ..SupervisorSpec::default()
4395        };
4396        assert_eq!(
4397            s.validate().unwrap_err(),
4398            SupervisorError::RestartWindowNotCanonical { window: w }
4399        );
4400    }
4401
4402    #[test]
4403    fn validate_accepts_integer_millisecond_restart_window_values() {
4404        // The positive-control sweep: every `Duration` the shared
4405        // codec can round-trip losslessly — the canonical
4406        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4407        // pair emits and accepts — passes `validate` without
4408        // surfacing the new canonical-form arm. Mirrors
4409        // `validate_accepts_integer_millisecond_wall_clock_values` on
4410        // the sibling `:limits :wall-clock` axis.
4411        for w in [
4412            Duration::from_millis(1),
4413            Duration::from_millis(500),
4414            Duration::from_millis(1500),
4415            Duration::from_secs(1),
4416            Duration::from_secs(30),
4417            Duration::from_secs(60),
4418            Duration::from_secs(120),
4419            Duration::from_secs(3600),
4420        ] {
4421            let s = SupervisorSpec {
4422                restart_window: Some(w),
4423                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4424                ..SupervisorSpec::default()
4425            };
4426            s.validate()
4427                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4428        }
4429    }
4430
4431    #[test]
4432    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4433        // Cross-arm ordering pin: `Duration::ZERO` has
4434        // `subsec_nanos() == 0` and would otherwise pass the
4435        // canonical-form arm — the zero-floor arm must fire first so
4436        // the more self-locating `RestartWindowZero` diagnostic (with
4437        // its omit-axis remediation directly named) leads. Same
4438        // posture every peer zero-then-shape gate uses
4439        // (`WallClockZero` → `WallClockNotCanonical`,
4440        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4441        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4442        let s = SupervisorSpec {
4443            restart_window: Some(Duration::ZERO),
4444            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4445            ..SupervisorSpec::default()
4446        };
4447        assert_eq!(
4448            s.validate().unwrap_err(),
4449            SupervisorError::RestartWindowZero
4450        );
4451    }
4452
4453    #[test]
4454    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4455        // Diagnostic-shape pin: the canonical-form arm names the
4456        // offending `Duration` verbatim so the author's grep lands on
4457        // the field's value, not a generic "duration not canonical"
4458        // message. Same shape every other typed-canonical-form arm
4459        // on this surface carries (`WallClockNotCanonical` carries
4460        // the offending `Duration` verbatim,
4461        // `PolicyTimeoutNotCanonical` carries the offending
4462        // `Duration` verbatim).
4463        let w = Duration::from_micros(500);
4464        let s = SupervisorSpec {
4465            restart_window: Some(w),
4466            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4467            ..SupervisorSpec::default()
4468        };
4469        let err = s.validate().unwrap_err();
4470        let msg = err.to_string();
4471        assert!(
4472            msg.contains("500"),
4473            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4474        );
4475        assert!(
4476            msg.contains("sub-millisecond"),
4477            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4478        );
4479    }
4480
4481    #[test]
4482    fn restart_window_validated_value_round_trips_through_codec() {
4483        // The structural property the canonical-ms gate enforces:
4484        // every `SupervisorSpec::restart_window` past
4485        // `SupervisorSpec::validate` round-trips losslessly through
4486        // the shared duration codec (serialize → string →
4487        // deserialize → equal value). Pin this end-to-end so a future
4488        // change to either side (the validate gate's accepted
4489        // granularity, the codec's parse/render unit set) that breaks
4490        // the alignment surfaces here. Peer of
4491        // `wall_clock_validated_value_round_trips_through_codec` on
4492        // the sibling `:limits :wall-clock` axis.
4493        for w in [
4494            Duration::from_millis(1),
4495            Duration::from_millis(1500),
4496            Duration::from_secs(30),
4497            Duration::from_secs(3600),
4498        ] {
4499            let s = SupervisorSpec {
4500                restart_window: Some(w),
4501                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4502                ..SupervisorSpec::default()
4503            };
4504            s.validate().unwrap();
4505            let json = serde_json::to_string(&s).unwrap();
4506            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4507            assert_eq!(back.restart_window, Some(w));
4508        }
4509    }
4510
4511    // ── value-shape: upper cap on :restart-window ─────────────────────────
4512    //
4513    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4514    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4515    // `:politicas :timeout` (2e8ee7e), and `:politicas
4516    // :circuit-breaker :window` (379a814). Brackets the typed
4517    // `:restart-window` axis structurally: every validated value lies
4518    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4519    // granularity, closing the
4520    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4521    // zero-floor-and-canonical-form-only checks left open.
4522
4523    #[test]
4524    fn validate_rejects_restart_window_above_cap() {
4525        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4526        // structurally one canonical-tick past the
4527        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4528        // integer-millisecond magnitude the canonical-form arm above
4529        // accepts cleanly, that the shared duration codec round-trips
4530        // losslessly as `"3601s"`, and that silently passed validate on
4531        // every pre-gate codebase because the typed slot's only checks
4532        // were the zero-floor and canonical-form arms. The runtime
4533        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4534        // Period reconciler, the future wasm-operator's per-supervisor
4535        // restart-intensity counter) reaches for a `Duration` so long
4536        // no realistic restart-recovery pattern resets the counter,
4537        // far from the source caixa.lisp.
4538        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4539        let s = SupervisorSpec {
4540            restart_window: Some(w),
4541            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4542            ..SupervisorSpec::default()
4543        };
4544        assert_eq!(
4545            s.validate().unwrap_err(),
4546            SupervisorError::RestartWindowExceedsCap { window: w }
4547        );
4548    }
4549
4550    #[test]
4551    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4552        // Boundary case: exactly 1ms past the cap (the granularity the
4553        // canonical-form gate enforces). Catches a future "strictly
4554        // less than" half-measure and pins the diagnostic to name the
4555        // offending `Duration` verbatim. Peer of
4556        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4557        // `rejects_policy_timeout_one_millisecond_above_cap` /
4558        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4559        // on the sibling typed-`Duration` axes' top edges.
4560        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4561        let s = SupervisorSpec {
4562            restart_window: Some(w),
4563            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4564            ..SupervisorSpec::default()
4565        };
4566        assert_eq!(
4567            s.validate().unwrap_err(),
4568            SupervisorError::RestartWindowExceedsCap { window: w }
4569        );
4570    }
4571
4572    #[test]
4573    fn validate_rejects_restart_window_far_above_cap() {
4574        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4575        // `(:restart-window "7d")`, or any "I want a lifetime counter
4576        // but wrote a `<integer>h` magnitude anyway" typo — values the
4577        // canonical-form arm accepts as integer-millisecond magnitudes,
4578        // the codec round-trips losslessly through serde, but the
4579        // operator's `MaxIntensity / Period` reconciler cannot honor
4580        // as a meaningful rolling window. Until this gate landed
4581        // validate accepted them. Pin the common above-cap values (24h,
4582        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4583        // surfaces here.
4584        for w in [
4585            Duration::from_secs(86_400),    // 24h
4586            Duration::from_secs(604_800),   // 7d
4587            Duration::from_secs(1_000_000), // ~11.5 days
4588        ] {
4589            let s = SupervisorSpec {
4590                restart_window: Some(w),
4591                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4592                ..SupervisorSpec::default()
4593            };
4594            assert_eq!(
4595                s.validate().unwrap_err(),
4596                SupervisorError::RestartWindowExceedsCap { window: w }
4597            );
4598        }
4599    }
4600
4601    #[test]
4602    fn validate_accepts_restart_window_at_cap() {
4603        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4604        // (1h) — must validate. The cap is inclusive on the top edge,
4605        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4606        // [`crate::POLICY_TIMEOUT_MAX`] /
4607        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4608        // capped axes. Pin the boundary explicitly so a future
4609        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4610        // instead of `>`) surfaces here as a test failure rather than a
4611        // silent contract narrowing.
4612        let s = SupervisorSpec {
4613            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4614            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4615            ..SupervisorSpec::default()
4616        };
4617        s.validate()
4618            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4619    }
4620
4621    #[test]
4622    fn validate_accepts_restart_window_typical_values() {
4623        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4624        // per-supervisor production-playbook band positive-control
4625        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4626        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4627        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4628        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4629        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4630        // default recommend (5s..=300s) must pass, plus a sweep
4631        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4632        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4633        // on the sibling `:limits :wall-clock` axis.
4634        for w in [
4635            Duration::from_millis(1),
4636            Duration::from_millis(500),
4637            Duration::from_secs(1),
4638            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4639            Duration::from_secs(10), // Riak Core lower
4640            Duration::from_secs(30),
4641            Duration::from_secs(60),  // Learn You Some Erlang default
4642            Duration::from_secs(120), // OTP supervisor MaxT typical
4643            Duration::from_secs(300), // Riak Core upper
4644            Duration::from_secs(900), // 15m
4645            Duration::from_secs(1800),
4646            Duration::from_secs(3600), // exactly 1h, the cap
4647        ] {
4648            let s = SupervisorSpec {
4649                restart_window: Some(w),
4650                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4651                ..SupervisorSpec::default()
4652            };
4653            s.validate()
4654                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4655        }
4656    }
4657
4658    #[test]
4659    fn restart_window_zero_takes_precedence_over_cap() {
4660        // The cross-arm ordering pin: `Duration::ZERO` is structurally
4661        // outside both `>= 1ms` (zero-floor) and `<=
4662        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4663        // diagnostic is the more self-locating one (it directly names
4664        // the omit-axis remediation), so the validate gate must fire
4665        // on zero first. Same shape every other zero-then-cap ordering
4666        // on this surface uses (`WallClockZero` then
4667        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4668        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4669        // `PolicyBreakerWindowExceedsCap`).
4670        let s = SupervisorSpec {
4671            restart_window: Some(Duration::ZERO),
4672            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4673            ..SupervisorSpec::default()
4674        };
4675        assert_eq!(
4676            s.validate().unwrap_err(),
4677            SupervisorError::RestartWindowZero,
4678            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4679        );
4680    }
4681
4682    #[test]
4683    fn restart_window_canonical_takes_precedence_over_cap() {
4684        // The cross-arm ordering pin: a `Duration` that is *both*
4685        // sub-millisecond (non-canonical-form) and structurally above
4686        // the cap surfaces the canonical-form diagnostic first,
4687        // because the round-trip-shape break is the more fundamental
4688        // issue (the value can't even round-trip through the codec,
4689        // so the cap diagnostic naming `1ms..=1h` would be misleading
4690        // — there's no integer-ms form of the offending value). Pin
4691        // the order so a future refactor that reorders the arms
4692        // surfaces here as a test failure rather than a silent
4693        // diagnostic regression. Peer of
4694        // `wall_clock_canonical_takes_precedence_over_cap` /
4695        // `policy_timeout_canonical_takes_precedence_over_cap`.
4696        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4697        let s = SupervisorSpec {
4698            restart_window: Some(w),
4699            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4700            ..SupervisorSpec::default()
4701        };
4702        assert_eq!(
4703            s.validate().unwrap_err(),
4704            SupervisorError::RestartWindowNotCanonical { window: w },
4705            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4706        );
4707    }
4708
4709    #[test]
4710    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4711        // The cross-arm ordering pin between the `:max-restarts` cap
4712        // and the sibling `:restart-window` cap. A supervisor carrying
4713        // both an over-cap `max_restarts` AND an over-cap window must
4714        // surface the `MaxRestartsExceedsCap` diagnostic first — the
4715        // cap arm is wired immediately after the zero-restart arm and
4716        // strictly before every window-axis arm (zero / canonical /
4717        // cap), so the offending value the diagnostic names matches
4718        // the order the author would discover the gates by reading
4719        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4720        // order so a future refactor that reorders the arms surfaces
4721        // here as a test failure rather than a silent diagnostic
4722        // regression. Peer of
4723        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4724        // on the sibling zero / canonical window arms.
4725        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4726        let s = SupervisorSpec {
4727            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4728            restart_window: Some(w),
4729            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4730            ..SupervisorSpec::default()
4731        };
4732        assert_eq!(
4733            s.validate().unwrap_err(),
4734            SupervisorError::MaxRestartsExceedsCap {
4735                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4736            },
4737            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4738        );
4739    }
4740
4741    #[test]
4742    fn restart_window_cap_diagnostic_carries_offending_value() {
4743        // The diagnostic-shape pin: the offending `Duration` is
4744        // carried verbatim into the
4745        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4746        // surfaced error message names the value the author wrote,
4747        // not just the cap. Same self-locating diagnostic shape every
4748        // other typed-cap arm on this surface carries
4749        // (`WallClockExceedsCap` carries the offending `Duration`
4750        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4751        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4752        // the offending `Duration` verbatim).
4753        let w = Duration::from_secs(7200); // 2h
4754        let s = SupervisorSpec {
4755            restart_window: Some(w),
4756            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4757            ..SupervisorSpec::default()
4758        };
4759        let err = s.validate().unwrap_err();
4760        assert!(
4761            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4762            "got {err:?}"
4763        );
4764        let msg = err.to_string();
4765        assert!(
4766            msg.contains("7200"),
4767            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4768        );
4769    }
4770
4771    #[test]
4772    fn supervisor_restart_window_cap_pins_canonical_value() {
4773        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4774        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4775        // shared duration codec emits as a clean canonical string
4776        // (`"<n>h"`). Pinning the literal value here surfaces a future
4777        // drift (a relaxation to 24h, a tightening to 5m) as a
4778        // deliberate test edit, not a silent contract narrowing.
4779        //
4780        // The four typed-`Duration` caps on the validation surface
4781        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4782        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4783        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4784        // single uniform top edge at the codec's largest emitted unit
4785        // — a structural-property invariant the equality assertions
4786        // here enshrine, so a future drift on any of the four
4787        // surfaces as a deliberate test edit. Same shape every other
4788        // typed-cap value pin uses
4789        // (`wall_clock_cap_pins_canonical_value`,
4790        // `policy_timeout_cap_pins_canonical_value`,
4791        // `circuit_breaker_window_cap_pins_canonical_value`).
4792        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4793        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4794        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4795        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4796        assert_eq!(
4797            SUPERVISOR_RESTART_WINDOW_MAX,
4798            crate::POLICY_BREAKER_WINDOW_MAX
4799        );
4800    }
4801
4802    #[test]
4803    fn restart_window_cap_value_round_trips_through_codec() {
4804        // The codec round-trip property the cap arm preserves: the
4805        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4806        // through the shared duration codec — every value at the cap
4807        // serializes to the canonical `"1h"` form and parses back
4808        // identically. Pin the round-trip so a future change to the
4809        // codec's unit set or to the cap's magnitude that breaks the
4810        // round-trip property surfaces here. Peer of
4811        // `wall_clock_cap_value_round_trips_through_codec` on the
4812        // sibling `:limits :wall-clock` axis.
4813        let s = SupervisorSpec {
4814            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4815            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4816            ..SupervisorSpec::default()
4817        };
4818        s.validate().unwrap();
4819        let json = serde_json::to_string(&s).unwrap();
4820        assert!(
4821            json.contains("\"1h\""),
4822            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
4823        );
4824        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4825        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
4826    }
4827
4828    #[test]
4829    fn validate_rejects_duplicate_child_caixa() {
4830        // Two children with the same :caixa render to two ComputeUnits
4831        // with the same name in the cluster's HelmRelease values —
4832        // one silently overwrites the other. Erlang/OTP's child_spec.id
4833        // is required-unique per supervisor; same set-not-multiset
4834        // discipline applied here as for :membros / :placement
4835        // :clusters / :entrada :paths.
4836        let s = SupervisorSpec {
4837            children: vec![
4838                child("worker", "^0.1", RestartPolicy::Permanent),
4839                child("cache", "^0.1", RestartPolicy::Transient),
4840                child("worker", "^0.2", RestartPolicy::Permanent),
4841            ],
4842            ..SupervisorSpec::default()
4843        };
4844        let err = s.validate().unwrap_err();
4845        assert!(
4846            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
4847            "got {err:?}"
4848        );
4849    }
4850
4851    #[test]
4852    fn validate_duplicate_child_diagnostic_names_first_collision() {
4853        // Iteration walks the :children list in declaration order —
4854        // the diagnostic names the first repeat, deterministically,
4855        // even when multiple names duplicate.
4856        let s = SupervisorSpec {
4857            children: vec![
4858                child("a", "^0.1", RestartPolicy::Permanent),
4859                child("b", "^0.1", RestartPolicy::Permanent),
4860                child("a", "^0.1", RestartPolicy::Permanent),
4861                child("b", "^0.1", RestartPolicy::Permanent),
4862            ],
4863            ..SupervisorSpec::default()
4864        };
4865        let err = s.validate().unwrap_err();
4866        assert!(
4867            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
4868            "got {err:?}"
4869        );
4870    }
4871
4872    // ── self-supervision cross-slot gate ──────────────────────────
4873
4874    #[test]
4875    fn validate_no_self_supervision_rejects_self_referential_child() {
4876        // A supervisor whose `:children` lists its own `:nome` is a
4877        // one-node reconciliation cycle — rejected, naming the parent.
4878        let children = vec![
4879            child("worker", "^0.1", RestartPolicy::Permanent),
4880            child("orquestra", "^0.1", RestartPolicy::Permanent),
4881        ];
4882        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
4883        assert!(
4884            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
4885            "got {err:?}"
4886        );
4887    }
4888
4889    #[test]
4890    fn validate_no_self_supervision_accepts_distinct_children() {
4891        // Positive control: distinct child names (including a child that
4892        // is itself a supervisor — nested trees are valid OTP) pass.
4893        let children = vec![
4894            child("worker", "^0.1", RestartPolicy::Permanent),
4895            child("sub-tree", "^0.1", RestartPolicy::Permanent),
4896        ];
4897        validate_no_self_supervision(&children, "orquestra").unwrap();
4898    }
4899
4900    #[test]
4901    fn validate_no_self_supervision_empty_children_is_ok() {
4902        // SimpleOneForOne / no-static-children supervisors have nothing
4903        // to self-reference — the gate is vacuously satisfied.
4904        validate_no_self_supervision(&[], "orquestra").unwrap();
4905    }
4906
4907    #[test]
4908    fn validate_simple_one_for_one_skips_uniqueness_check() {
4909        // SimpleOneForOne supervisors carry no static children — the
4910        // duplicate-child loop never runs. A zero-window declaration
4911        // on a SimpleOneForOne supervisor still trips the window check
4912        // (window applies to dynamic children too).
4913        let s = SupervisorSpec {
4914            estrategia: RestartStrategy::SimpleOneForOne,
4915            restart_window: None,
4916            children: vec![],
4917            ..SupervisorSpec::default()
4918        };
4919        s.validate().unwrap();
4920        let s_zero = SupervisorSpec {
4921            estrategia: RestartStrategy::SimpleOneForOne,
4922            restart_window: Some(Duration::ZERO),
4923            children: vec![],
4924            ..SupervisorSpec::default()
4925        };
4926        assert_eq!(
4927            s_zero.validate().unwrap_err(),
4928            SupervisorError::RestartWindowZero
4929        );
4930    }
4931
4932    #[test]
4933    fn validate_zero_window_runs_after_max_restarts_check() {
4934        // Pin the order: max_restarts == 0 fires before
4935        // restart_window == 0s, so an author with both wrong sees the
4936        // counter-axis diagnostic first (matches the order in the
4937        // struct and in the doc comment).
4938        let s = SupervisorSpec {
4939            max_restarts: 0,
4940            restart_window: Some(Duration::ZERO),
4941            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4942            ..SupervisorSpec::default()
4943        };
4944        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4945    }
4946
4947    #[test]
4948    fn round_trip_all_strategies() {
4949        for &strat in RestartStrategy::ALL {
4950            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
4951            // shape partition through the [`gen_platform::IsVariant`]
4952            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
4953            // predicate rather than the raw
4954            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
4955            // open-coded pattern-match — same closed-set-typed-enum
4956            // arm-discriminator dispatch discipline the sibling
4957            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
4958            // (915a934) extended onto its two paired positive / negated
4959            // `matches!` filter sites, and the sibling
4960            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
4961            // predicate convergence (766ec63) extended onto the M3 mesh-
4962            // slot per-`:placement` distribution-strategy `matches!`
4963            // discriminator axis. See the sibling
4964            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
4965            // fixture and the peer `manifest::tests::
4966            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
4967            // fixture — all three sites (the last unlifted
4968            // `matches!`-based arm-discriminator axis on the OTP-shape
4969            // supervisor sibling-restart-strategy closed-set typed enum,
4970            // acknowledged in 915a934's Prior-commits footnote as the
4971            // outstanding follow-up) now consult one typed dispatch on
4972            // the substrate primitive.
4973            let s = SupervisorSpec {
4974                estrategia: strat,
4975                children: if strat.is_simple_one_for_one() {
4976                    vec![]
4977                } else {
4978                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
4979                },
4980                ..SupervisorSpec::default()
4981            };
4982            let json = serde_json::to_string(&s).unwrap();
4983            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4984            assert_eq!(s, back);
4985        }
4986    }
4987
4988    #[test]
4989    fn round_trip_all_restart_policies() {
4990        for policy in [
4991            RestartPolicy::Permanent,
4992            RestartPolicy::Temporary,
4993            RestartPolicy::Transient,
4994        ] {
4995            let c = child("w", "^0.1", policy);
4996            let json = serde_json::to_string(&c).unwrap();
4997            let back: ChildSpec = serde_json::from_str(&json).unwrap();
4998            assert_eq!(c, back);
4999        }
5000    }
5001
5002    #[test]
5003    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5004        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5005        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5006        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5007        // is the only variant that satisfies `.is_simple_one_for_one()`;
5008        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5009        // / `RestForOne`) returns `false`. This pin makes the partition
5010        // invariant load-bearing at caixa-core test time so a future
5011        // derive regression (a hole that returns `false` for
5012        // `SimpleOneForOne` too, or a byte-collision that flips a second
5013        // variant to `true`) trips here rather than laundering the arm
5014        // at the three test-fixture builder sites (a hole flips the
5015        // `SimpleOneForOne` fixture to carry a non-empty children list
5016        // and the subsequent `SupervisorSpec::validate` would refuse the
5017        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5018        // a collision flips a peer strategy's fixture to carry an empty
5019        // children list and the subsequent `validate` would refuse with
5020        // [`SupervisorError::NoChildren`] — either way, the pin fires
5021        // here, at the derive site, rather than at the fixture-refusal
5022        // site far away). Peer of the sibling
5023        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5024        // (915a934) pin on the M2 OTP-appup axis and the sibling
5025        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5026        // pin on the M0 `:kind` axis.
5027        let cases: &[(RestartStrategy, bool)] = &[
5028            (RestartStrategy::OneForOne, false),
5029            (RestartStrategy::OneForAll, false),
5030            (RestartStrategy::RestForOne, false),
5031            (RestartStrategy::SimpleOneForOne, true),
5032        ];
5033        for (variant, expected) in cases {
5034            assert_eq!(
5035                variant.is_simple_one_for_one(),
5036                *expected,
5037                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5038                 return {expected} (partition invariant on the \
5039                 IsVariant-derived arm-discriminator predicate — every \
5040                 test-fixture site that partitions the `:children` slot \
5041                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5042                 off this typed dispatch, so a derive regression must \
5043                 surface here rather than at the fixture-refusal site)"
5044            );
5045        }
5046    }
5047
5048    #[test]
5049    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5050        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5051        // fixture-shape partition against the pre-lift
5052        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5053        // pattern-match every test-fixture builder site previously
5054        // coupled to inline. Asserts the two projections agree byte-for-
5055        // byte on every arm of the enum, so a future derive regression
5056        // that flipped either predicate's arm-set would surface here at
5057        // caixa-core test time rather than at the three fixture-builder
5058        // sites (`supervisor::tests::round_trip_all_strategies`,
5059        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5060        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5061        // far from the derive site. Same peer-shape byte-identity pin
5062        // every sibling `IsVariant`-derive-routed convergence carries on
5063        // the substrate's closed-set typed-enum surface (peer of
5064        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5065        // on the M2 OTP-appup axis).
5066        for &strat in RestartStrategy::ALL {
5067            let via_predicate = strat.is_simple_one_for_one();
5068            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5069            assert_eq!(
5070                via_predicate, via_matches,
5071                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5072                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5073                 the pre-lift open-coded pattern and the \
5074                 IsVariant-derived predicate are the same axis, \
5075                 one typed dispatch"
5076            );
5077        }
5078    }
5079
5080    #[test]
5081    fn duration_codec_round_trip_canonical_units() {
5082        // Note the canonical-form rule: durations serialize to the
5083        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5084        // "60s" — but the round-trip preserves the underlying Duration.
5085        let cases = [
5086            ("30s", Duration::from_secs(30)),
5087            ("5m", Duration::from_secs(300)),
5088            ("1h", Duration::from_secs(3600)),
5089            ("500ms", Duration::from_millis(500)),
5090        ];
5091        for (lit, dur) in cases {
5092            let s = SupervisorSpec {
5093                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5094                restart_window: Some(dur),
5095                ..SupervisorSpec::default()
5096            };
5097            let json = serde_json::to_string(&s).unwrap();
5098            assert!(
5099                json.contains(&format!("\"{lit}\"")),
5100                "expected \"{lit}\" in {json}"
5101            );
5102            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5103            assert_eq!(back.restart_window, Some(dur));
5104        }
5105    }
5106
5107    #[test]
5108    fn duration_canonicalizes_to_largest_unit() {
5109        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5110        // typed Duration still equals 60s on the way back.
5111        let s = SupervisorSpec {
5112            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5113            restart_window: Some(Duration::from_secs(60)),
5114            ..SupervisorSpec::default()
5115        };
5116        let json = serde_json::to_string(&s).unwrap();
5117        assert!(json.contains("\"1m\""), "{json}");
5118        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5119        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5120    }
5121
5122    #[test]
5123    fn three_child_one_for_one_validates() {
5124        let s = SupervisorSpec {
5125            estrategia: RestartStrategy::OneForOne,
5126            max_restarts: 5,
5127            restart_window: Some(Duration::from_secs(60)),
5128            children: vec![
5129                child("worker", "^0.1", RestartPolicy::Permanent),
5130                child("cache", "^0.1", RestartPolicy::Transient),
5131                child("scratch", "^0.1", RestartPolicy::Temporary),
5132            ],
5133        };
5134        s.validate().unwrap();
5135    }
5136
5137    #[test]
5138    fn json_uses_pascal_case_for_strategy_and_policy() {
5139        // Variant names are PascalCase by default in serde, matching
5140        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5141        let c = child("w", "^0.1", RestartPolicy::Permanent);
5142        let json = serde_json::to_string(&c).unwrap();
5143        assert!(json.contains("\"Permanent\""));
5144        assert!(!json.contains("\"permanent\""));
5145
5146        let s = SupervisorSpec {
5147            estrategia: RestartStrategy::OneForOne,
5148            children: vec![c],
5149            ..SupervisorSpec::default()
5150        };
5151        let json = serde_json::to_string(&s).unwrap();
5152        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5153    }
5154
5155    // ── shared duration codec: integer-magnitude canonical-form gate ──
5156    //
5157    // The gate lifts the discipline `crate::limits::parse_duration`
5158    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5159    // the shared codec backing the remaining three typed-duration
5160    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5161    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5162    // emits is a non-negative integer with no decimal point and no
5163    // leading sign, so the codec's accepted set must match for
5164    // serialize/deserialize to round-trip without canonical-form
5165    // drift.
5166
5167    #[test]
5168    fn parse_accepts_integer_canonical_units() {
5169        // Pin the happy-path: every canonical author shape `render`
5170        // ever emits parses to the same `Duration` value, so the
5171        // codec's accepted set is at least a superset of its emitted
5172        // set on the canonical-unit axis.
5173        for (lit, dur) in [
5174            ("30s", Duration::from_secs(30)),
5175            ("500ms", Duration::from_millis(500)),
5176            ("2m", Duration::from_secs(120)),
5177            ("1h", Duration::from_secs(3600)),
5178            ("0s", Duration::ZERO),
5179        ] {
5180            assert_eq!(
5181                duration_codec::parse(lit).unwrap(),
5182                dur,
5183                "parse({lit:?}) should be {dur:?}"
5184            );
5185        }
5186    }
5187
5188    #[test]
5189    fn parse_accepts_bare_integer_as_seconds() {
5190        // The `"s" | ""` arm: a bare integer with no unit is read as
5191        // seconds. Pin this so the unit-empty form keeps parsing (it
5192        // renders to `"<n>s"` on serialize — that's a unit-choice
5193        // drift the integer-magnitude gate does NOT close, matching
5194        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5195        // the peer `:limits :memory` codec).
5196        assert_eq!(
5197            duration_codec::parse("30").unwrap(),
5198            Duration::from_secs(30)
5199        );
5200    }
5201
5202    #[test]
5203    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5204        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5205        // on first serialize — DRIFT. The integer-magnitude gate names
5206        // the offending `"1.5"` verbatim and points at the canonical
5207        // remediation `"1500ms"`.
5208        let err = duration_codec::parse("1.5s").unwrap_err();
5209        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5210        assert!(
5211            err.contains("not a non-negative integer"),
5212            "missing canonical-form reason in {err:?}"
5213        );
5214        assert!(
5215            err.contains("\"1500ms\""),
5216            "missing canonical-form remediation in {err:?}"
5217        );
5218    }
5219
5220    #[test]
5221    fn parse_rejects_decimal_shaped_integer_seconds() {
5222        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5223        // `1s` exactly, so the round-trip looks correct — but the
5224        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5225        // decimal-shape-with-integer-value form so author intent is
5226        // never silently rewritten.
5227        let err = duration_codec::parse("1.0s").unwrap_err();
5228        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5229        assert!(
5230            err.contains("not a non-negative integer"),
5231            "missing canonical-form reason in {err:?}"
5232        );
5233    }
5234
5235    #[test]
5236    fn parse_rejects_half_unit_minute() {
5237        // `"0.5m"` is the unit-fraction footgun — author writes a
5238        // human-readable half-minute, serde silently rewrites to
5239        // `"30s"` on next emit. The gate names the offending
5240        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5241        // form.
5242        let err = duration_codec::parse("0.5m").unwrap_err();
5243        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5244        assert!(
5245            err.contains("\"30s\""),
5246            "missing canonical-form remediation in {err:?}"
5247        );
5248    }
5249
5250    #[test]
5251    fn parse_rejects_leading_plus_sign() {
5252        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5253        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5254        // cleanly to 30s and round-tripped to `"30s"` on next emit
5255        // (DRIFT). The digit-only gate closes the leading-sign class
5256        // first; the diagnostic names `"+30"` verbatim.
5257        let err = duration_codec::parse("+30s").unwrap_err();
5258        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5259        assert!(
5260            err.contains("not a non-negative integer"),
5261            "missing canonical-form reason in {err:?}"
5262        );
5263    }
5264
5265    #[test]
5266    fn parse_rejects_leading_minus_sign() {
5267        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5268        // rejected with `"negative duration in \"-30s\""`. Under the
5269        // integer-magnitude gate the diagnostic is unified — `-30` is
5270        // non-digit-only, f64-numeric, and surfaces with the canonical-
5271        // form reason (no leading `+` / `-` sign) naming the offending
5272        // `"-30"` verbatim. Same diagnostic shape as every other
5273        // rejected non-integer magnitude.
5274        let err = duration_codec::parse("-30s").unwrap_err();
5275        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5276        assert!(
5277            err.contains("not a non-negative integer"),
5278            "missing canonical-form reason in {err:?}"
5279        );
5280    }
5281
5282    #[test]
5283    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5284        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5285        // through to the narrower "bad duration magnitude" arm — the
5286        // canonical-form diagnostic is reserved for the parser-shape
5287        // footgun case, not the "not a number at all" case. Same
5288        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5289        // the peer `:limits :memory` codec.
5290        let err = duration_codec::parse("--1s").unwrap_err();
5291        assert!(
5292            err.contains("bad duration magnitude"),
5293            "expected bad-magnitude wording in {err:?}"
5294        );
5295    }
5296
5297    #[test]
5298    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5299        // The accepted set is now closed under `u64`-exact integer
5300        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5301        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5302        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5303        // possible. Pin the integer-exact arms across the four unit
5304        // suffixes so a future refactor that reaches back for f64
5305        // (`from_secs_f64`, `mul_f64`) surfaces here.
5306        assert_eq!(
5307            duration_codec::parse("3600s").unwrap(),
5308            Duration::from_secs(3600)
5309        );
5310        assert_eq!(
5311            duration_codec::parse("60m").unwrap(),
5312            Duration::from_secs(3600)
5313        );
5314        assert_eq!(
5315            duration_codec::parse("1h").unwrap(),
5316            Duration::from_secs(3600)
5317        );
5318        assert_eq!(
5319            duration_codec::parse("999ms").unwrap(),
5320            Duration::from_millis(999)
5321        );
5322    }
5323
5324    #[test]
5325    fn restart_window_serde_rejects_fractional_seconds() {
5326        // The shared codec backs `SupervisorSpec::restart_window`
5327        // (`with = "duration_codec"`) — so the gate applies on serde
5328        // deserialize for the typed Supervisor slot. A
5329        // `{"restartWindow":"1.5s"}` payload that previously round-
5330        // tripped to a different canonical string on next serialize
5331        // is now refused at deserialize with the integer-magnitude
5332        // diagnostic.
5333        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5334            "restartWindow":"1.5s",
5335            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5336        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5337        let msg = err.to_string();
5338        assert!(
5339            msg.contains("not a non-negative integer"),
5340            "expected integer-magnitude diagnostic in {msg:?}"
5341        );
5342        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5343    }
5344
5345    #[test]
5346    fn restart_window_serde_rejects_leading_plus() {
5347        // The `u64::from_str` leading-`+` permissiveness gap that
5348        // motivated the digit-only gate (the `f64`-side accepted
5349        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5350        // is now closed on the shared codec — surfaces as a structured
5351        // diagnostic at the serde layer for every typed-duration slot.
5352        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5353            "restartWindow":"+30s",
5354            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5355        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5356        let msg = err.to_string();
5357        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5358        assert!(
5359            msg.contains("not a non-negative integer"),
5360            "missing canonical-form reason in {msg:?}"
5361        );
5362    }
5363
5364    #[test]
5365    fn parse_rejects_leading_zero_magnitude() {
5366        // `"030s"` is digit-only, so the existing non-digit-only / sign
5367        // / fractional arm doesn't catch it — `u64::from_str("030")`
5368        // returns `Ok(30)`, so before this gate `"030s"` parsed to
5369        // `Duration::from_secs(30)` and round-tripped through `render`
5370        // to `"30s"` — a *different* canonical string on the next emit,
5371        // breaking the THEORY.md Part V render-determinism contract
5372        // exactly the way `"+30s"` did before the leading-`+` arm
5373        // landed. Peer with the `rate_limit_codec` leading-zero arm
5374        // (4f46830) on the same canonical-form-drift axis.
5375        let err = duration_codec::parse("030s").unwrap_err();
5376        assert!(
5377            err.contains("non-canonical leading zero"),
5378            "expected leading-zero diagnostic in {err:?}"
5379        );
5380        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5381        assert!(
5382            err.contains("\"30s\""),
5383            "missing canonical-form remediation in {err:?}"
5384        );
5385        assert!(
5386            err.contains("THEORY.md"),
5387            "missing render-determinism citation in {err:?}"
5388        );
5389    }
5390
5391    #[test]
5392    fn parse_rejects_multi_digit_zero_magnitude() {
5393        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5394        // digit-only, parse losslessly to `Duration::ZERO`, but render
5395        // back to `"0s"` (the single-byte canonical form) on the next
5396        // emit. The leading-zero arm refuses the drift class at the
5397        // codec layer; the semantic-zero gate downstream
5398        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5399        // the single-byte canonical form `"0s"` separately on the
5400        // typed-validate layer.
5401        let err = duration_codec::parse("00s").unwrap_err();
5402        assert!(
5403            err.contains("non-canonical leading zero"),
5404            "expected leading-zero diagnostic in {err:?}"
5405        );
5406        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5407    }
5408
5409    #[test]
5410    fn parse_rejects_leading_zero_per_hour_window() {
5411        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5412        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5413        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5414        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5415        // `h` / bare-integer-as-seconds) inherits the same gate.
5416        let err = duration_codec::parse("01h").unwrap_err();
5417        assert!(
5418            err.contains("non-canonical leading zero"),
5419            "expected leading-zero diagnostic in {err:?}"
5420        );
5421        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5422    }
5423
5424    #[test]
5425    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5426        // The `parse_accepts_bare_integer_as_seconds` happy-path
5427        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5428        // multi-byte starts-with-`0`, parses losslessly to
5429        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5430        // bare-integer surface accepts permissive unit-empty
5431        // shorthand but still must reject leading-zero padding.
5432        let err = duration_codec::parse("030").unwrap_err();
5433        assert!(
5434            err.contains("non-canonical leading zero"),
5435            "expected leading-zero diagnostic in {err:?}"
5436        );
5437        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5438    }
5439
5440    #[test]
5441    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5442        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5443        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5444        // each round-trips losslessly through `render`
5445        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5446        // accepts them. The downstream semantic-zero gates
5447        // (`SupervisorError::ZeroRestartWindow`,
5448        // `AplicacaoError::PolicyTimeoutZero`,
5449        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5450        // zero-magnitude authoring at the typed-validate layer above,
5451        // peer with the `rate_limit_codec` codec-layer / typed-
5452        // validate-layer partition for `"0/s"`.
5453        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5454        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5455        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5456    }
5457
5458    #[test]
5459    fn parse_accepts_canonical_magnitude_with_leading_one() {
5460        // The complementary boundary: a future tightening cannot
5461        // drift into rejecting valid canonical magnitudes that
5462        // happen to start with `1` (or any digit `[1-9]`). Pin
5463        // every canonical-unit suffix so the leading-zero arm
5464        // remains strictly narrower than the digit-only arm.
5465        assert_eq!(
5466            duration_codec::parse("100ms").unwrap(),
5467            Duration::from_millis(100)
5468        );
5469        assert_eq!(
5470            duration_codec::parse("100s").unwrap(),
5471            Duration::from_secs(100)
5472        );
5473        assert_eq!(
5474            duration_codec::parse("10m").unwrap(),
5475            Duration::from_secs(600)
5476        );
5477        assert_eq!(
5478            duration_codec::parse("10h").unwrap(),
5479            Duration::from_secs(36_000)
5480        );
5481    }
5482
5483    #[test]
5484    fn restart_window_serde_rejects_leading_zero() {
5485        // The shared codec backs `SupervisorSpec::restart_window`
5486        // (`with = "duration_codec"`) — so the leading-zero arm
5487        // applies on serde deserialize for the typed Supervisor slot.
5488        // A `{"restartWindow":"030s"}` payload that previously round-
5489        // tripped to a different canonical string on next serialize
5490        // is now refused at deserialize with the leading-zero
5491        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5492        // / `restart_window_serde_rejects_fractional_seconds` on the
5493        // same canonical-form-drift axis.
5494        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5495            "restartWindow":"030s",
5496            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5497        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5498        let msg = err.to_string();
5499        assert!(
5500            msg.contains("non-canonical leading zero"),
5501            "expected leading-zero diagnostic in {msg:?}"
5502        );
5503        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5504    }
5505
5506    #[test]
5507    fn parse_rejects_leading_whitespace() {
5508        // `" 30s"` — the canonical paste-from-aligned-doc /
5509        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5510        // gate the top-level `s.trim()` at parse entry silently ate
5511        // the leading space and parsed the value to
5512        // `Duration::from_secs(30)`, which then round-tripped through
5513        // `render` to `"30s"` (a *different* canonical string on the
5514        // next emit) — the exact canonical-form-drift class the
5515        // leading-`+` / leading-zero arms already close, extended
5516        // to the whitespace-byte class. Peer with the sibling
5517        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5518        // the M3 `:politicas` axis.
5519        let err = duration_codec::parse(" 30s").unwrap_err();
5520        assert!(
5521            err.contains("contains whitespace byte"),
5522            "expected whitespace diagnostic in {err:?}"
5523        );
5524        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5525        assert!(
5526            err.contains("THEORY.md"),
5527            "missing render-determinism contract citation in {err:?}"
5528        );
5529    }
5530
5531    #[test]
5532    fn parse_rejects_trailing_whitespace() {
5533        // `"30s "` — the canonical shell-history / trailing-space
5534        // paste footgun. Before this gate the top-level `s.trim()`
5535        // silently ate the trailing space and parsed to
5536        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5537        // next emit — same canonical-form drift as the leading-space
5538        // sibling, closed on the same whitespace-byte arm.
5539        let err = duration_codec::parse("30s ").unwrap_err();
5540        assert!(
5541            err.contains("contains whitespace byte"),
5542            "expected whitespace diagnostic in {err:?}"
5543        );
5544        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5545    }
5546
5547    #[test]
5548    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5549        // `"30 s"` — the canonical typographically-spaced author
5550        // shape (the same idiom every prose reference to a duration
5551        // renders as, mistakenly retained when the value is pasted
5552        // into a codec-shaped slot). Before this gate the per-part
5553        // `num_part.trim()` / `unit.trim()` calls silently ate the
5554        // whitespace between the magnitude and the unit and parsed
5555        // the value to `Duration::from_secs(30)`, round-tripping to
5556        // `"30s"` — the codec's *internal* whitespace-tolerance
5557        // vector, orthogonal to the leading / trailing surface but
5558        // the same canonical-form-drift class. Pins the arm as
5559        // strictly stronger than the pre-existing top-level
5560        // `s.trim()` behavior: it fires on whitespace anywhere in
5561        // the value, not just at the string boundary.
5562        let err = duration_codec::parse("30 s").unwrap_err();
5563        assert!(
5564            err.contains("contains whitespace byte"),
5565            "expected whitespace diagnostic in {err:?}"
5566        );
5567        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5568    }
5569
5570    #[test]
5571    fn parse_rejects_tab_byte() {
5572        // `"\t30s"` — the canonical paste-from-indented-doc /
5573        // paste-from-YAML-block-scalar footgun where a tab byte leads
5574        // the magnitude. Pins that the gate covers tab (`0x09`) as
5575        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5576        // members and both would be silently swallowed by `s.trim()`
5577        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5578        // space alone to the full ASCII-whitespace set (space `0x20`,
5579        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5580        // the tab arm as a representative of the non-space members.
5581        let err = duration_codec::parse("\t30s").unwrap_err();
5582        assert!(
5583            err.contains("contains whitespace byte"),
5584            "expected whitespace diagnostic in {err:?}"
5585        );
5586        assert!(
5587            err.contains("0x09"),
5588            "missing offending tab byte in {err:?}"
5589        );
5590    }
5591
5592    #[test]
5593    fn restart_window_serde_rejects_whitespace() {
5594        // The shared codec backs `SupervisorSpec::restart_window`
5595        // (`with = "duration_codec"`) — so the whitespace arm
5596        // applies on serde deserialize for the typed Supervisor slot.
5597        // A `{"restartWindow":" 30s"}` payload that previously round-
5598        // tripped to a different canonical string on next serialize
5599        // is now refused at deserialize with the whitespace-byte
5600        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5601        // / `restart_window_serde_rejects_leading_plus` /
5602        // `restart_window_serde_rejects_fractional_seconds` on the
5603        // same canonical-form-drift axis.
5604        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5605            "restartWindow":" 30s",
5606            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5607        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5608        let msg = err.to_string();
5609        assert!(
5610            msg.contains("contains whitespace byte"),
5611            "expected whitespace diagnostic in {msg:?}"
5612        );
5613        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5614    }
5615
5616    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5617    //
5618    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5619    // duration codec — closes the strictly-complementary class the
5620    // byte-scan cannot see, through the lifted
5621    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5622    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5623    // and `:politicas :circuit-breaker :window` simultaneously via
5624    // this shared codec.
5625
5626    #[test]
5627    fn duration_codec_parse_rejects_leading_nbsp() {
5628        // NBSP prefix — the strictly-complementary drift class the
5629        // ASCII byte-scan cannot see. `str::trim` strips it silently
5630        // and the value drifts to `"30s"` on next serialize.
5631        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5632        assert!(
5633            err.contains("non-ASCII Unicode whitespace character"),
5634            "expected non-ASCII whitespace diagnostic in {err:?}"
5635        );
5636        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5637    }
5638
5639    #[test]
5640    fn duration_codec_parse_rejects_trailing_line_separator() {
5641        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5642        // footgun.
5643        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5644        assert!(
5645            err.contains("non-ASCII Unicode whitespace character"),
5646            "expected non-ASCII whitespace diagnostic in {err:?}"
5647        );
5648        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5649    }
5650
5651    #[test]
5652    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5653        // Positive-control pin: every ASCII-only canonical form the
5654        // renderer emits stays accepted through the new arm.
5655        assert_eq!(
5656            duration_codec::parse("30s").unwrap(),
5657            Duration::from_secs(30)
5658        );
5659        assert_eq!(
5660            duration_codec::parse("500ms").unwrap(),
5661            Duration::from_millis(500)
5662        );
5663        assert_eq!(
5664            duration_codec::parse("1h").unwrap(),
5665            Duration::from_secs(3600)
5666        );
5667    }
5668
5669    #[test]
5670    fn restart_window_serde_rejects_non_ascii_whitespace() {
5671        // The shared codec backs `SupervisorSpec::restart_window` — so
5672        // the new non-ASCII Unicode whitespace arm applies on serde
5673        // deserialize for the typed Supervisor slot. A
5674        // `{"restartWindow":" 30s"}` payload that previously
5675        // survived the ASCII byte-scan (only ASCII whitespace was
5676        // refused) is now refused at deserialize with the
5677        // non-ASCII-whitespace-and-codepoint diagnostic.
5678        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5679            \"restartWindow\":\"\u{00A0}30s\",\
5680            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5681        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5682        let msg = err.to_string();
5683        assert!(
5684            msg.contains("non-ASCII Unicode whitespace character"),
5685            "expected non-ASCII whitespace diagnostic in {msg:?}"
5686        );
5687        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5688    }
5689
5690    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5691
5692    #[test]
5693    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5694        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5695        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5696        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5697        // name the exact camelCase JSON keys the
5698        // `#[serde(rename_all = "camelCase")]` attribute on
5699        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5700        // field carries `Some(_)` / non-empty) and pin that each canonical
5701        // byte-sequence appears verbatim in the JSON — a future accidental
5702        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5703        // name flip at the derive attribute (any of which would silently
5704        // break every downstream JSON consumer that reaches for one of the
5705        // four consts via `Value::get(...)`) surfaces here as a build-time
5706        // test failure at `supervisor.rs`, not as an apply-time
5707        // `.get(<stale-canonical-const>)` returning `None` far from the
5708        // derive-attr drift's commit. Peer with the sibling
5709        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5710        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5711        // M2 typed-slot family established, extended here to close the
5712        // top-level Supervisor axis.
5713        let spec = SupervisorSpec {
5714            estrategia: RestartStrategy::OneForOne,
5715            max_restarts: 5,
5716            restart_window: Some(Duration::from_secs(60)),
5717            children: vec![ChildSpec {
5718                caixa: "w".into(),
5719                versao: "^0.1".into(),
5720                restart: RestartPolicy::Permanent,
5721            }],
5722        };
5723        let json = serde_json::to_string(&spec).unwrap();
5724        for key in [
5725            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5726            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5727            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5728            crate::render::SUPERVISOR_KEY_CHILDREN,
5729        ] {
5730            let quoted = format!("\"{key}\"");
5731            assert!(
5732                json.contains(&quoted),
5733                "serialized SupervisorSpec must carry the lifted \
5734                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5735                 the JSON emission (got: {json})",
5736            );
5737        }
5738    }
5739
5740    #[test]
5741    fn supervisor_key_consts_are_pairwise_distinct() {
5742        // Cross-axis drift-detection pin: a future collapse of two
5743        // canonical top-level byte-strings onto the same value (e.g. an
5744        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5745        // also read `"estrategia"`) would silently reroute every
5746        // downstream probe on one axis onto the sibling axis's overlay
5747        // entry and pass every propagation-probe test that expected only
5748        // the stale axis's value. Peer of the sibling four-way distinct
5749        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5750        let all = [
5751            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5752            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5753            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5754            crate::render::SUPERVISOR_KEY_CHILDREN,
5755        ];
5756        for (i, a) in all.iter().enumerate() {
5757            for b in all.iter().skip(i + 1) {
5758                assert_ne!(
5759                    a, b,
5760                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5761                     canonical byte-sequences — got `{a}` == `{b}`",
5762                );
5763            }
5764        }
5765    }
5766
5767    #[test]
5768    fn supervisor_key_consts_are_lower_camel_case_shape() {
5769        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5770        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5771        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5772        // capital, no whitespace / dots) — the canonical shape the
5773        // `#[serde(rename_all = "camelCase")]` derive produces on
5774        // `SupervisorSpec`. A future flip to a non-camelCase attribute
5775        // at the derive surfaces both here (this test fails on the
5776        // stale-constant shape) and at
5777        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5778        // (that test fails on the mismatch between const and derive).
5779        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5780        // (d8b8b4f) on the sibling M2 `:limits` axis.
5781        for key in [
5782            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5783            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5784            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5785            crate::render::SUPERVISOR_KEY_CHILDREN,
5786        ] {
5787            assert!(
5788                !key.is_empty(),
5789                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5790            );
5791            let first = key.chars().next().unwrap();
5792            assert!(
5793                first.is_ascii_lowercase(),
5794                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5795                 (got {key:?}, leads with {first:?})",
5796            );
5797            assert!(
5798                key.chars().all(|c| c.is_ascii_alphanumeric()),
5799                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5800                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5801            );
5802        }
5803    }
5804
5805    #[test]
5806    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5807        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5808        // (camelCase JSON keys, no leading colon) must never collide
5809        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5810        // consts (kebab-case author-facing labels with leading colon)
5811        // that sit next to them at `caixa_core::render`. Both families
5812        // cover the same four typed Supervisor slots on two distinct
5813        // axes (author-side kebab vs renderer-side camelCase);
5814        // collapsing either family onto the other's byte-shape would
5815        // silently reroute the render-side probe onto the author-facing
5816        // surface, or vice versa. Peer of the byte-distinctness
5817        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5818        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5819        let pairs = [
5820            (
5821                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5822                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
5823            ),
5824            (
5825                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5826                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
5827            ),
5828            (
5829                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5830                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
5831            ),
5832            (
5833                crate::render::SUPERVISOR_KEY_CHILDREN,
5834                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
5835            ),
5836        ];
5837        for (json_key, author_key) in pairs {
5838            assert_ne!(
5839                json_key, author_key,
5840                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
5841                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
5842                 got JSON `{json_key}` == author `{author_key}`",
5843            );
5844        }
5845    }
5846
5847    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
5848
5849    #[test]
5850    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
5851        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
5852        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
5853        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
5854        // keys the `#[serde(rename_all = "camelCase")]` attribute on
5855        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
5856        // pin that each canonical byte-sequence appears verbatim in the
5857        // JSON — a future accidental `rename_all = "snake_case"` /
5858        // `"kebab-case"` / verbatim-field-name flip at the derive
5859        // attribute (any of which would silently break every downstream
5860        // JSON consumer that reaches for one of the three consts via
5861        // `Value::get(...)`) surfaces here as a build-time test failure at
5862        // `supervisor.rs`, not as an apply-time
5863        // `.get(<stale-canonical-const>)` returning `None` far from the
5864        // derive-attr drift's commit. Peer with the enclosing
5865        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5866        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
5867        // discipline the SupervisorSpec top-level lift established,
5868        // extended here to the sibling per-`:children` entry `ChildSpec`
5869        // derive so the last M2 typed-struct sub-block
5870        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
5871        // surface without a lifted serde-key peer joins the substrate's
5872        // "one canonical byte-string per typed serialized-key axis"
5873        // discipline.
5874        let c = ChildSpec {
5875            caixa: "worker".into(),
5876            versao: "^0.1".into(),
5877            restart: RestartPolicy::Permanent,
5878        };
5879        let json = serde_json::to_string(&c).unwrap();
5880        for key in [
5881            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5882            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5883            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5884        ] {
5885            let quoted = format!("\"{key}\"");
5886            assert!(
5887                json.contains(&quoted),
5888                "serialized ChildSpec must carry the lifted \
5889                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
5890                 in the JSON emission (got: {json})",
5891            );
5892        }
5893    }
5894
5895    #[test]
5896    fn supervisor_child_key_consts_are_pairwise_distinct() {
5897        // Cross-axis drift-detection pin: a future collapse of two
5898        // canonical `ChildSpec` per-entry byte-strings onto the same
5899        // value (e.g. an accidental copy-paste flip of
5900        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
5901        // silently reroute every downstream probe on one axis onto the
5902        // sibling axis's overlay entry and pass every propagation-probe
5903        // test that expected only the stale axis's value. Peer of the
5904        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
5905        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
5906        // pair (ce80ca0).
5907        let all = [
5908            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5909            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5910            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5911        ];
5912        for (i, a) in all.iter().enumerate() {
5913            for b in all.iter().skip(i + 1) {
5914                assert_ne!(
5915                    a, b,
5916                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
5917                     distinct canonical byte-sequences — got `{a}` == `{b}`",
5918                );
5919            }
5920        }
5921    }
5922
5923    #[test]
5924    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
5925        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
5926        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5927        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5928        // capital, no whitespace / dots) — the canonical shape the
5929        // `#[serde(rename_all = "camelCase")]` derive produces on
5930        // `ChildSpec`. A future flip to a non-camelCase attribute at the
5931        // derive surfaces both here (this test fails on the
5932        // stale-constant shape) and at
5933        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
5934        // (that test fails on the mismatch between const and derive).
5935        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
5936        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
5937        for key in [
5938            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5939            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5940            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5941        ] {
5942            assert!(
5943                !key.is_empty(),
5944                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
5945            );
5946            let first = key.chars().next().unwrap();
5947            assert!(
5948                first.is_ascii_lowercase(),
5949                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
5950                 byte (got {key:?}, leads with {first:?})",
5951            );
5952            assert!(
5953                key.chars().all(|c| c.is_ascii_alphanumeric()),
5954                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
5955                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5956            );
5957        }
5958    }
5959
5960    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
5961
5962    #[test]
5963    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
5964        // The fail-before-pass-after pin: pre-lift there was no
5965        // single-source binding between the [`RestartStrategy`] variant
5966        // name the un-`rename`d `Serialize` derive emits under
5967        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
5968        // every downstream cluster-side dispatcher (the future
5969        // wasm-operator's per-supervisor sibling-restart branch, the
5970        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5971        // admission-time enum-arm bind, the `caixa-operator`'s
5972        // hierarchical reconciliation scheduler's per-strategy fan-out)
5973        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
5974        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
5975        // override, or a variant rename in the source — would silently
5976        // rebrand the emitted scalar under one spelling while every
5977        // downstream dispatcher still probed the other, with the failure
5978        // surfacing at the operator's reconcile posture (subtrees coming
5979        // up under the `default()` `OneForOne` arm rather than the typed
5980        // slot's declared strategy — a bad child would then only take
5981        // itself down instead of the sibling set the author intended, so
5982        // shared-state children fall out of sync) far from the source
5983        // rebrand commit and with no field naming the drift. Pinning the
5984        // two paths (the `Serialize` derive's serialized string AND the
5985        // [`RestartStrategy::as_str`] helper) to the same four lifted
5986        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
5987        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
5988        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
5989        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
5990        // byte-strings makes any future drift on either endpoint fail
5991        // here at caixa-core build time. Peer of the M3
5992        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
5993        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
5994        // three-path-convergence discipline, extended to close the
5995        // OTP-shaped per-supervisor sibling-restart axis.
5996        for (variant, expected) in [
5997            (
5998                RestartStrategy::OneForOne,
5999                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6000            ),
6001            (
6002                RestartStrategy::OneForAll,
6003                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6004            ),
6005            (
6006                RestartStrategy::RestForOne,
6007                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6008            ),
6009            (
6010                RestartStrategy::SimpleOneForOne,
6011                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6012            ),
6013        ] {
6014            let json = serde_json::to_string(&variant).unwrap();
6015            assert_eq!(
6016                json,
6017                format!("\"{expected}\""),
6018                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6019            );
6020            assert_eq!(
6021                variant.as_str(),
6022                expected,
6023                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6024                 SUPERVISOR_ESTRATEGIA_* constant"
6025            );
6026        }
6027    }
6028
6029    #[test]
6030    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6031        // Cross-arm drift-detection pin: a future collapse of two
6032        // canonical variant byte-strings onto the same value (e.g. an
6033        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6034        // to also read `"OneForOne"`) would silently reroute every
6035        // downstream operator's per-strategy dispatch onto the sibling
6036        // arm's reconcile branch and pass every propagation-probe test
6037        // that expected only the stale arm's value — the mis-strategied
6038        // subtree would come up with the wrong sibling-restart posture
6039        // on every subsequent failure. Peer of the sibling four-way
6040        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6041        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6042        let all = [
6043            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6044            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6045            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6046            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6047        ];
6048        for (i, a) in all.iter().enumerate() {
6049            for (j, b) in all.iter().enumerate() {
6050                if i != j {
6051                    assert_ne!(
6052                        a, b,
6053                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6054                         — got duplicate {a:?} at indices {i} and {j}",
6055                    );
6056                }
6057            }
6058        }
6059    }
6060
6061    #[test]
6062    fn restart_strategy_display_routes_through_as_str_helper() {
6063        // The fail-before-pass-after pin on the first half of the
6064        // three-path convergence: pre-convergence the sibling
6065        // OTP-shape typed enum [`RestartStrategy`] carried a
6066        // [`std::fmt::Display`] surface via its
6067        // `#[discriminant(also_display)]` gen-platform derive route,
6068        // which arrived kebab-case as `"one-for-one"` /
6069        // `"one-for-all"` / `"rest-for-one"` /
6070        // `"simple-one-for-one"` while the wire format ran as
6071        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6072        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6073        // Every consumer reaching for a strategy byte-string past the
6074        // wire format had to pick between three paths
6075        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6076        // serialized string, or `format!("{v}")` on the
6077        // discriminant-Display route), any two of which a future
6078        // variant rename or `#[serde(rename_all = "kebab-case")]`
6079        // attribute would silently desynchronize. Wiring
6080        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6081        // closes the third path: every `format!("{v}")` call reaches
6082        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6083        // const the wire format and the [`RestartStrategy::as_str`]
6084        // helper already route through, so a future variant rename
6085        // lands at exactly one place. Pin the routing here so a future
6086        // `impl std::fmt::Display for RestartStrategy`
6087        // reimplementation that hand-rolls the arms instead of
6088        // delegating to [`RestartStrategy::as_str`] fails at
6089        // caixa-core build time. Peer of the M3
6090        // `placement_strategy_display_routes_through_as_str_helper`
6091        // (cc8f749) which the M3 axis converged first.
6092        for &variant in RestartStrategy::ALL {
6093            assert_eq!(
6094                variant.to_string(),
6095                variant.as_str(),
6096                "RestartStrategy::{variant:?} Display must route through \
6097                 RestartStrategy::as_str (single source of truth: the lifted \
6098                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6099            );
6100        }
6101    }
6102
6103    #[test]
6104    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6105        // The fail-before-pass-after pin on the second half of the
6106        // three-path convergence: `Display` (user-facing text) agrees
6107        // byte-for-byte with the `Serialize` derive's wire format
6108        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6109        // scalar) on every variant. Pre-convergence the two paths
6110        // were structurally independent — a future
6111        // `#[serde(rename_all = "kebab-case")]` attribute on the
6112        // enum would silently rebrand the emitted wire scalar
6113        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6114        // `simple-one-for-one`) while every consumer that
6115        // pretty-prints the strategy (the future wasm-operator's
6116        // per-supervisor sibling-restart-strategy diagnostic line,
6117        // the future `feira app graph` per-supervisor strategy line,
6118        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6119        // materializer's admission-webhook rejection body) would
6120        // still emit the PascalCase form the `as_str` / `Display`
6121        // route returns, with the mismatch surfacing at consumer
6122        // parse time / operator dispatch time far from the source
6123        // rebrand commit. Pin the two paths byte-for-byte here so any
6124        // future serde-attribute or variant-rename drift is a
6125        // caixa-core-build-time test failure at this call, not a
6126        // silent per-consumer dispatch miss. Peer of the M3
6127        // `placement_strategy_display_matches_serialized_wire_byte_string`
6128        // (cc8f749) which the M3 axis converged first.
6129        for &variant in RestartStrategy::ALL {
6130            let wire = serde_json::to_string(&variant).unwrap();
6131            let unquoted = wire
6132                .strip_prefix('"')
6133                .and_then(|s| s.strip_suffix('"'))
6134                .expect("serialized RestartStrategy is a JSON string");
6135            assert_eq!(
6136                variant.to_string(),
6137                unquoted,
6138                "RestartStrategy::{variant:?} Display byte-string must match the \
6139                 Serialize derive's wire byte-string (three-path convergence: \
6140                 Display + as_str + Serialize all resolve to the same \
6141                 SUPERVISOR_ESTRATEGIA_* const)"
6142            );
6143        }
6144    }
6145
6146    #[test]
6147    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6148        // Fail-before-pass-after byte-parity pin on the lifted
6149        // `impl AsRef<str> for RestartStrategy` — asserts the
6150        // standard-library trait impl and the substrate-primitive
6151        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6152        // to the same `&str` per instance across the four-arm
6153        // closed set, so any future silent detour that routes the
6154        // impl through a divergent projection (a per-arm inline
6155        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6156        // re-inlining that opens a compile-time link to the un-lifted
6157        // arm-literal, a swap onto the kebab-case
6158        // [`gen_platform::Discriminant`] catalog identity that would
6159        // collide the wire axis with the dispatcher-catalog axis) trips
6160        // at caixa-core test time under `PartialEq` rather than at a
6161        // downstream `impl AsRef<str>`-bound consumer's silent split.
6162        // Sweeps every one of the four arms
6163        // [`RestartStrategy::ALL`] carries so no arm's projection is
6164        // covered only by the sibling wire-format `Serialize` derive
6165        // path. Peer of the sibling
6166        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6167        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6168        // top-level `:versao` typed newtype — the two pins together
6169        // cover the substrate primitive's `AsRef<str>` projection axis
6170        // on the paired newtype + closed-set-typed-enum surface.
6171        for &variant in RestartStrategy::ALL {
6172            assert_eq!(
6173                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6174                variant.as_str(),
6175                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6176                 byte-equal RestartStrategy::as_str on the same instance \
6177                 — divergence signals a silent detour off the substrate-\
6178                 primitive accessor"
6179            );
6180        }
6181    }
6182
6183    #[test]
6184    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6185        // Fail-before-pass-after byte-parity pin on the three-path
6186        // convergence discipline the M2 sibling-restart primitive now
6187        // carries on the `&str`-projection axis:
6188        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6189        // lifted impl), `format!("{s}")` (the pre-existing
6190        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6191        // primitive `pub const fn` accessor both trait impls delegate
6192        // through) must resolve to the same byte-string on every
6193        // instance across the four-arm closed set. Refuses any future
6194        // divergence between the two trait impls (a stray
6195        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6196        // rather than delegating through the shared accessor; a
6197        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6198        // literal cascade) that would silently split the two
6199        // projection paths of the same closed-set typed enum. Mirrors
6200        // the sibling three-path-convergence discipline the peer
6201        // [`crate::CaixaVersion`] typed newtype carries on its
6202        // `AsRef<str>` / `Display` / `as_str` triple
6203        // (version.rs pin
6204        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6205        // 16d5c7e).
6206        for &variant in RestartStrategy::ALL {
6207            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6208            let via_display: String = format!("{variant}");
6209            let via_accessor: &str = variant.as_str();
6210            assert_eq!(via_as_ref, via_accessor);
6211            assert_eq!(via_display, via_accessor);
6212            assert_eq!(via_as_ref, via_display.as_str());
6213        }
6214    }
6215
6216    #[test]
6217    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6218        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6219        // exhaustive-iteration surface: every variant appears exactly
6220        // once, and the slice length matches the arm count of the
6221        // closed set. Every consumer that walks the accepted-strategy
6222        // set (a future `feira supervisor --estrategia …` CLI-side
6223        // arg-parse's "did you mean" hint, a future M4 admission-
6224        // webhook's rejection body naming the accepted-`:estrategia`
6225        // list, the [`RestartStrategy::from_wire`] reverse-projection
6226        // consumers that iterate the accept-set for diagnostic
6227        // rendering) reads through this slice, so a future arm addition
6228        // that grows the enum but forgets to grow [`Self::ALL`]
6229        // silently truncates every downstream consumer's accept-set at
6230        // the same pre-addition boundary — this pin fails at caixa-core
6231        // build time on the pairwise-distinct + arm-count invariants.
6232        //
6233        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6234        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6235        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6236        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6237        // pins on the peer closed-set typed-enum axes.
6238        let all: &[RestartStrategy] = RestartStrategy::ALL;
6239        assert_eq!(
6240            all.len(),
6241            4,
6242            "RestartStrategy::ALL must enumerate every variant of the \
6243             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6244             SimpleOneForOne); got {all:?}"
6245        );
6246        for (i, a) in all.iter().enumerate() {
6247            for (j, b) in all.iter().enumerate() {
6248                if i != j {
6249                    assert_ne!(
6250                        a, b,
6251                        "RestartStrategy::ALL must carry every variant exactly \
6252                         once — got duplicate {a:?} at indices {i} and {j}"
6253                    );
6254                }
6255            }
6256        }
6257        for variant in [
6258            RestartStrategy::OneForOne,
6259            RestartStrategy::OneForAll,
6260            RestartStrategy::RestForOne,
6261            RestartStrategy::SimpleOneForOne,
6262        ] {
6263            assert!(
6264                all.contains(&variant),
6265                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6266                 addition that grows the enum but forgets to grow the ALL slice \
6267                 silently truncates every downstream consumer's accept-set at \
6268                 the pre-addition boundary"
6269            );
6270        }
6271    }
6272
6273    #[test]
6274    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6275        // Fail-before-pass-after pin on the forward accept-set of the
6276        // [`RestartStrategy::from_wire`] reverse projection: every
6277        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6278        // constant the [`RestartStrategy::as_str`] emitter walks parses
6279        // back to its paired variant. Any future arm addition that
6280        // grows the emitter's `as_str` match but forgets to grow the
6281        // parser's `from_wire` match silently splits the two halves of
6282        // the round-trip — the wire byte-string one non-serde consumer
6283        // parses from the one the emitter wrote — with the failure
6284        // surfacing at parse time far from the rebrand commit. Pinning
6285        // the four-arm accept-set here catches the drift at caixa-core
6286        // build time.
6287        //
6288        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6289        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6290        // accept-set pins on the peer closed-set typed-enum `str → Self`
6291        // axes.
6292        for (wire, expected) in [
6293            (
6294                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6295                RestartStrategy::OneForOne,
6296            ),
6297            (
6298                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6299                RestartStrategy::OneForAll,
6300            ),
6301            (
6302                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6303                RestartStrategy::RestForOne,
6304            ),
6305            (
6306                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6307                RestartStrategy::SimpleOneForOne,
6308            ),
6309        ] {
6310            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6311                panic!(
6312                    "RestartStrategy::from_wire({wire:?}) must accept every \
6313                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6314                     lifted canonical byte-string that RestartStrategy::{expected:?} \
6315                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6316                )
6317            });
6318            assert_eq!(
6319                parsed, expected,
6320                "RestartStrategy::from_wire({wire:?}) must return \
6321                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6322            );
6323        }
6324    }
6325
6326    #[test]
6327    fn restart_strategy_from_wire_round_trips_through_as_str() {
6328        // Fail-before-pass-after pin on the closed round-trip between
6329        // the forward [`RestartStrategy::as_str`] emitter and the
6330        // reverse [`RestartStrategy::from_wire`] parser: for every
6331        // variant in [`RestartStrategy::ALL`], parsing the emitter's
6332        // output must return exactly the same variant. Any per-arm
6333        // divergence — a future arm added to `as_str` but not
6334        // `from_wire`, an accidental copy-paste flip in one but not
6335        // the other — silently splits the emit and parse halves and
6336        // the failure surfaces at consumer parse time far from the
6337        // drift site. The `ALL`-iterating shape means a future arm
6338        // addition picks up the coverage by construction.
6339        //
6340        // Peer of the sibling
6341        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6342        // (18c7342) round-trip pin on
6343        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6344        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6345        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6346        for &variant in RestartStrategy::ALL {
6347            let wire = variant.as_str();
6348            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6349                panic!(
6350                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6351                     must be Some({variant:?}) — the two halves of the round-trip \
6352                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6353                     got None on wire byte-string {wire:?}"
6354                )
6355            });
6356            assert_eq!(
6357                parsed, variant,
6358                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6359                 must round-trip to the same variant; got {parsed:?}"
6360            );
6361        }
6362    }
6363
6364    #[test]
6365    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6366        // Fail-before-pass-after pin on the closed-set refusal
6367        // discipline of [`RestartStrategy::from_wire`]: every
6368        // byte-string outside the four-arm accept-set returns `None`
6369        // rather than silently collapsing onto the [`Default`]
6370        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6371        // exercised here sweeps the load-bearing drift shapes: the
6372        // empty string (a stripped serde-attribute drift), all-
6373        // whitespace strings (the canonical text-editor accidental
6374        // padding shape), the kebab-case dispatcher-catalog identities
6375        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6376        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6377        // derived [`std::str::FromStr`] accept-set, which parses the
6378        // *other* axis of this enum's two-axis split and must not leak
6379        // into the `from_wire` PascalCase-wire accept-set), the
6380        // lowercased single-word forms (`"oneforone"`), the padded
6381        // canonical scalar (`" OneForOne "`), the trailing-newline
6382        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6383        // (`"AllForOne"` — the canonical typo direction).
6384        //
6385        // Peer of the sibling
6386        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6387        // (2aa6d23) +
6388        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6389        // (18c7342) refusal pins on the peer closed-set typed-enum
6390        // axes.
6391        for bad in [
6392            "",
6393            " ",
6394            "\n",
6395            "\t",
6396            "one-for-one",
6397            "one-for-all",
6398            "rest-for-one",
6399            "simple-one-for-one",
6400            "oneforone",
6401            "OneForOnes",
6402            "one_for_one",
6403            "one for one",
6404            "ONEFORONE",
6405            "OneForOne ",
6406            " OneForOne",
6407            " SimpleOneForOne ",
6408            "OneForOne\n",
6409            "restforone",
6410            "REST_FOR_ONE",
6411            "AllForOne",
6412            "Simple",
6413            "?",
6414        ] {
6415            assert!(
6416                RestartStrategy::from_wire(bad).is_none(),
6417                "RestartStrategy::from_wire({bad:?}) must return None — the \
6418                 parser's accept-set is exactly the four RestartStrategy::as_str \
6419                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6420                 and this byte-string is outside that closed set"
6421            );
6422        }
6423    }
6424
6425    #[test]
6426    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6427        // Fail-before-pass-after pin on the fourth path of the four-path
6428        // convergence: `from_wire` (the reverse projection) inverts the
6429        // `Serialize` derive's wire byte-string on every variant.
6430        // Together with the pre-existing three-path convergence
6431        // (`Display` + `as_str` + `Serialize` all resolve to the same
6432        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6433        // pinned by
6434        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6435        // this closes the round-trip: the wire byte-string the
6436        // `Serialize` derive emits parses back to the same variant
6437        // through `from_wire`, so any future serde-attribute or variant-
6438        // rename drift on the emit half now surfaces as a matched drift
6439        // on the parse half at caixa-core build time — the two halves
6440        // migrate as a unit through the lifted consts on any future
6441        // rename, and the round-trip cannot silently split.
6442        //
6443        // Peer of the sibling
6444        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6445        // (18c7342) wire-format pin on
6446        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6447        for &variant in RestartStrategy::ALL {
6448            let wire = serde_json::to_string(&variant).unwrap();
6449            let unquoted = wire
6450                .strip_prefix('"')
6451                .and_then(|s| s.strip_suffix('"'))
6452                .expect("serialized RestartStrategy is a JSON string");
6453            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6454                panic!(
6455                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6456                     Serialize derive's wire byte-string for \
6457                     RestartStrategy::{variant:?} — the four-path convergence \
6458                     (Display + as_str + Serialize + from_wire) resolves through \
6459                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6460                )
6461            });
6462            assert_eq!(
6463                parsed, variant,
6464                "RestartStrategy::from_wire of the Serialize derive's wire \
6465                 byte-string for RestartStrategy::{variant:?} must round-trip \
6466                 to the same variant; got {parsed:?}"
6467            );
6468        }
6469    }
6470
6471    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
6472
6473    #[test]
6474    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
6475        // The fail-before-pass-after pin: pre-lift there was no
6476        // single-source binding between the [`RestartPolicy`] variant
6477        // name the un-`rename`d `Serialize` derive emits under
6478        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
6479        // byte-string every downstream cluster-side dispatcher (the
6480        // future wasm-operator's per-child post-exit restart-decision
6481        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6482        // materializer's admission-time enum-arm bind, the
6483        // `caixa-operator`'s hierarchical reconciliation scheduler's
6484        // per-child-policy fan-out) probes verbatim. A future
6485        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
6486        // or a per-variant `#[serde(rename = "…")]` override, or a
6487        // variant rename in the source — would silently rebrand the
6488        // emitted scalar under one spelling while every downstream
6489        // dispatcher still probed the other, with the failure surfacing
6490        // at the operator's reconcile posture (children coming up under
6491        // the `default()` `Permanent` arm rather than the typed slot's
6492        // declared policy — a `:temporary` `oneShot` child would be
6493        // restarted on clean exit, treating the successful-completion
6494        // signal as failure and re-running the completion-terminal
6495        // one-shot indefinitely; a `:transient` child that clean-exited
6496        // would be restarted, masking the clean-completion contract)
6497        // far from the source rebrand commit and with no field naming
6498        // the drift. Pinning the two paths (the `Serialize` derive's
6499        // serialized string AND the [`RestartPolicy::as_str`] helper)
6500        // to the same three lifted
6501        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
6502        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
6503        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
6504        // byte-strings makes any future drift on either endpoint fail
6505        // here at caixa-core build time. Peer of the sibling
6506        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
6507        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6508        // and the M3
6509        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6510        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
6511        // same three-path-convergence discipline, extended to close the
6512        // third OTP-shaped closed-enum discriminator axis on the caixa
6513        // typed surface (per-child restart-decision policy).
6514        for (variant, expected) in [
6515            (
6516                RestartPolicy::Permanent,
6517                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6518            ),
6519            (
6520                RestartPolicy::Temporary,
6521                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6522            ),
6523            (
6524                RestartPolicy::Transient,
6525                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6526            ),
6527        ] {
6528            let json = serde_json::to_string(&variant).unwrap();
6529            assert_eq!(
6530                json,
6531                format!("\"{expected}\""),
6532                "RestartPolicy::{variant:?} must serialize to {expected:?}"
6533            );
6534            assert_eq!(
6535                variant.as_str(),
6536                expected,
6537                "RestartPolicy::{variant:?}.as_str() must return the lifted \
6538                 SUPERVISOR_CHILD_RESTART_* constant"
6539            );
6540        }
6541    }
6542
6543    #[test]
6544    fn supervisor_child_restart_consts_are_pairwise_distinct() {
6545        // Cross-arm drift-detection pin: a future collapse of two
6546        // canonical variant byte-strings onto the same value (e.g. an
6547        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
6548        // to also read `"Permanent"`) would silently reroute every
6549        // downstream operator's per-child-policy dispatch onto the
6550        // sibling arm's reconcile branch and pass every propagation-probe
6551        // test that expected only the stale arm's value — a `:transient`
6552        // child would come up under the `:permanent` restart-decision
6553        // posture on every subsequent clean exit, so a completion-terminal
6554        // child would be restarted indefinitely against its declared
6555        // policy. Peer of the sibling
6556        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
6557        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6558        // and the four-way distinct pin
6559        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
6560        // top-level `SUPERVISOR_KEY_*` axis.
6561        let all = [
6562            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6563            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6564            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6565        ];
6566        for (i, a) in all.iter().enumerate() {
6567            for (j, b) in all.iter().enumerate() {
6568                if i != j {
6569                    assert_ne!(
6570                        a, b,
6571                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
6572                         — got duplicate {a:?} at indices {i} and {j}",
6573                    );
6574                }
6575            }
6576        }
6577    }
6578
6579    #[test]
6580    fn restart_policy_display_routes_through_as_str_helper() {
6581        // The fail-before-pass-after pin on the first half of the
6582        // three-path convergence: pre-convergence [`RestartPolicy`]
6583        // carried a [`std::fmt::Display`] surface via its
6584        // `#[discriminant(also_display)]` gen-platform derive route,
6585        // which arrived kebab-case as `"permanent"` / `"temporary"`
6586        // / `"transient"` on this three-arm enum (whose variant
6587        // names each collapse to their own lowercase form under the
6588        // kebab-case transform) while the wire format ran as
6589        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
6590        // through the un-`rename`d serde derive. Every consumer
6591        // reaching for a policy byte-string past the wire format had
6592        // to pick between three paths ([`RestartPolicy::as_str`],
6593        // the `Serialize` derive's serialized string, or
6594        // `format!("{v}")` on the discriminant-Display route), any
6595        // two of which a future variant rename or
6596        // `#[serde(rename_all = "kebab-case")]` attribute would
6597        // silently desynchronize. Wiring [`std::fmt::Display`]
6598        // through [`RestartPolicy::as_str`] closes the third path:
6599        // every `format!("{v}")` call reaches the same lifted
6600        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
6601        // wire format and the [`RestartPolicy::as_str`] helper
6602        // already route through, so a future variant rename lands at
6603        // exactly one place. Pin the routing here so a future
6604        // `impl std::fmt::Display for RestartPolicy`
6605        // reimplementation that hand-rolls the arms instead of
6606        // delegating to [`RestartPolicy::as_str`] fails at
6607        // caixa-core build time. Peer of the sibling
6608        // [`restart_strategy_display_routes_through_as_str_helper`]
6609        // on the per-supervisor sibling-restart-strategy axis and
6610        // the M3
6611        // `placement_strategy_display_routes_through_as_str_helper`
6612        // (cc8f749) — the third of three OTP-shape closed-enum
6613        // discriminator axes on the caixa typed surface now
6614        // converged onto the same three-path
6615        // (Display → as_str → lifted const) discipline.
6616        for variant in [
6617            RestartPolicy::Permanent,
6618            RestartPolicy::Temporary,
6619            RestartPolicy::Transient,
6620        ] {
6621            assert_eq!(
6622                variant.to_string(),
6623                variant.as_str(),
6624                "RestartPolicy::{variant:?} Display must route through \
6625                 RestartPolicy::as_str (single source of truth: the lifted \
6626                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
6627            );
6628        }
6629    }
6630
6631    #[test]
6632    fn restart_policy_display_matches_serialized_wire_byte_string() {
6633        // The fail-before-pass-after pin on the second half of the
6634        // three-path convergence: `Display` (user-facing text) agrees
6635        // byte-for-byte with the `Serialize` derive's wire format
6636        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
6637        // scalar) on every variant. Pre-convergence the two paths
6638        // were structurally independent — a future
6639        // `#[serde(rename_all = "kebab-case")]` attribute on the
6640        // enum would silently rebrand the emitted wire scalar
6641        // (`permanent`, `temporary`, `transient`) while every
6642        // consumer that pretty-prints the policy (the future
6643        // wasm-operator's per-child post-exit restart-decision
6644        // diagnostic line, the future `feira app graph` per-child
6645        // restart column, the future M4
6646        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6647        // per-child admission-webhook rejection body) would still
6648        // emit the PascalCase form the `as_str` / `Display` route
6649        // returns, with the mismatch surfacing at consumer parse
6650        // time / operator dispatch time far from the source rebrand
6651        // commit. Pin the two paths byte-for-byte here so any future
6652        // serde-attribute or variant-rename drift is a
6653        // caixa-core-build-time test failure at this call, not a
6654        // silent per-consumer dispatch miss. Peer of the sibling
6655        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
6656        // on the per-supervisor sibling-restart-strategy axis and
6657        // the M3
6658        // `placement_strategy_display_matches_serialized_wire_byte_string`
6659        // (cc8f749).
6660        for variant in [
6661            RestartPolicy::Permanent,
6662            RestartPolicy::Temporary,
6663            RestartPolicy::Transient,
6664        ] {
6665            let wire = serde_json::to_string(&variant).unwrap();
6666            let unquoted = wire
6667                .strip_prefix('"')
6668                .and_then(|s| s.strip_suffix('"'))
6669                .expect("serialized RestartPolicy is a JSON string");
6670            assert_eq!(
6671                variant.to_string(),
6672                unquoted,
6673                "RestartPolicy::{variant:?} Display byte-string must match the \
6674                 Serialize derive's wire byte-string (three-path convergence: \
6675                 Display + as_str + Serialize all resolve to the same \
6676                 SUPERVISOR_CHILD_RESTART_* const)"
6677            );
6678        }
6679    }
6680
6681    #[test]
6682    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
6683        // Fail-before-pass-after byte-parity pin on the lifted
6684        // `impl AsRef<str> for RestartPolicy` — asserts the
6685        // standard-library trait impl and the substrate-primitive
6686        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
6687        // to the same `&str` per instance across the three-arm
6688        // closed set, so any future silent detour that routes the
6689        // impl through a divergent projection (a per-arm inline
6690        // `match self { RestartPolicy::Permanent => "Permanent", … }`
6691        // re-inlining that opens a compile-time link to the un-lifted
6692        // arm-literal, a swap onto the kebab-case
6693        // [`gen_platform::Discriminant`] catalog identity that would
6694        // collide the wire axis with the dispatcher-catalog axis) trips
6695        // at caixa-core test time under `PartialEq` rather than at a
6696        // downstream `impl AsRef<str>`-bound consumer's silent split.
6697        // Sweeps every one of the three arms
6698        // [`RestartPolicy::ALL`] carries so no arm's projection is
6699        // covered only by the sibling wire-format `Serialize` derive
6700        // path. Peer of the sibling
6701        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
6702        // (63eb1a4) on the paired per-supervisor sibling-restart-
6703        // strategy axis and the [`crate::CaixaVersion`]
6704        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
6705        // top-level `:versao` typed newtype — the three pins together
6706        // cover the substrate primitive's `AsRef<str>` projection axis
6707        // on the paired newtype + M2 closed-set-typed-enum surface.
6708        for &variant in RestartPolicy::ALL {
6709            assert_eq!(
6710                <RestartPolicy as AsRef<str>>::as_ref(&variant),
6711                variant.as_str(),
6712                "AsRef<str> impl on RestartPolicy::{variant:?} must \
6713                 byte-equal RestartPolicy::as_str on the same instance \
6714                 — divergence signals a silent detour off the substrate-\
6715                 primitive accessor"
6716            );
6717        }
6718    }
6719
6720    #[test]
6721    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
6722        // Fail-before-pass-after byte-parity pin on the three-path
6723        // convergence discipline the M2 per-child-restart-policy
6724        // primitive now carries on the `&str`-projection axis:
6725        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
6726        // lifted impl), `format!("{v}")` (the pre-existing
6727        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
6728        // primitive `pub const fn` accessor both trait impls delegate
6729        // through) must resolve to the same byte-string on every
6730        // instance across the three-arm closed set. Refuses any future
6731        // divergence between the two trait impls (a stray
6732        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6733        // rather than delegating through the shared accessor; a
6734        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6735        // literal cascade) that would silently split the two
6736        // projection paths of the same closed-set typed enum. Mirrors
6737        // the sibling three-path-convergence discipline the peer
6738        // [`RestartStrategy`] typed enum carries on its
6739        // `AsRef<str>` / `Display` / `as_str` triple
6740        // (supervisor.rs pin
6741        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
6742        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
6743        // carries on the same triple (version.rs pin
6744        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6745        // 16d5c7e).
6746        for &variant in RestartPolicy::ALL {
6747            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
6748            let via_display: String = format!("{variant}");
6749            let via_accessor: &str = variant.as_str();
6750            assert_eq!(via_as_ref, via_accessor);
6751            assert_eq!(via_display, via_accessor);
6752            assert_eq!(via_as_ref, via_display.as_str());
6753        }
6754    }
6755
6756    #[test]
6757    fn restart_policy_all_enumerates_every_variant_exactly_once() {
6758        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
6759        // exhaustive-iteration surface: every variant appears exactly
6760        // once, and the slice length matches the arm count of the
6761        // closed set. Every consumer that walks the accepted-policy
6762        // set (a future `feira supervisor --restart …` CLI-side
6763        // arg-parse's "did you mean" hint, a future M4 admission-
6764        // webhook's per-child rejection body naming the accepted-
6765        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
6766        // projection consumers that iterate the accept-set for
6767        // diagnostic rendering) reads through this slice, so a future
6768        // arm addition that grows the enum but forgets to grow
6769        // [`Self::ALL`] silently truncates every downstream consumer's
6770        // accept-set at the same pre-addition boundary — this pin
6771        // fails at caixa-core build time on the pairwise-distinct +
6772        // arm-count invariants.
6773        //
6774        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
6775        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
6776        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6777        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6778        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6779        // pins on the peer closed-set typed-enum axes.
6780        let all: &[RestartPolicy] = RestartPolicy::ALL;
6781        assert_eq!(
6782            all.len(),
6783            3,
6784            "RestartPolicy::ALL must enumerate every variant of the \
6785             three-arm closed set (Permanent, Temporary, Transient); \
6786             got {all:?}"
6787        );
6788        for (i, a) in all.iter().enumerate() {
6789            for (j, b) in all.iter().enumerate() {
6790                if i != j {
6791                    assert_ne!(
6792                        a, b,
6793                        "RestartPolicy::ALL must carry every variant exactly \
6794                         once — got duplicate {a:?} at indices {i} and {j}"
6795                    );
6796                }
6797            }
6798        }
6799        for variant in [
6800            RestartPolicy::Permanent,
6801            RestartPolicy::Temporary,
6802            RestartPolicy::Transient,
6803        ] {
6804            assert!(
6805                all.contains(&variant),
6806                "RestartPolicy::ALL must contain {variant:?} — a future arm \
6807                 addition that grows the enum but forgets to grow the ALL slice \
6808                 silently truncates every downstream consumer's accept-set at \
6809                 the pre-addition boundary"
6810            );
6811        }
6812    }
6813
6814    #[test]
6815    fn restart_policy_from_wire_accepts_every_lifted_constant() {
6816        // Fail-before-pass-after pin on the forward accept-set of the
6817        // [`RestartPolicy::from_wire`] reverse projection: every
6818        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
6819        // constant the [`RestartPolicy::as_str`] emitter walks parses
6820        // back to its paired variant. Any future arm addition that
6821        // grows the emitter's `as_str` match but forgets to grow the
6822        // parser's `from_wire` match silently splits the two halves of
6823        // the round-trip — the wire byte-string one non-serde consumer
6824        // parses from the one the emitter wrote — with the failure
6825        // surfacing at the operator's reconcile posture (a `:temporary`
6826        // `oneShot` child restarted on clean exit, a `:transient` child
6827        // restarted after clean completion) far from the rebrand
6828        // commit. Pinning the three-arm accept-set here catches the
6829        // drift at caixa-core build time.
6830        //
6831        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
6832        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
6833        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6834        // accept-set pins on the peer closed-set typed-enum `str → Self`
6835        // axes.
6836        for (wire, expected) in [
6837            (
6838                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6839                RestartPolicy::Permanent,
6840            ),
6841            (
6842                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6843                RestartPolicy::Temporary,
6844            ),
6845            (
6846                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6847                RestartPolicy::Transient,
6848            ),
6849        ] {
6850            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6851                panic!(
6852                    "RestartPolicy::from_wire({wire:?}) must accept every \
6853                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
6854                     lifted canonical byte-string that RestartPolicy::{expected:?} \
6855                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
6856                )
6857            });
6858            assert_eq!(
6859                parsed, expected,
6860                "RestartPolicy::from_wire({wire:?}) must return \
6861                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
6862            );
6863        }
6864    }
6865
6866    #[test]
6867    fn restart_policy_from_wire_round_trips_through_as_str() {
6868        // Fail-before-pass-after pin on the closed round-trip between
6869        // the forward [`RestartPolicy::as_str`] emitter and the
6870        // reverse [`RestartPolicy::from_wire`] parser: for every
6871        // variant in [`RestartPolicy::ALL`], parsing the emitter's
6872        // output must return exactly the same variant. Any per-arm
6873        // divergence — a future arm added to `as_str` but not
6874        // `from_wire`, an accidental copy-paste flip in one but not
6875        // the other — silently splits the emit and parse halves and
6876        // the failure surfaces at consumer parse time far from the
6877        // drift site. The `ALL`-iterating shape means a future arm
6878        // addition picks up the coverage by construction.
6879        //
6880        // Peer of the sibling
6881        // [`restart_strategy_from_wire_round_trips_through_as_str`]
6882        // (4eec29c) round-trip pin on
6883        // [`RestartStrategy::from_wire`] and the M3
6884        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6885        // (18c7342) round-trip pin on
6886        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6887        for &variant in RestartPolicy::ALL {
6888            let wire = variant.as_str();
6889            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6890                panic!(
6891                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6892                     must be Some({variant:?}) — the two halves of the round-trip \
6893                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
6894                     got None on wire byte-string {wire:?}"
6895                )
6896            });
6897            assert_eq!(
6898                parsed, variant,
6899                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6900                 must round-trip to the same variant; got {parsed:?}"
6901            );
6902        }
6903    }
6904
6905    #[test]
6906    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
6907        // Fail-before-pass-after pin on the closed-set refusal
6908        // discipline of [`RestartPolicy::from_wire`]: every
6909        // byte-string outside the three-arm accept-set returns `None`
6910        // rather than silently collapsing onto the [`Default`]
6911        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
6912        // exercised here sweeps the load-bearing drift shapes: the
6913        // empty string (a stripped serde-attribute drift), all-
6914        // whitespace strings (the canonical text-editor accidental
6915        // padding shape), the kebab-case dispatcher-catalog identities
6916        // (`"permanent"` / `"temporary"` / `"transient"` — the
6917        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
6918        // accept-set, which parses the *other* axis of this enum's
6919        // two-axis split and must not leak into the `from_wire`
6920        // PascalCase-wire accept-set — a lowercase leak here would
6921        // silently accept the operator's kebab-case
6922        // dispatcher-catalog probe under the wire-axis parser and mis-
6923        // route a `:permanent` intent), the padded canonical scalar
6924        // (`" Permanent "`), the trailing-newline shapes
6925        // (`"Permanent\n"`), the uppercase-single-word forms
6926        // (`"PERMANENT"`), and neighboring-but-unknown arms
6927        // (`"Restart"` — the canonical typo direction toward the
6928        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
6929        //
6930        // Peer of the sibling
6931        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
6932        // (4eec29c) +
6933        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6934        // (2aa6d23) +
6935        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6936        // (18c7342) refusal pins on the peer closed-set typed-enum
6937        // axes.
6938        for bad in [
6939            "",
6940            " ",
6941            "\n",
6942            "\t",
6943            "permanent",
6944            "temporary",
6945            "transient",
6946            "PERMANENT",
6947            "TEMPORARY",
6948            "TRANSIENT",
6949            "Permanents",
6950            "Permanent ",
6951            " Permanent",
6952            " Transient ",
6953            "Permanent\n",
6954            "perma",
6955            "Trans",
6956            "OneForOne",
6957            "Restart",
6958            "?",
6959        ] {
6960            assert!(
6961                RestartPolicy::from_wire(bad).is_none(),
6962                "RestartPolicy::from_wire({bad:?}) must return None — the \
6963                 parser's accept-set is exactly the three RestartPolicy::as_str \
6964                 outputs (Permanent, Temporary, Transient), and this \
6965                 byte-string is outside that closed set"
6966            );
6967        }
6968    }
6969
6970    #[test]
6971    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
6972        // Fail-before-pass-after pin on the fourth path of the four-path
6973        // convergence: `from_wire` (the reverse projection) inverts the
6974        // `Serialize` derive's wire byte-string on every variant.
6975        // Together with the pre-existing three-path convergence
6976        // (`Display` + `as_str` + `Serialize` all resolve to the same
6977        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
6978        // pinned by
6979        // [`restart_policy_display_matches_serialized_wire_byte_string`])
6980        // this closes the round-trip: the wire byte-string the
6981        // `Serialize` derive emits parses back to the same variant
6982        // through `from_wire`, so any future serde-attribute or variant-
6983        // rename drift on the emit half now surfaces as a matched drift
6984        // on the parse half at caixa-core build time — the two halves
6985        // migrate as a unit through the lifted consts on any future
6986        // rename, and the round-trip cannot silently split.
6987        //
6988        // Peer of the sibling
6989        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6990        // (4eec29c) wire-format pin on
6991        // [`RestartStrategy::from_wire`] and the M3
6992        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6993        // (18c7342) wire-format pin on
6994        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6995        for &variant in RestartPolicy::ALL {
6996            let wire = serde_json::to_string(&variant).unwrap();
6997            let unquoted = wire
6998                .strip_prefix('"')
6999                .and_then(|s| s.strip_suffix('"'))
7000                .expect("serialized RestartPolicy is a JSON string");
7001            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
7002                panic!(
7003                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
7004                     Serialize derive's wire byte-string for \
7005                     RestartPolicy::{variant:?} — the four-path convergence \
7006                     (Display + as_str + Serialize + from_wire) resolves through \
7007                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
7008                )
7009            });
7010            assert_eq!(
7011                parsed, variant,
7012                "RestartPolicy::from_wire of the Serialize derive's wire \
7013                 byte-string for RestartPolicy::{variant:?} must round-trip \
7014                 to the same variant; got {parsed:?}"
7015            );
7016        }
7017    }
7018
7019    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
7020    //
7021    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
7022    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
7023    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
7024    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
7025    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
7026    // the peer per-`:upgrade-from :from` axis. The three pins jointly
7027    // brace the accessor against every future silent detour that would
7028    // desynchronize it from the raw `.caixa` field access every consumer
7029    // previously open-coded.
7030
7031    #[test]
7032    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
7033        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
7034        // [`ChildSpec::nome`] must return the `:children :caixa` field
7035        // byte-for-byte across every DNS-1123-label value the upstream
7036        // [`crate::render::require_valid_dns_1123_label`] gate at
7037        // `SupervisorSpec::validate` admits. Peer of the sibling
7038        // `membro_nome_returns_caixa_byte_equal_across_permutations`
7039        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
7040        // substrate-primitive accessor must byte-equal the raw field
7041        // access verbatim across every author-declared value" discipline
7042        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7043        // against a future silent detour that re-normalized the child
7044        // identity (an accidental `.to_lowercase()` — every `:children
7045        // :caixa` is validated as a DNS-1123 label upstream, so any
7046        // re-normalization is redundant + a drift surface between the
7047        // validator and the accessor), a namespace-prefix rewrite (an
7048        // accidental `format!("{namespace}/{caixa}")` per-CR
7049        // fully-qualified rewrite that didn't land on the peer axes), or
7050        // a per-cluster alias stamp the future wasm-operator's
7051        // hierarchical reconciliation scheduler authors on one consumer
7052        // without the others. Five values sweep the accept-set the
7053        // DNS-1123 gate upstream admits (short single-word / dashed /
7054        // v-suffixed / mixed-digit child names).
7055        for name in [
7056            "worker",
7057            "cache-server",
7058            "scratch-job",
7059            "orders-v2",
7060            "session-8080",
7061        ] {
7062            let c = ChildSpec {
7063                caixa: name.into(),
7064                versao: "^0.1".into(),
7065                restart: RestartPolicy::Permanent,
7066            };
7067            assert_eq!(
7068                c.nome(),
7069                name,
7070                "ChildSpec::nome must return :children :caixa verbatim \
7071                 (got {:?}, expected {name:?})",
7072                c.nome(),
7073            );
7074            assert_eq!(
7075                c.nome(),
7076                c.caixa.as_str(),
7077                "ChildSpec::nome must byte-equal the .caixa field access",
7078            );
7079        }
7080    }
7081
7082    #[test]
7083    fn child_spec_nome_borrows_from_caixa_storage() {
7084        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
7085        // `&str` slice that borrows from the typed slot's own [`String`]
7086        // storage — same-address invariant with `c.caixa.as_str()`. Pins
7087        // against a future silent detour that allocated a fresh `String`
7088        // (`self.caixa.clone()` in the body would type-check but silently
7089        // drop the borrow, and every downstream consumer that assumed
7090        // the returned slice outlives `&self` would break on a stale-
7091        // reference use-after-free — the [`crate::render::insert_first_seen`]
7092        // dedup key at [`SupervisorSpec::validate`], the
7093        // [`validate_no_self_supervision`] equality check against the
7094        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
7095        // borrow — each would silently misbehave if this accessor
7096        // produced a detached copy). Peer of the sibling
7097        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
7098        // M3 per-`:membros` axis and the
7099        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
7100        // first M2 slot scalar accessor.
7101        let c = ChildSpec {
7102            caixa: "worker".into(),
7103            versao: "^0.1".into(),
7104            restart: RestartPolicy::Permanent,
7105        };
7106        let name = c.nome();
7107        let caixa_slice = c.caixa.as_str();
7108        assert_eq!(
7109            name.as_ptr(),
7110            caixa_slice.as_ptr(),
7111            "ChildSpec::nome must borrow from the .caixa String's backing \
7112             storage — a fresh allocation here means the accessor no \
7113             longer names the substrate-primitive typed dispatch and \
7114             every downstream consumer would silently carry a detached \
7115             copy",
7116        );
7117        assert_eq!(
7118            name.len(),
7119            caixa_slice.len(),
7120            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
7121             as well as in address",
7122        );
7123    }
7124
7125    #[test]
7126    fn validate_gates_child_nome_through_lifted_accessor() {
7127        // Bilateral coherence pin: every `:children :caixa` that
7128        // [`SupervisorSpec::validate`] accepts is one
7129        // [`crate::render::require_valid_dns_1123_label`] accepts on the
7130        // accessor-projected value, and vice versa on the reject side.
7131        // This closes the "the validator reads through the accessor"
7132        // contract structurally — a future silent detour that made the
7133        // accessor return a different byte-string than the validator
7134        // gates against would surface here as a coverage mismatch, not
7135        // as an apply-time DNS-1123 rejection at
7136        // `metadata.name: Invalid value` far from the caixa.lisp source.
7137        // Peer of the M2 sibling
7138        // `validate_parses_prior_versao_through_lifted_accessor`
7139        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
7140        // `validate_membros` peer discipline.
7141        //
7142        // Accept-set sweep: five DNS-1123-label values the upstream gate
7143        // admits.
7144        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
7145            let s = SupervisorSpec {
7146                children: vec![ChildSpec {
7147                    caixa: ok_name.into(),
7148                    versao: "^0.1".into(),
7149                    restart: RestartPolicy::Permanent,
7150                }],
7151                ..SupervisorSpec::default()
7152            };
7153            s.validate().unwrap_or_else(|e| {
7154                panic!(
7155                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
7156                     (upstream DNS-1123 gate accepts it): got {e:?}",
7157                );
7158            });
7159            let c = ChildSpec {
7160                caixa: ok_name.into(),
7161                versao: "^0.1".into(),
7162                restart: RestartPolicy::Permanent,
7163            };
7164            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
7165                .unwrap_or_else(|()| {
7166                    panic!(
7167                        "require_valid_dns_1123_label must accept the accessor-projected \
7168                     :children :caixa {ok_name:?}",
7169                    );
7170                });
7171        }
7172        // Reject-set sweep: five DNS-1123-label-violating shapes the
7173        // upstream gate refuses (empty / uppercase / underscore / dot /
7174        // leading-hyphen). Every rejection at the validator must
7175        // correspond to a rejection when the accessor's projected value
7176        // is fed back through the shared gate.
7177        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
7178            let s = SupervisorSpec {
7179                children: vec![ChildSpec {
7180                    caixa: bad_name.into(),
7181                    versao: "^0.1".into(),
7182                    restart: RestartPolicy::Permanent,
7183                }],
7184                ..SupervisorSpec::default()
7185            };
7186            let err = s.validate().unwrap_err();
7187            assert!(
7188                matches!(
7189                    err,
7190                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
7191                ),
7192                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
7193                 via the DNS-1123 gate: got {err:?}",
7194            );
7195            let c = ChildSpec {
7196                caixa: bad_name.into(),
7197                versao: "^0.1".into(),
7198                restart: RestartPolicy::Permanent,
7199            };
7200            assert!(
7201                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
7202                    .is_err(),
7203                "require_valid_dns_1123_label must reject the accessor-projected \
7204                 :children :caixa {bad_name:?}",
7205            );
7206        }
7207    }
7208
7209    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
7210    //
7211    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
7212    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
7213    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
7214    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
7215    // trio on the peer per-`:children` `String`-carry axis. The three pins
7216    // jointly brace the accessor against every future silent detour that
7217    // would desynchronize it from the raw `.versao` field access the
7218    // requirement gate + error carrier previously open-coded.
7219    //
7220    // Closes the last unlifted per-`:children` `String`-carry axis: the
7221    // pair (`nome`, `versao_requirement`) now jointly projects the
7222    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
7223    // consumer that fans on per-child identity + version pin reads,
7224    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
7225    // pair discipline verbatim.
7226    #[test]
7227    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
7228        // The canonical per-`:children` child-`:versao`-scalar pin:
7229        // [`ChildSpec::versao_requirement`] must return the `:children
7230        // :versao` field byte-for-byte across every Cargo-shaped semver
7231        // requirement value the upstream
7232        // [`crate::render::require_valid_versao_requirement`] gate admits.
7233        // Peer of the sibling
7234        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
7235        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
7236        // substrate-primitive accessor must byte-equal the raw field
7237        // access verbatim across every author-declared value" discipline
7238        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7239        // against a future silent detour that re-canonicalized the
7240        // requirement (an accidental `.to_string()` via
7241        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
7242        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
7243        // silently drifted the error carrier's quoted requirement away
7244        // from the source `caixa.lisp`, an accidental whitespace trim on
7245        // `"^ 0.1"` that no consumer ever produced from the field-access
7246        // side, an accidental per-cluster lacre-projected concrete-version
7247        // rewrite that didn't land on the peer requirement-gate call).
7248        // Five values sweep the accept-set the shared
7249        // [`crate::render::require_valid_versao_requirement`] gate admits
7250        // (caret / tilde / exact / wildcard / bare-major).
7251        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7252            let c = ChildSpec {
7253                caixa: "worker".into(),
7254                versao: req.into(),
7255                restart: RestartPolicy::Permanent,
7256            };
7257            assert_eq!(
7258                c.versao_requirement(),
7259                req,
7260                "ChildSpec::versao_requirement must return :children :versao \
7261                 verbatim (got {:?}, expected {req:?})",
7262                c.versao_requirement(),
7263            );
7264            assert_eq!(
7265                c.versao_requirement(),
7266                c.versao.as_str(),
7267                "ChildSpec::versao_requirement must byte-equal the .versao \
7268                 field access",
7269            );
7270        }
7271    }
7272
7273    #[test]
7274    fn child_spec_versao_requirement_borrows_from_versao_storage() {
7275        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
7276        // return a `&str` slice that borrows from the typed slot's own
7277        // [`String`] storage — same-address invariant with
7278        // `c.versao.as_str()`. Pins against a future silent detour that
7279        // allocated a fresh `String` (`self.versao.clone()` in the body
7280        // would type-check but silently drop the borrow, and every
7281        // downstream consumer that assumed the returned slice outlives
7282        // `&self` — the [`crate::render::require_valid_versao_requirement`]
7283        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
7284        // `.to_string()` carrier's byte-length assumption — would silently
7285        // misbehave if this accessor produced a detached copy). Peer of
7286        // the sibling `child_spec_nome_borrows_from_caixa_storage`
7287        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
7288        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
7289        // pin on the peer per-`:membros` `:versao` axis.
7290        let c = ChildSpec {
7291            caixa: "worker".into(),
7292            versao: "^0.1".into(),
7293            restart: RestartPolicy::Permanent,
7294        };
7295        let req = c.versao_requirement();
7296        let versao_slice = c.versao.as_str();
7297        assert_eq!(
7298            req.as_ptr(),
7299            versao_slice.as_ptr(),
7300            "ChildSpec::versao_requirement must borrow from the .versao \
7301             String's backing storage — a fresh allocation here means the \
7302             accessor no longer names the substrate-primitive typed \
7303             dispatch and every downstream consumer would silently carry \
7304             a detached copy",
7305        );
7306        assert_eq!(
7307            req.len(),
7308            versao_slice.len(),
7309            "ChildSpec::versao_requirement and .versao.as_str() must \
7310             byte-equal in length as well as in address",
7311        );
7312    }
7313
7314    #[test]
7315    fn validate_gates_child_versao_through_lifted_accessor() {
7316        // Bilateral coherence pin: every `:children :versao` that
7317        // [`SupervisorSpec::validate`] accepts is one
7318        // [`crate::render::require_valid_versao_requirement`] accepts on
7319        // the accessor-projected value, and vice versa on the reject side.
7320        // This closes the "the validator reads through the accessor"
7321        // contract structurally — a future silent detour that made the
7322        // accessor return a different byte-string than the validator gates
7323        // against would surface here as a coverage mismatch, not as a
7324        // resolver-time semver-parse rejection at lacre-closure time far
7325        // from the caixa.lisp source. Peer of the sibling
7326        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
7327        // the per-`:children :caixa` axis and the M2
7328        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
7329        // on the peer per-`:upgrade-from :from` axis.
7330        //
7331        // Accept-set sweep: five Cargo-shaped semver requirement values
7332        // the upstream gate admits (caret / tilde / exact / wildcard /
7333        // bare-major).
7334        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7335            let s = SupervisorSpec {
7336                children: vec![ChildSpec {
7337                    caixa: "worker".into(),
7338                    versao: ok_req.into(),
7339                    restart: RestartPolicy::Permanent,
7340                }],
7341                ..SupervisorSpec::default()
7342            };
7343            s.validate().unwrap_or_else(|e| {
7344                panic!(
7345                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
7346                     (upstream versao-requirement gate accepts it): got {e:?}",
7347                );
7348            });
7349            let c = ChildSpec {
7350                caixa: "worker".into(),
7351                versao: ok_req.into(),
7352                restart: RestartPolicy::Permanent,
7353            };
7354            crate::render::require_valid_versao_requirement(
7355                c.versao_requirement(),
7356                || (),
7357                |_reason| (),
7358            )
7359            .unwrap_or_else(|()| {
7360                panic!(
7361                    "require_valid_versao_requirement must accept the accessor-projected \
7362                     :children :versao {ok_req:?}",
7363                );
7364            });
7365        }
7366        // Reject-set sweep: five requirement-violating shapes the upstream
7367        // gate refuses. The empty string closes the empty-first arm of the
7368        // shared [`crate::render::require_valid_versao_requirement`]
7369        // cascade; the four non-empty arms exercise distinct semver-parse
7370        // failure modes the M3 peer per-`:membros` reject-set already pins
7371        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
7372        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
7373        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
7374        // shared parser routing means the same reject-set must fail
7375        // identically at the M2 supervisor-tree per-`:children` accessor
7376        // arm here. Every rejection at the validator must correspond to a
7377        // rejection when the accessor's projected value is fed back
7378        // through the shared gate.
7379        //
7380        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
7381        // `"not-a-semver"` are intentionally *not* in the reject-set: the
7382        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
7383        // and the identifier-tail arm's grammar admits some non-canonical
7384        // shapes — matching what the M3 peer test suite already documents
7385        // as the shared parser's accept-set edges.)
7386        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
7387            let s = SupervisorSpec {
7388                children: vec![ChildSpec {
7389                    caixa: "worker".into(),
7390                    versao: bad_req.into(),
7391                    restart: RestartPolicy::Permanent,
7392                }],
7393                ..SupervisorSpec::default()
7394            };
7395            let err = s.validate().unwrap_err();
7396            assert!(
7397                matches!(
7398                    err,
7399                    SupervisorError::EmptyChildVersion { .. }
7400                        | SupervisorError::ChildVersaoInvalid { .. }
7401                ),
7402                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
7403                 via the versao-requirement gate: got {err:?}",
7404            );
7405            let c = ChildSpec {
7406                caixa: "worker".into(),
7407                versao: bad_req.into(),
7408                restart: RestartPolicy::Permanent,
7409            };
7410            assert!(
7411                crate::render::require_valid_versao_requirement(
7412                    c.versao_requirement(),
7413                    || (),
7414                    |_reason| (),
7415                )
7416                .is_err(),
7417                "require_valid_versao_requirement must reject the accessor-projected \
7418                 :children :versao {bad_req:?}",
7419            );
7420        }
7421    }
7422
7423    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
7424    //
7425    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
7426    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
7427    // already project the `String`-carry `(caixa, versao)` fields; the
7428    // `Copy`-composite-enum `restart` field is the third and final axis).
7429    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
7430    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
7431    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
7432    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
7433    // strategy scalar accessor — same "one typed dispatch on the substrate
7434    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
7435    // extended onto the M2 supervisor-slot per-`:children` restart-decision
7436    // axis. The pin below covers the accessor's byte-equal projection
7437    // against the raw field access across every variant in the closed
7438    // accept-set (`Permanent`, `Transient`, `Temporary`).
7439
7440    #[test]
7441    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
7442        // The canonical per-`:children` restart-decision-policy-scalar
7443        // pin: [`ChildSpec::restart`] must return the `:children :restart`
7444        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
7445        // typed slot's own [`RestartPolicy`] storage across every variant
7446        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
7447        // Pins against a future silent detour that re-derived the policy
7448        // from a peer axis (an accidental fallback to
7449        // `if is_supervisor_child { Permanent } else { Temporary }` that
7450        // collapsed the child's kind axis into the restart discriminator),
7451        // a variant remap the operator authors on one consumer without the
7452        // other, or a stale-derive detour that substituted
7453        // [`RestartPolicy::default`] when the field held any explicit
7454        // variant (which would silently collapse the distinction between
7455        // "author explicitly declared `:restart Permanent`" and "author
7456        // omitted the slot and inherited the default" the future
7457        // per-cluster restart-decision override slot depends on).
7458        //
7459        // Peer of the sibling per-`:supervisor`
7460        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7461        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
7462        // axis and the M3
7463        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7464        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
7465        // — same "the substrate-primitive accessor must byte-equal the raw
7466        // field access verbatim across every author-declared value"
7467        // discipline extended onto the M2 supervisor-slot per-`:children`
7468        // restart-decision-policy axis, closing the last unlifted axis on
7469        // the per-`:children` [`ChildSpec`] type.
7470        for restart in [
7471            RestartPolicy::Permanent,
7472            RestartPolicy::Transient,
7473            RestartPolicy::Temporary,
7474        ] {
7475            let c = ChildSpec {
7476                caixa: "worker".into(),
7477                versao: "^0.1".into(),
7478                restart,
7479            };
7480            assert_eq!(
7481                c.restart(),
7482                restart,
7483                "ChildSpec::restart must return :children :restart \
7484                 verbatim (got {:?}, expected {restart:?})",
7485                c.restart(),
7486            );
7487            assert_eq!(
7488                c.restart(),
7489                c.restart,
7490                "ChildSpec::restart accessor and .restart field access \
7491                 must byte-equal — the accessor is the substrate-primitive \
7492                 typed dispatch every downstream per-child restart-\
7493                 decision consumer must route through",
7494            );
7495        }
7496    }
7497
7498    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
7499    //
7500    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
7501    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
7502    // distribution-strategy accessor discipline onto the M2 supervisor-slot
7503    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
7504    // scalar axis. The two pins below cover (1) the accessor's byte-equal
7505    // projection against the raw field access across every variant in the
7506    // closed accept-set, and (2) the two-consumer coherence between the
7507    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
7508    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
7509    // carrier's `estrategia:` field — peer of the sibling M3
7510    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7511    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
7512    // pair on the per-`:placement` distribution-strategy axis.
7513
7514    #[test]
7515    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
7516        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
7517        // pin: [`SupervisorSpec::estrategia`] must return the
7518        // `:supervisor :estrategia` field verbatim as a
7519        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
7520        // [`RestartStrategy`] storage across every variant in the closed
7521        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
7522        // `SimpleOneForOne`). Pins against a future silent detour that
7523        // re-derived the strategy from a peer axis (an accidental
7524        // fallback to `if children.is_empty() { SimpleOneForOne } else {
7525        // OneForOne }` collapse that read the children-count axis into
7526        // the strategy discriminator), a variant remap the operator
7527        // authors on one consumer without the other, or a stale-derive
7528        // detour that substituted [`RestartStrategy::default`] when the
7529        // field held any explicit variant (which would silently collapse
7530        // the distinction between "author explicitly declared
7531        // `:estrategia OneForOne`" and "author omitted the slot and
7532        // inherited the default" the future per-cluster strategy override
7533        // slot depends on). Peer of the sibling M3
7534        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7535        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
7536        // axis — same "the substrate-primitive accessor must byte-equal
7537        // the raw field access verbatim across every author-declared
7538        // value" discipline extended onto the M2 supervisor-slot
7539        // per-`:supervisor` sibling-restart-strategy axis.
7540        for &estrategia in RestartStrategy::ALL {
7541            // `SimpleOneForOne` requires `children.is_empty()`; the peer
7542            // three strategies require a non-empty static children list.
7543            // Build each shape coherently so the pin's fixture would
7544            // itself pass [`SupervisorSpec::validate`] once fed through
7545            // the sibling coherence pin below — the byte-equal projection
7546            // asserted here is a strictly weaker property (a `Copy` field
7547            // read) that does not depend on `validate` running, but
7548            // keeping the fixture validate-clean means a future extension
7549            // of the pin to exercise `validate` end-to-end does not have
7550            // to re-author the children shape.
7551            //
7552            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7553            // shape partition through the [`gen_platform::IsVariant`]
7554            // derive-generated
7555            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
7556            // than the raw `matches!(estrategia, RestartStrategy::
7557            // SimpleOneForOne)` open-coded pattern-match — same closed-
7558            // set-typed-enum arm-discriminator dispatch discipline the
7559            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
7560            // convergence (915a934) extended onto its two paired positive
7561            // / negated `matches!` sites and the peer
7562            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7563            // predicate convergence (766ec63) extended onto the M3 mesh-
7564            // slot per-`:placement` distribution-strategy discriminator
7565            // axis. See the sibling `round_trip_all_strategies` and the
7566            // peer `manifest::tests::
7567            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7568            // fixture for the two peer sites the same lift closes on.
7569            let children = if estrategia.is_simple_one_for_one() {
7570                Vec::new()
7571            } else {
7572                vec![ChildSpec {
7573                    caixa: "worker".into(),
7574                    versao: "^0.1".into(),
7575                    restart: RestartPolicy::Permanent,
7576                }]
7577            };
7578            let s = SupervisorSpec {
7579                estrategia,
7580                children,
7581                ..SupervisorSpec::default()
7582            };
7583            assert_eq!(
7584                s.estrategia(),
7585                estrategia,
7586                "SupervisorSpec::estrategia must return :supervisor :estrategia \
7587                 verbatim (got {:?}, expected {estrategia:?})",
7588                s.estrategia(),
7589            );
7590            assert_eq!(
7591                s.estrategia(),
7592                s.estrategia,
7593                "SupervisorSpec::estrategia accessor and .estrategia field \
7594                 access must byte-equal — the accessor is the substrate-\
7595                 primitive typed dispatch every downstream sibling-restart-\
7596                 strategy consumer must route through",
7597            );
7598        }
7599    }
7600
7601    #[test]
7602    fn validate_reads_through_lifted_estrategia_accessor() {
7603        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
7604        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
7605        // dispatch (which reads through [`SupervisorSpec::estrategia`]
7606        // to fan across the strategy-arm shape-gate cascades) and the
7607        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
7608        // error carrier's `estrategia:` field (which reads through
7609        // [`SupervisorSpec::estrategia`] to name the strategy the empty
7610        // `:children` list was declared against) must both key off the
7611        // lifted accessor, so any future rebrand on the typed slot's
7612        // reader shape lands at exactly one place. Pins the two-site
7613        // coherence by exercising the `NoChildren` error surface end-to-
7614        // end across every non-`SimpleOneForOne` variant and asserting
7615        // the surfaced `estrategia:` field byte-equals the accessor's
7616        // return. Peer of the sibling M3
7617        // `validate_placement_reads_through_lifted_estrategia_accessor`
7618        // (921fe1b) three-consumer coherence pin on the per-`:placement`
7619        // distribution-strategy axis.
7620        for estrategia in [
7621            RestartStrategy::OneForOne,
7622            RestartStrategy::OneForAll,
7623            RestartStrategy::RestForOne,
7624        ] {
7625            let s = SupervisorSpec {
7626                estrategia,
7627                children: Vec::new(),
7628                ..SupervisorSpec::default()
7629            };
7630            let err = s.validate().unwrap_err();
7631            match err {
7632                SupervisorError::NoChildren { estrategia: e } => {
7633                    assert_eq!(
7634                        e,
7635                        s.estrategia(),
7636                        "NoChildren.estrategia must byte-equal \
7637                         SupervisorSpec::estrategia() — the empty-`:children` \
7638                         refusal reads through the lifted accessor",
7639                    );
7640                    assert_eq!(
7641                        e, estrategia,
7642                        "NoChildren.estrategia must carry the author-declared \
7643                         :supervisor :estrategia variant verbatim (got {e:?}, \
7644                         expected {estrategia:?})",
7645                    );
7646                }
7647                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
7648            }
7649        }
7650    }
7651
7652    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
7653    //
7654    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
7655    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
7656    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
7657    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
7658    // The two pins below cover (1) the accessor's byte-equal projection
7659    // against the raw field access across every representative value in
7660    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
7661    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
7662    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
7663    // zero-floor / cap composition — the validate gate and the accessor
7664    // must route through the same substrate-primitive typed dispatch, so
7665    // any future silent detour that had the accessor perform a
7666    // bounds-collapsing clamp would fail here at caixa-core build time.
7667    // Peer of the sibling M3
7668    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7669    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
7670
7671    #[test]
7672    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
7673        // The canonical per-`:supervisor` restart-budget-count scalar pin:
7674        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
7675        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
7676        // typed slot's own `u32` storage, byte-equal to the raw field
7677        // access across every representative value in the accept-set —
7678        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
7679        // accept-set the surrounding [`SupervisorSpec::validate`] gate
7680        // carves out on the sibling `ZeroMaxRestarts` refusal),
7681        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
7682        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
7683        // (a past-the-guard sentinel that pins the accessor doesn't
7684        // perform a silent bounds-collapse into `1` on the zero arm —
7685        // validate rejects zero but the accessor must ship the raw slot
7686        // verbatim so a validate-time gate regression surfaces at the
7687        // emit boundary rather than being silently absorbed), `u32::MAX`
7688        // (a past-the-guard sentinel that pins the accessor doesn't
7689        // perform a silent bounds-collapse through
7690        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
7691        //
7692        // Peer of the sibling M3
7693        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7694        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
7695        // required-scalar axis — same "the substrate-primitive accessor
7696        // must byte-equal the raw field access verbatim across every
7697        // value in the `u32` accept-set" discipline extended onto the M2
7698        // supervisor-slot per-`:supervisor` restart-budget-count axis.
7699        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
7700            let s = SupervisorSpec {
7701                max_restarts,
7702                ..SupervisorSpec::default()
7703            };
7704            assert_eq!(
7705                s.max_restarts(),
7706                max_restarts,
7707                "SupervisorSpec::max_restarts must return :supervisor \
7708                 :max-restarts verbatim (got {}, expected {max_restarts})",
7709                s.max_restarts(),
7710            );
7711            assert_eq!(
7712                s.max_restarts(),
7713                s.max_restarts,
7714                "SupervisorSpec::max_restarts accessor and .max_restarts \
7715                 field access must byte-equal — the accessor is the \
7716                 substrate-primitive typed dispatch every downstream \
7717                 restart-budget-count consumer must route through",
7718            );
7719        }
7720    }
7721
7722    #[test]
7723    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
7724        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
7725        // zero-floor + upper-cap bracket must key off
7726        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
7727        // field access. Structurally: a `SupervisorSpec { max_restarts:
7728        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
7729        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7730        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
7731        // (with the offending count carried verbatim from the accessor
7732        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
7733        // lower boundary of the accept-set) plus a `SupervisorSpec {
7734        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
7735        // boundary) must pass validate. The four together jointly pin the
7736        // accessor + validate-gate composition: any future silent detour
7737        // that had the accessor return a fresh `1` on the zero arm (a
7738        // `.max_restarts().max(1)` collapse) would silently absorb the
7739        // `ZeroMaxRestarts` refusal at the accessor boundary and the
7740        // validate gate would accept a struct-literal `SupervisorSpec {
7741        // max_restarts: 0, .. }` — the composition pin catches that at
7742        // caixa-core build time.
7743        //
7744        // Peer of the sibling M3
7745        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
7746        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
7747        // composition axis — same "the validate / shape-gate predicate
7748        // must route through the substrate-primitive typed dispatch"
7749        // discipline extended onto the peer M2 supervisor-slot
7750        // required-`u32` composition axis.
7751        let child = ChildSpec {
7752            caixa: "worker".into(),
7753            versao: "^0.1".into(),
7754            restart: RestartPolicy::Permanent,
7755        };
7756        // Zero-floor arm.
7757        let s = SupervisorSpec {
7758            max_restarts: 0,
7759            children: vec![child.clone()],
7760            ..SupervisorSpec::default()
7761        };
7762        assert_eq!(
7763            s.validate().unwrap_err(),
7764            SupervisorError::ZeroMaxRestarts,
7765            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
7766             — the accessor and the validate gate must route through the \
7767             same substrate-primitive typed dispatch on the zero-floor arm",
7768        );
7769        // Cap arm — the surfaced `max_restarts:` field must byte-equal
7770        // the accessor's return so a future rebrand on the accessor
7771        // lands in the diagnostic without a coordinated rewrite.
7772        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
7773        let s = SupervisorSpec {
7774            max_restarts: over_cap,
7775            children: vec![child.clone()],
7776            ..SupervisorSpec::default()
7777        };
7778        match s.validate().unwrap_err() {
7779            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
7780                assert_eq!(
7781                    max_restarts,
7782                    s.max_restarts(),
7783                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
7784                     SupervisorSpec::max_restarts() — the cap-arm refusal \
7785                     reads through the lifted accessor",
7786                );
7787                assert_eq!(
7788                    max_restarts, over_cap,
7789                    "MaxRestartsExceedsCap.max_restarts must carry the \
7790                     author-declared :supervisor :max-restarts value \
7791                     verbatim (got {max_restarts}, expected {over_cap})",
7792                );
7793            }
7794            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
7795        }
7796        // Lower + upper accept-set boundaries.
7797        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
7798            let s = SupervisorSpec {
7799                max_restarts,
7800                children: vec![child.clone()],
7801                ..SupervisorSpec::default()
7802            };
7803            assert!(
7804                s.validate().is_ok(),
7805                "validate must accept max_restarts == {max_restarts} \
7806                 (an accept-set boundary of \
7807                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
7808            );
7809        }
7810    }
7811
7812    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
7813    //
7814    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
7815    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
7816    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
7817    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
7818    // supervisor-slot per-`:supervisor` restart-intensity-denominator
7819    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
7820    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
7821    // per-`:supervisor` scalar-value axis. The three pins below cover
7822    // (1) the accessor's byte-equal projection against the raw field
7823    // access across every representative value in the `Option<Duration>`
7824    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
7825    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
7826    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
7827    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
7828    // `if let Some(w) = self.restart_window() { … }` bracket-arm
7829    // composition — the validate gate and the accessor must route through
7830    // the same substrate-primitive typed dispatch, so any future silent
7831    // detour that had the accessor perform a bounds-collapsing clamp
7832    // would fail here at caixa-core build time, and (3) the accessor's
7833    // by-copy idempotence pin — the returned `Option<Duration>` must
7834    // outlive `&self` and two successive calls must return byte-equal
7835    // values. Peer of the sibling M2
7836    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7837    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
7838    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7839    // (7073d0f) pin on the per-`:politicas :timeout` axis.
7840
7841    #[test]
7842    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
7843        // The canonical per-`:supervisor` restart-intensity-denominator
7844        // scalar pin: [`SupervisorSpec::restart_window`] must return the
7845        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
7846        // `Option<Duration>`, `Copy`-projected from the typed slot's own
7847        // `Option<Duration>` storage, byte-equal to the raw field access
7848        // across every representative value in the accept-set — `None`
7849        // (the "never reset — every restart across the supervisor's
7850        // lifetime counts against the sibling `:max-restarts` budget"
7851        // sentinel the field's own docstring names and the peer
7852        // `validate_accepts_none_restart_window` pin locks in on the
7853        // [`SupervisorSpec::validate`] entry-side),
7854        // `Some(Duration::from_millis(1))` (the structural minimum a
7855        // validated `:restart-window` may carry, the integer-millisecond
7856        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
7857        // everything sub-ms; `Duration::ZERO` is separately rejected by
7858        // [`SupervisorError::RestartWindowZero`]),
7859        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
7860        // surrounding [`SupervisorSpec::validate`] gate carves out on the
7861        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
7862        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
7863        // accessor doesn't perform a silent bounds-collapse into `None` on
7864        // the zero-Duration arm — validate rejects zero but the accessor
7865        // must ship the raw slot verbatim so a validate-time gate
7866        // regression surfaces at the emit boundary rather than being
7867        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
7868        // sentinel that pins the accessor doesn't perform a silent
7869        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
7870        // return path).
7871        //
7872        // Peer of the sibling M2
7873        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7874        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
7875        // sibling M3
7876        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7877        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
7878        // substrate-primitive accessor must byte-equal the raw field
7879        // access verbatim across every value in the `Option<Duration>`
7880        // accept-set" discipline extended onto the M2 supervisor-slot
7881        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
7882        // silent detour that re-derived the restart-window from a peer
7883        // axis (an accidental `.max_restarts.into()` collapse that read
7884        // the restart-budget-count as a duration — the two axes serve
7885        // different halves of the `MaxIntensity / Period` restart-
7886        // intensity ratio, and confusing them silently inverts the
7887        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
7888        // "zero means never reset" collapse (the canonical
7889        // `Option<Duration>` → `Duration` collapse footgun the
7890        // [`SupervisorError::RestartWindowZero`] validate arm guards on
7891        // the peer zero-floor axis; a zero period either trips on the
7892        // first failure or never trips depending on operator
7893        // interpretation, neither of which is the author's "never reset"
7894        // intent that `None` expresses structurally), or a per-arm
7895        // variant swap that landed on one consumer without the other.
7896        for restart_window in [
7897            None,
7898            Some(Duration::from_millis(1)),
7899            Some(SUPERVISOR_RESTART_WINDOW_MAX),
7900            Some(Duration::ZERO),
7901            Some(Duration::MAX),
7902        ] {
7903            let s = SupervisorSpec {
7904                restart_window,
7905                ..SupervisorSpec::default()
7906            };
7907            assert_eq!(
7908                s.restart_window(),
7909                restart_window,
7910                "SupervisorSpec::restart_window must return :supervisor \
7911                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
7912                s.restart_window(),
7913            );
7914            assert_eq!(
7915                s.restart_window(),
7916                s.restart_window,
7917                "SupervisorSpec::restart_window accessor and \
7918                 .restart_window field access must byte-equal — the \
7919                 accessor is the substrate-primitive typed dispatch every \
7920                 downstream restart-intensity-denominator consumer must \
7921                 route through",
7922            );
7923        }
7924    }
7925
7926    #[test]
7927    fn validate_restart_window_bracket_arm_routes_through_accessor() {
7928        // Composition pin: [`SupervisorSpec::validate`]'s
7929        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
7930        // zero-floor + integer-millisecond canonical-form + upper-cap
7931        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
7932        // the raw `.restart_window` field access. Structurally: a
7933        // `SupervisorSpec { restart_window: None, .. }` must pass the
7934        // arm gate structurally (the `if let Some(_)` shape returns
7935        // early on the `None` arm — the accessor and the validate gate
7936        // must agree on `None → skip the bracket cascade` so an authored
7937        // `:restart-window ()` structurally routes through the "never
7938        // reset" sentinel path), a `SupervisorSpec { restart_window:
7939        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
7940        // refusal exactly, a `SupervisorSpec { restart_window:
7941        // Some(Duration::from_micros(1500)), .. }` must surface the
7942        // `RestartWindowNotCanonical` refusal exactly (with the offending
7943        // duration carried verbatim from the accessor return), a
7944        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
7945        // + Duration::from_millis(1)), .. }` must surface the
7946        // `RestartWindowExceedsCap` refusal exactly (with the offending
7947        // duration carried verbatim from the accessor return), and a
7948        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
7949        // .. }` (the lower boundary of the accept-set) plus a
7950        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7951        // .. }` (the upper boundary) must pass validate. The six together
7952        // jointly pin the accessor + validate-gate composition: any future
7953        // silent detour that had the accessor return a fresh `None` on any
7954        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
7955        // collapse) would silently absorb the `RestartWindowZero` refusal
7956        // at the accessor boundary and the validate gate would accept a
7957        // struct-literal `SupervisorSpec { restart_window:
7958        // Some(Duration::ZERO), .. }` — the composition pin catches that
7959        // at caixa-core build time.
7960        //
7961        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
7962        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
7963        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
7964        // accessor-composition pin on the per-`:politicas :timeout` axis —
7965        // same "the validate / shape-gate predicate must route through
7966        // the substrate-primitive typed dispatch" discipline extended
7967        // onto the peer M2 supervisor-slot optional-`Duration` axis.
7968        let child = ChildSpec {
7969            caixa: "worker".into(),
7970            versao: "^0.1".into(),
7971            restart: RestartPolicy::Permanent,
7972        };
7973        // None arm — must not surface any :restart-window-shaped refusal;
7974        // the `if let Some(_)` bracket returns early on `None` structurally.
7975        let s = SupervisorSpec {
7976            restart_window: None,
7977            children: vec![child.clone()],
7978            ..SupervisorSpec::default()
7979        };
7980        assert!(
7981            s.validate().is_ok(),
7982            "validate must accept restart_window: None (the never-reset \
7983             sentinel) — the `if let Some(_)` bracket returns early on \
7984             the None arm and the accessor must agree",
7985        );
7986        // Zero-floor arm.
7987        let s = SupervisorSpec {
7988            restart_window: Some(Duration::ZERO),
7989            children: vec![child.clone()],
7990            ..SupervisorSpec::default()
7991        };
7992        assert_eq!(
7993            s.validate().unwrap_err(),
7994            SupervisorError::RestartWindowZero,
7995            "validate must reject restart_window == Some(Duration::ZERO) \
7996             with RestartWindowZero — the accessor and the validate gate \
7997             must route through the same substrate-primitive typed \
7998             dispatch on the zero-floor arm",
7999        );
8000        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
8001        // byte-equal the accessor's return so a future rebrand on the
8002        // accessor lands in the diagnostic without a coordinated rewrite.
8003        let sub_ms = Duration::from_micros(1500);
8004        let s = SupervisorSpec {
8005            restart_window: Some(sub_ms),
8006            children: vec![child.clone()],
8007            ..SupervisorSpec::default()
8008        };
8009        match s.validate().unwrap_err() {
8010            SupervisorError::RestartWindowNotCanonical { window } => {
8011                assert_eq!(
8012                    Some(window),
8013                    s.restart_window(),
8014                    "RestartWindowNotCanonical.window must byte-equal \
8015                     SupervisorSpec::restart_window().unwrap() — the \
8016                     non-canonical-arm refusal reads through the lifted \
8017                     accessor",
8018                );
8019                assert_eq!(
8020                    window, sub_ms,
8021                    "RestartWindowNotCanonical.window must carry the \
8022                     author-declared :supervisor :restart-window value \
8023                     verbatim (got {window:?}, expected {sub_ms:?})",
8024                );
8025            }
8026            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8027        }
8028        // Cap arm — the surfaced `window:` field must byte-equal the
8029        // accessor's return.
8030        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8031        let s = SupervisorSpec {
8032            restart_window: Some(over_cap),
8033            children: vec![child.clone()],
8034            ..SupervisorSpec::default()
8035        };
8036        match s.validate().unwrap_err() {
8037            SupervisorError::RestartWindowExceedsCap { window } => {
8038                assert_eq!(
8039                    Some(window),
8040                    s.restart_window(),
8041                    "RestartWindowExceedsCap.window must byte-equal \
8042                     SupervisorSpec::restart_window().unwrap() — the \
8043                     cap-arm refusal reads through the lifted accessor",
8044                );
8045                assert_eq!(
8046                    window, over_cap,
8047                    "RestartWindowExceedsCap.window must carry the \
8048                     author-declared :supervisor :restart-window value \
8049                     verbatim (got {window:?}, expected {over_cap:?})",
8050                );
8051            }
8052            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
8053        }
8054        // Lower + upper accept-set boundaries.
8055        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
8056            let s = SupervisorSpec {
8057                restart_window: Some(restart_window),
8058                children: vec![child.clone()],
8059                ..SupervisorSpec::default()
8060            };
8061            assert!(
8062                s.validate().is_ok(),
8063                "validate must accept restart_window == Some({restart_window:?}) \
8064                 (an accept-set boundary of \
8065                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
8066            );
8067        }
8068    }
8069
8070    #[test]
8071    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
8072        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
8073        // `Option<Duration>` by copy — `Duration` is `Copy` (so
8074        // `Option<Duration>` is `Copy`) and the accessor must return by
8075        // value, not by reference. Peer of the sibling M2
8076        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
8077        // per-`:limits :wall-clock` axis and the sibling M3
8078        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
8079        // per-`:politicas :timeout` axis, extended onto the peer M2
8080        // supervisor-slot `Option<Duration>` copy-invariant shape — the
8081        // accessor's returned `Option<Duration>` must outlive `&self`
8082        // (multiple calls must return equal values from a dropped-`&self`
8083        // copy, since the returned Option carries no borrow), and calling
8084        // the accessor twice on the same SupervisorSpec must yield the
8085        // same `Option<Duration>` verbatim (idempotent, no side effects
8086        // on `&self`).
8087        //
8088        // Pins against a future silent detour that returned
8089        // `Option<&Duration>` (which would type-check but silently break
8090        // every downstream caller — the future wasm-operator's
8091        // per-supervisor restart-intensity counter consumes `Duration` by
8092        // value and `&Duration` would fold to a detached copy at the call
8093        // site), an accidental `Option::as_ref()` projection
8094        // (`self.restart_window.as_ref()` would also type-check but
8095        // return `Option<&Duration>`), or a one-arm-only accessor that
8096        // reads `Some(*w)` in the Some arm but reads a fresh
8097        // `Default::default()` (which would collapse to `Duration::ZERO`,
8098        // not `None`) in the None arm — a footgun the
8099        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
8100        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
8101        // requires `Period > 0` and `None` structurally expresses "never
8102        // reset" instead.
8103        for restart_window in [
8104            None,
8105            Some(Duration::from_millis(1)),
8106            Some(Duration::from_secs(60)),
8107            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8108        ] {
8109            let s = SupervisorSpec {
8110                restart_window,
8111                ..SupervisorSpec::default()
8112            };
8113            let first = s.restart_window();
8114            let second = s.restart_window();
8115            assert_eq!(
8116                first, second,
8117                "SupervisorSpec::restart_window must be idempotent — two \
8118                 successive calls on the same &self must return the \
8119                 same Option<Duration>",
8120            );
8121            assert_eq!(
8122                first, restart_window,
8123                "SupervisorSpec::restart_window must return :supervisor \
8124                 :restart-window verbatim by copy — got {first:?}, \
8125                 expected {restart_window:?}",
8126            );
8127        }
8128    }
8129
8130    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
8131    //
8132    // The [`SupervisorSpec::children`] accessor lift is the seed of the
8133    // slice-return (`&[T]`) accessor discipline on the substrate — the four
8134    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
8135    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
8136    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
8137    // access at the time of this seed, and inherit this pin family's
8138    // discipline as future compounding runs migrate their consumers. The
8139    // three pins below cover (1) the accessor's byte-equal projection
8140    // against the raw field access across the empty / singleton / cohort
8141    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
8142    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
8143    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
8144    // consumer routing through the accessor on both arms, and (3) the
8145    // per-child validate loop's traversal reading the same slice-view the
8146    // accessor projects. Peer of the sibling M2
8147    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8148    // two-consumer coherence pin on the per-`:supervisor`
8149    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
8150    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
8151
8152    #[test]
8153    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
8154        // The canonical per-`:supervisor` static-child-list scalar-shape
8155        // pin: [`SupervisorSpec::children`] must return the `:supervisor
8156        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
8157        // slice-view over the same backing buffer the raw
8158        // `self.children.as_slice()` field access borrows from, byte-
8159        // equal across every representative fixture in the accept-set —
8160        // the empty slice (the `SimpleOneForOne`-arm sentinel),
8161        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
8162        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
8163        // with the peer three restart-policy variants in play).
8164        //
8165        // Pins against a future silent detour that returned
8166        // `&Vec<ChildSpec>` (which would type-check but leak the
8167        // storage-side `Vec`'s grow/push/reserve surface no consumer of
8168        // the typed view reaches for), a fresh-allocated
8169        // `Vec<ChildSpec>` copy (which would type-check via a coercion
8170        // but silently break every downstream caller that relied on the
8171        // slice sharing the backing buffer's identity), or an
8172        // out-of-order or length-drifted projection (which would silently
8173        // split the per-child validate loop's traversal input from the
8174        // paired partition-dispatch `.is_empty()` probe's input).
8175        //
8176        // Peer of the sibling
8177        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8178        // (eafb619) `Copy`-composite-enum byte-equal pin on the
8179        // per-`:supervisor` sibling-restart-strategy axis, extended onto
8180        // the per-`:supervisor` static-child-list `Vec`-carry axis.
8181        let fixtures: Vec<Vec<ChildSpec>> = vec![
8182            Vec::new(),
8183            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8184            vec![
8185                child("worker", "^0.1", RestartPolicy::Permanent),
8186                child("cache-server", "^0.1", RestartPolicy::Transient),
8187            ],
8188            vec![
8189                child("worker", "^0.1", RestartPolicy::Permanent),
8190                child("cache-server", "^0.1", RestartPolicy::Transient),
8191                child("scratch-job", "^0.1", RestartPolicy::Temporary),
8192            ],
8193        ];
8194        for children in fixtures {
8195            let s = SupervisorSpec {
8196                children: children.clone(),
8197                ..SupervisorSpec::default()
8198            };
8199            assert_eq!(
8200                s.children(),
8201                children.as_slice(),
8202                "SupervisorSpec::children must return :supervisor \
8203                 :children verbatim (got {:?}, expected {:?})",
8204                s.children(),
8205                children.as_slice(),
8206            );
8207            assert_eq!(
8208                s.children(),
8209                s.children.as_slice(),
8210                "SupervisorSpec::children accessor and \
8211                 .children.as_slice() field access must byte-equal — \
8212                 the accessor is the substrate-primitive typed \
8213                 dispatch every downstream static-child-list consumer \
8214                 must route through",
8215            );
8216            assert_eq!(
8217                s.children().len(),
8218                s.children.len(),
8219                "SupervisorSpec::children().len() must byte-equal \
8220                 self.children.len() — a length-drift would silently \
8221                 split the paired partition-dispatch `.is_empty()` \
8222                 probe input from the per-child validate loop's \
8223                 traversal input",
8224            );
8225        }
8226    }
8227
8228    #[test]
8229    fn validate_reads_through_lifted_children_accessor() {
8230        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
8231        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
8232        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
8233        // when the accessor projects a non-empty slice under a
8234        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
8235        // `self.children().is_empty()` refusal probe (which must trip
8236        // [`SupervisorError::NoChildren`] when the accessor projects the
8237        // empty slice under any peer estrategia), and the per-child
8238        // validate loop's `for child in self.children()` traversal
8239        // (which must reach every entry in the same order the accessor
8240        // projects) must all key off the lifted accessor, so any future
8241        // rebrand on the typed slot's reader shape lands at exactly one
8242        // place. Pins the three-site coherence by exercising each
8243        // production consumer end-to-end: (1) the
8244        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
8245        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
8246        // refusal under the empty slice + non-`SimpleOneForOne`
8247        // estrategia across every peer variant, and (3) the per-child
8248        // duplicate-detection surface fires on the second entry of a
8249        // two-child cohort that shares a `:caixa` name (which requires
8250        // the loop to reach both entries — a first-entry-only projection
8251        // would silently pass since the dedup HashSet has room for the
8252        // first insert).
8253        //
8254        // Peer of the sibling M2
8255        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8256        // two-consumer coherence pin on the per-`:supervisor`
8257        // sibling-restart-strategy axis, extended onto the
8258        // per-`:supervisor` static-child-list `Vec`-carry axis.
8259
8260        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
8261        // `SimpleOneForOne` estrategia must trip
8262        // `SimpleOneForOneWithStaticChildren`.
8263        let s = SupervisorSpec {
8264            estrategia: RestartStrategy::SimpleOneForOne,
8265            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8266            ..SupervisorSpec::default()
8267        };
8268        assert_eq!(
8269            s.validate().unwrap_err(),
8270            SupervisorError::SimpleOneForOneWithStaticChildren,
8271            "SimpleOneForOne + non-empty children must trip \
8272             SimpleOneForOneWithStaticChildren — the accessor projects \
8273             a non-empty slice, and the SimpleOneForOne-arm refusal \
8274             probe reads through the lifted accessor",
8275        );
8276        assert!(
8277            !s.children().is_empty(),
8278            "the SimpleOneForOne-arm refusal input must be a non-empty \
8279             slice per the accessor's projection",
8280        );
8281
8282        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
8283        // under any peer estrategia must trip `NoChildren`.
8284        for estrategia in [
8285            RestartStrategy::OneForOne,
8286            RestartStrategy::OneForAll,
8287            RestartStrategy::RestForOne,
8288        ] {
8289            let s = SupervisorSpec {
8290                estrategia,
8291                children: Vec::new(),
8292                ..SupervisorSpec::default()
8293            };
8294            match s.validate().unwrap_err() {
8295                SupervisorError::NoChildren { estrategia: e } => {
8296                    assert_eq!(
8297                        e, estrategia,
8298                        "NoChildren.estrategia must carry the author-\
8299                         declared :supervisor :estrategia variant \
8300                         verbatim (got {e:?}, expected {estrategia:?})",
8301                    );
8302                }
8303                other => panic!(
8304                    "expected NoChildren, got {other:?} for \
8305                     estrategia={estrategia:?}"
8306                ),
8307            }
8308            assert!(
8309                s.children().is_empty(),
8310                "the non-SimpleOneForOne-arm refusal input must be the \
8311                 empty slice per the accessor's projection",
8312            );
8313        }
8314
8315        // (3) Per-child validate loop: a two-child cohort that shares a
8316        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
8317        // reach both entries through the accessor.
8318        let s = SupervisorSpec {
8319            estrategia: RestartStrategy::OneForOne,
8320            children: vec![
8321                child("worker", "^0.1", RestartPolicy::Permanent),
8322                child("worker", "^0.2", RestartPolicy::Transient),
8323            ],
8324            ..SupervisorSpec::default()
8325        };
8326        match s.validate().unwrap_err() {
8327            SupervisorError::DuplicateChildCaixa { caixa } => {
8328                assert_eq!(
8329                    caixa, "worker",
8330                    "DuplicateChildCaixa.caixa must carry the shared \
8331                     child `:caixa` name verbatim",
8332                );
8333            }
8334            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
8335        }
8336        assert_eq!(
8337            s.children().len(),
8338            2,
8339            "the per-child validate loop's traversal input must be a \
8340             two-element slice per the accessor's projection",
8341        );
8342    }
8343
8344    // Shared helper for the M2 per-`:children` per-slot-gate ≡
8345    // `validate` equivalence pins: builds an `OneForOne`-estrategia
8346    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
8347    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
8348    // bracket all pass cleanly so the sole failing surface is the
8349    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
8350    // pins the two-altitude equivalence on the paired probe.
8351    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
8352        let s = SupervisorSpec {
8353            estrategia: RestartStrategy::OneForOne,
8354            children,
8355            ..SupervisorSpec::default()
8356        };
8357        let via_gate = s.validate_children().unwrap_err();
8358        let via_validate = s.validate().unwrap_err();
8359        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
8360        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
8361        assert_eq!(
8362            via_gate, via_validate,
8363            "per-slot gate ≡ validate() must discriminate the same \
8364             refusal shape",
8365        );
8366    }
8367
8368    #[test]
8369    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
8370        // Fail-before-pass-after equivalence pin on the M2
8371        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
8372        // convergence — sibling of the M3 mesh-slot
8373        // `validate_membros_*` / `validate_contratos_*` /
8374        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
8375        // peer per-entry axes. Sweeps four of the five refusal shapes
8376        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
8377        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
8378        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
8379        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
8380        // duplicate-`:caixa` fan-out. Companion pin
8381        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
8382        // covers `ChildVersaoInvalid` (whose parser-owned reason string
8383        // needs pattern-matching, not equality) and the clean-pass
8384        // canonical fixture; together the two pins guarantee the
8385        // per-slot gate and `validate` discriminate the same set on
8386        // every per-child-covered input.
8387        assert_validate_children_matches_gate(
8388            vec![child("", "^0.1", RestartPolicy::Permanent)],
8389            &SupervisorError::EmptyChildName,
8390        );
8391        assert_validate_children_matches_gate(
8392            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
8393            &SupervisorError::ChildCaixaInvalid {
8394                caixa: "Worker".into(),
8395                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
8396            },
8397        );
8398        assert_validate_children_matches_gate(
8399            vec![child("worker", "", RestartPolicy::Permanent)],
8400            &SupervisorError::EmptyChildVersion {
8401                caixa: "worker".into(),
8402            },
8403        );
8404        assert_validate_children_matches_gate(
8405            vec![
8406                child("worker", "^0.1", RestartPolicy::Permanent),
8407                child("worker", "^0.2", RestartPolicy::Transient),
8408            ],
8409            &SupervisorError::DuplicateChildCaixa {
8410                caixa: "worker".into(),
8411            },
8412        );
8413    }
8414
8415    #[test]
8416    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
8417        // Second half of the two-altitude equivalence pin — covers the
8418        // one refusal shape whose reason string is parser-owned
8419        // (`ChildVersaoInvalid`, whose reason comes from the shared
8420        // [`crate::version::parse_requirement`] impl and may drift) and
8421        // the clean-pass canonical fixture. Sibling pin
8422        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
8423        // covers the four equality-comparable refusal shapes.
8424        let s_bad_versao = SupervisorSpec {
8425            estrategia: RestartStrategy::OneForOne,
8426            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
8427            ..SupervisorSpec::default()
8428        };
8429        let via_gate = s_bad_versao.validate_children().unwrap_err();
8430        let via_validate = s_bad_versao.validate().unwrap_err();
8431        match (&via_gate, &via_validate) {
8432            (
8433                SupervisorError::ChildVersaoInvalid {
8434                    caixa: cg,
8435                    versao: vg,
8436                    ..
8437                },
8438                SupervisorError::ChildVersaoInvalid {
8439                    caixa: cv,
8440                    versao: vv,
8441                    ..
8442                },
8443            ) => {
8444                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
8445                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
8446                assert_eq!(cv, "worker", "validate() :caixa carrier");
8447                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
8448            }
8449            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
8450        }
8451        assert_eq!(
8452            via_gate, via_validate,
8453            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
8454        );
8455
8456        let s_ok = SupervisorSpec {
8457            estrategia: RestartStrategy::OneForOne,
8458            children: vec![
8459                child("worker-a", "^0.1", RestartPolicy::Permanent),
8460                child("worker-b", "~0.2.3", RestartPolicy::Transient),
8461                child("collector", "*", RestartPolicy::Temporary),
8462            ],
8463            ..SupervisorSpec::default()
8464        };
8465        s_ok.validate_children()
8466            .expect("per-slot gate must accept the clean-pass fixture");
8467        s_ok.validate()
8468            .expect("validate() must accept the clean-pass fixture");
8469    }
8470
8471    #[test]
8472    fn validate_children_is_self_contained_on_children_slot() {
8473        // Self-containment pin: [`SupervisorSpec::validate_children`]
8474        // resolves the per-child cascade against `&self` alone, without
8475        // depending on the peer `:estrategia`/`:max-restarts`/
8476        // `:restart-window` gates having run first — same posture the M3
8477        // peer per-slot gates carry (`validate_membros`,
8478        // `validate_contratos`, `validate_entrada`, `validate_placement`,
8479        // routing through their own oracles rather than borrowing state
8480        // threaded down from `validate`). A future consumer that reaches
8481        // the per-slot gate directly on a spec whose peer slots would
8482        // fail `validate` still surfaces the per-child refusal, not the
8483        // peer refusal.
8484        //
8485        // Construct a spec whose `:max-restarts` is `0` (which would
8486        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
8487        // the partition-dispatch) and whose `:children` carries a
8488        // `DuplicateChildCaixa` shape: the per-slot gate called directly
8489        // must surface `DuplicateChildCaixa`, proving it does not depend
8490        // on the peer `:max-restarts` gate running first.
8491        let s = SupervisorSpec {
8492            estrategia: RestartStrategy::OneForOne,
8493            max_restarts: 0,
8494            restart_window: Some(Duration::from_secs(60)),
8495            children: vec![
8496                child("worker", "^0.1", RestartPolicy::Permanent),
8497                child("worker", "^0.2", RestartPolicy::Transient),
8498            ],
8499        };
8500        assert_eq!(
8501            s.validate_children().unwrap_err(),
8502            SupervisorError::DuplicateChildCaixa {
8503                caixa: "worker".into(),
8504            },
8505            "per-slot gate must resolve per-child refusal directly against \
8506             `&self` — a dependency on the peer `:max-restarts` gate \
8507             running first would surface ZeroMaxRestarts here instead",
8508        );
8509        // The peer gate is still the surface `validate` reaches — pin
8510        // the ordering to establish that `validate_children` truly runs
8511        // last in `validate`'s dispatch, so a direct call bypasses the
8512        // peer gates on any spec whose per-child cascade would fail.
8513        assert_eq!(
8514            s.validate().unwrap_err(),
8515            SupervisorError::ZeroMaxRestarts,
8516            "validate() must surface the peer `:max-restarts` gate before \
8517             reaching the per-child cascade — this pins the dispatch \
8518             ordering the per-slot gate's self-containment complements",
8519        );
8520    }
8521
8522    #[test]
8523    fn child_spec_restart_accessor_is_const_fn() {
8524        // The [`ChildSpec::restart`] per-`:children` restart-decision-
8525        // policy `Copy`-return scalar accessor is declared
8526        // `#[must_use] pub const fn` — matching the sibling M2
8527        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
8528        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
8529        // both converted in this commit), the sibling M2
8530        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
8531        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
8532        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
8533        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
8534        // `Copy`-return `pub const fn` scalar accessors on the sibling
8535        // M3 surface. Pin the `const`-eval posture here so a future
8536        // accidental downgrade to non-`const` (an added runtime helper
8537        // reachable only from a non-`const` context, an
8538        // `Option<RestartPolicy>`-shape migration on the per-child
8539        // restart-decision axis once heterogeneous per-cluster
8540        // restart-policy overlays land that would silently drop the
8541        // `const` qualifier, a manual hand-rolled shadow) trips at
8542        // caixa-core build time rather than surfacing as a downstream
8543        // `const`-context regression far from the declaration.
8544        //
8545        // Same shape as the sibling M3
8546        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
8547        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
8548        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
8549        // accessor axis — the load-bearing witness lives in the
8550        // module-scope `const fn` wrapper `restart_via_const_fn` below:
8551        // a body that calls [`ChildSpec::restart`] under a `const fn`
8552        // signature is well-formed only when the callee is itself
8553        // `const fn`, so any future accidental downgrade of
8554        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
8555        // build time (const-eval E0015 `cannot call non-const method`),
8556        // strictly stronger than a runtime `assert!(CONST)` and
8557        // side-stepping the destructor-in-const restriction that
8558        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
8559        // items on `ChildSpec`'s `String` carriers.
8560        //
8561        // The runtime body sweeps every closed-set [`RestartPolicy`]
8562        // arm and asserts the wrapped and direct dispatches agree.
8563        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
8564            c.restart()
8565        }
8566        for restart in [
8567            RestartPolicy::Permanent,
8568            RestartPolicy::Transient,
8569            RestartPolicy::Temporary,
8570        ] {
8571            let c = ChildSpec {
8572                caixa: "worker".into(),
8573                versao: "^0.1".into(),
8574                restart,
8575            };
8576            assert_eq!(
8577                restart_via_const_fn(&c),
8578                c.restart(),
8579                "const-fn-wrapped and direct dispatch on \
8580                 ChildSpec::restart must agree for {restart:?}",
8581            );
8582            assert_eq!(
8583                c.restart(),
8584                restart,
8585                "ChildSpec::restart must return the storage-side \
8586                 RestartPolicy verbatim for {restart:?} (a violation \
8587                 means the accessor stopped being a raw field-return \
8588                 copy)",
8589            );
8590        }
8591    }
8592
8593    #[test]
8594    fn supervisor_spec_estrategia_accessor_is_const_fn() {
8595        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
8596        // sibling-restart-strategy `Copy`-return scalar accessor is
8597        // declared `#[must_use] pub const fn` — matching the sibling M2
8598        // per-`:children` [`ChildSpec::restart`] (pinned by
8599        // [`child_spec_restart_accessor_is_const_fn`] above, both
8600        // converted in this commit), the sibling M2 per-`:supervisor`
8601        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
8602        // accessor already `pub const fn`, and mirroring the peer M3
8603        // mesh-slot per-`:placement`
8604        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
8605        // `pub const fn` scalar accessor whose method-name discipline
8606        // the [`SupervisorSpec::estrategia`] method was authored to
8607        // match. Pin the `const`-eval posture here so a future
8608        // accidental downgrade to non-`const` (an added runtime helper
8609        // reachable only from a non-`const` context, an
8610        // `Option<RestartStrategy>`-shape migration once the substrate
8611        // grows per-cluster strategy overlays that would silently drop
8612        // the `const` qualifier, a manual hand-rolled shadow) trips at
8613        // caixa-core build time rather than surfacing as a downstream
8614        // `const`-context regression far from the declaration.
8615        //
8616        // Same shape as the sibling
8617        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
8618        // load-bearing witness lives in the module-scope `const fn`
8619        // wrapper `estrategia_via_const_fn` below: a body that calls
8620        // [`SupervisorSpec::estrategia`] under a `const fn` signature
8621        // is well-formed only when the callee is itself `const fn`,
8622        // side-stepping the destructor-in-const restriction that would
8623        // otherwise block a direct
8624        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
8625        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
8626        // carriers.
8627        //
8628        // The runtime body sweeps every closed-set [`RestartStrategy`]
8629        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
8630        // direct dispatches agree.
8631        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
8632            s.estrategia()
8633        }
8634        for &estrategia in RestartStrategy::ALL {
8635            let s = SupervisorSpec {
8636                estrategia,
8637                max_restarts: 5,
8638                restart_window: Some(Duration::from_secs(60)),
8639                children: Vec::new(),
8640            };
8641            assert_eq!(
8642                estrategia_via_const_fn(&s),
8643                s.estrategia(),
8644                "const-fn-wrapped and direct dispatch on \
8645                 SupervisorSpec::estrategia must agree for {estrategia:?}",
8646            );
8647            assert_eq!(
8648                s.estrategia(),
8649                estrategia,
8650                "SupervisorSpec::estrategia must return the storage-side \
8651                 RestartStrategy verbatim for {estrategia:?} (a violation \
8652                 means the accessor stopped being a raw field-return \
8653                 copy)",
8654            );
8655        }
8656    }
8657
8658    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
8659    // macro definition (see the paired doc-block above the macro
8660    // definition) — every generated `<ctor>(caixa: &str) -> Self`
8661    // constructor folds the uniform `Self::<Variant> { caixa:
8662    // caixa.to_string() }` one-field struct-literal onto one substrate
8663    // primitive. The three per-variant equivalence pins below
8664    // (fail-before-pass-after by construction — a byte-mismatched macro
8665    // arm would trip its equivalence pin first) lock each generated
8666    // constructor to its struct-literal peer under `PartialEq`, so
8667    // every wire-up in [`SupervisorSpec::validate_children`] and
8668    // [`validate_no_self_supervision`] on that variant produces a
8669    // byte-equal `SupervisorError` to the pre-lift open-coded
8670    // struct-literal. The cross-axis pin that follows (non-default
8671    // caixa name) routes the sole constructor input axis through
8672    // `.to_string()`, so the fold does not silently collapse onto a
8673    // fixed name.
8674    //
8675    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
8676    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
8677    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
8678    // `missing_entry_ctor_matches_struct_literal_wrap` /
8679    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
8680    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
8681    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
8682    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
8683    // on the six sibling ctor families the recent trajectory closed
8684    // on the peer `LayoutError` / `AplicacaoError` envelopes.
8685
8686    #[test]
8687    fn empty_child_version_ctor_matches_struct_literal_wrap() {
8688        assert_eq!(
8689            SupervisorError::empty_child_version("worker"),
8690            SupervisorError::EmptyChildVersion {
8691                caixa: "worker".to_string(),
8692            },
8693            "generated empty_child_version ctor must produce byte-equal \
8694             SupervisorError to the open-coded struct-literal wrap on the \
8695             same &str fixture",
8696        );
8697    }
8698
8699    #[test]
8700    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
8701        assert_eq!(
8702            SupervisorError::duplicate_child_caixa("worker"),
8703            SupervisorError::DuplicateChildCaixa {
8704                caixa: "worker".to_string(),
8705            },
8706            "generated duplicate_child_caixa ctor must produce byte-equal \
8707             SupervisorError to the open-coded struct-literal wrap on the \
8708             same &str fixture",
8709        );
8710    }
8711
8712    #[test]
8713    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
8714        assert_eq!(
8715            SupervisorError::child_supervises_self("orquestra"),
8716            SupervisorError::ChildSupervisesSelf {
8717                caixa: "orquestra".to_string(),
8718            },
8719            "generated child_supervises_self ctor must produce byte-equal \
8720             SupervisorError to the open-coded struct-literal wrap on the \
8721             same &str fixture",
8722        );
8723    }
8724
8725    // Per-variant equivalence pins for the two lifted
8726    // [`SupervisorError::child_caixa_invalid`] /
8727    // [`SupervisorError::child_versao_invalid`] inherent constructors
8728    // (fail-before-pass-after by construction — a byte-mismatched ctor body
8729    // would trip its equivalence pin first). Each pins the ctor output to
8730    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
8731    // in [`SupervisorSpec::validate_children`] on the two variants
8732    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
8733    // struct-literal on the same scalar fixtures. Peers of the sibling
8734    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
8735    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
8736    // the peer `AplicacaoError` envelope's
8737    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
8738
8739    #[test]
8740    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
8741        let caixa = "Worker";
8742        let reason = "sample reason text";
8743        assert_eq!(
8744            SupervisorError::child_caixa_invalid(caixa, reason),
8745            SupervisorError::ChildCaixaInvalid {
8746                caixa: caixa.to_string(),
8747                reason: reason.to_string(),
8748            },
8749            "lifted child_caixa_invalid ctor must produce byte-equal \
8750             SupervisorError to the open-coded struct-literal wrap on the \
8751             same (&str, reason) fixture",
8752        );
8753    }
8754
8755    #[test]
8756    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
8757        let caixa = "worker";
8758        let versao = "not-a-req";
8759        let reason = "sample reason text";
8760        assert_eq!(
8761            SupervisorError::child_versao_invalid(caixa, versao, reason),
8762            SupervisorError::ChildVersaoInvalid {
8763                caixa: caixa.to_string(),
8764                versao: versao.to_string(),
8765                reason: reason.to_string(),
8766            },
8767            "lifted child_versao_invalid ctor must produce byte-equal \
8768             SupervisorError to the open-coded struct-literal wrap on the \
8769             same (&str, &str, reason) fixture",
8770        );
8771    }
8772
8773    #[test]
8774    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
8775        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
8776        // against a `&str`-literal vs. `format!(…)` reason input to pin
8777        // both constructors accept the `impl Into<String>` bound
8778        // uniformly, so neither wire-up site drifts under a per-arm
8779        // wrapper transformation on the caller-side `reason` axis. Peer
8780        // of the sibling
8781        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
8782        // sweep on the peer `AplicacaoError` envelope.
8783        let via_literal = "literal reason text";
8784        let via_format = format!("{} reason text", "literal");
8785        assert_eq!(
8786            SupervisorError::child_caixa_invalid("Worker", via_literal),
8787            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
8788        );
8789        assert_eq!(
8790            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
8791            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
8792        );
8793    }
8794
8795    #[test]
8796    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
8797        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
8798        // &str`) through a non-default fixture name against every
8799        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
8800        // so any wrapper-side lowercase / trim / truncate / re-order on
8801        // the `caixa.to_string()` sole-field construction surfaces
8802        // here rather than at a downstream diagnostic-shape mismatch.
8803        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
8804        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
8805        // through_to_string` / `contrato_target_ctors_route_edge_
8806        // triple_through_verbatim` / `contrato_empty_pair_ctors_
8807        // route_edge_pair_through_verbatim` cross-axis routing pins on
8808        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
8809        // here onto the `SupervisorError` `{ caixa: String }` envelope
8810        // so every substrate-primitive ctor family in caixa-core
8811        // guarantees the sole-field construction routes the caller's
8812        // `&str` through `.to_string()` verbatim.
8813        let name = "cache-v2";
8814        assert_eq!(
8815            SupervisorError::empty_child_version(name),
8816            SupervisorError::EmptyChildVersion {
8817                caixa: name.to_string(),
8818            },
8819        );
8820        assert_eq!(
8821            SupervisorError::duplicate_child_caixa(name),
8822            SupervisorError::DuplicateChildCaixa {
8823                caixa: name.to_string(),
8824            },
8825        );
8826        assert_eq!(
8827            SupervisorError::child_supervises_self(name),
8828            SupervisorError::ChildSupervisesSelf {
8829                caixa: name.to_string(),
8830            },
8831        );
8832    }
8833
8834    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
8835    //
8836    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
8837    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
8838    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
8839    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
8840    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
8841    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
8842    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
8843    // / silent constant-substitution on any one variant surfaces here rather
8844    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
8845    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
8846    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
8847    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
8848    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
8849    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
8850    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
8851    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
8852    #[test]
8853    fn no_children_ctor_matches_struct_literal_wrap() {
8854        let estrategia = RestartStrategy::OneForAll;
8855        assert_eq!(
8856            SupervisorError::no_children(estrategia),
8857            SupervisorError::NoChildren { estrategia },
8858            "generated no_children ctor must produce byte-equal \
8859             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
8860             on the same `Copy`-`RestartStrategy` fixture",
8861        );
8862    }
8863
8864    #[test]
8865    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
8866        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8867        assert_eq!(
8868            SupervisorError::max_restarts_exceeds_cap(max_restarts),
8869            SupervisorError::MaxRestartsExceedsCap { max_restarts },
8870            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
8871             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
8872             struct-literal wrap on the same `Copy`-`u32` fixture",
8873        );
8874    }
8875
8876    #[test]
8877    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
8878        let window = Duration::from_micros(1_500);
8879        assert_eq!(
8880            SupervisorError::restart_window_not_canonical(window),
8881            SupervisorError::RestartWindowNotCanonical { window },
8882            "generated restart_window_not_canonical ctor must produce \
8883             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
8884             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
8885        );
8886    }
8887
8888    #[test]
8889    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
8890        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8891        assert_eq!(
8892            SupervisorError::restart_window_exceeds_cap(window),
8893            SupervisorError::RestartWindowExceedsCap { window },
8894            "generated restart_window_exceeds_cap ctor must produce \
8895             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
8896             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
8897        );
8898    }
8899
8900    #[test]
8901    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
8902        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
8903        // constructor input axis through a non-default `Copy` fixture against
8904        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
8905        // side silent `.into()` / silent constant-substitution / silent field
8906        // re-name away from the canonical `estrategia | max_restarts | window`
8907        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
8908        // axis silently rerouted through some other `Copy` coercion, surfaces
8909        // here rather than at a downstream per-`:supervisor` diagnostic-shape
8910        // drift. Peer of the sibling
8911        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
8912        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
8913        // envelope's per-`:politicas` per-axis ctor family, extended here onto
8914        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
8915        // variant family folded onto a substrate primitive.
8916        //
8917        // Fixtures picked out of each variant's accept-set boundary rather
8918        // than the default value so a silent constant-substitution to a per-
8919        // variant sentinel surfaces here on the structural-equality assertion.
8920        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
8921        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
8922        // isn't the `SimpleOneForOne` arm the sibling
8923        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
8924        // `max_restarts` fixture picks an above-cap magnitude the cap arm
8925        // rejects; the two `Duration` fixtures pick the sub-millisecond and
8926        // above-cap ends of the `:restart-window` canonical-form + cap
8927        // bracket respectively.
8928        let estrategia = RestartStrategy::RestForOne;
8929        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
8930        let sub_ms = Duration::from_micros(1_500);
8931        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
8932        assert_eq!(
8933            SupervisorError::no_children(estrategia),
8934            SupervisorError::NoChildren { estrategia },
8935        );
8936        assert_eq!(
8937            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
8938            SupervisorError::MaxRestartsExceedsCap {
8939                max_restarts: above_cap_restarts,
8940            },
8941        );
8942        assert_eq!(
8943            SupervisorError::restart_window_not_canonical(sub_ms),
8944            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
8945        );
8946        assert_eq!(
8947            SupervisorError::restart_window_exceeds_cap(above_hour),
8948            SupervisorError::RestartWindowExceedsCap { window: above_hour },
8949        );
8950    }
8951
8952    #[test]
8953    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
8954        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
8955        // generated ctor `const fn` so a caller can pin a `SupervisorError`
8956        // at compile time — the same zero-runtime-work property the pre-lift
8957        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
8958        // its `Copy`-pass-through construction path (no `.to_string()` /
8959        // `.into()` allocation, no branching). If any future edit silently
8960        // drops the `const` qualifier from the macro body the per-arm `const`
8961        // bindings below fail to compile, which surfaces the regression at
8962        // the substrate-primitive definition rather than at some downstream
8963        // consumer that had come to rely on the `const`-constructibility.
8964        // Peer of the sibling
8965        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
8966        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
8967        // per-`:politicas` per-axis ctor family.
8968        const NO_CHILDREN: SupervisorError =
8969            SupervisorError::no_children(RestartStrategy::OneForAll);
8970        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
8971        const WINDOW_NC: SupervisorError =
8972            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
8973        const WINDOW_CAP: SupervisorError =
8974            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
8975        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
8976        assert!(matches!(
8977            MAX_RESTARTS_CAP,
8978            SupervisorError::MaxRestartsExceedsCap { .. }
8979        ));
8980        assert!(matches!(
8981            WINDOW_NC,
8982            SupervisorError::RestartWindowNotCanonical { .. }
8983        ));
8984        assert!(matches!(
8985            WINDOW_CAP,
8986            SupervisorError::RestartWindowExceedsCap { .. }
8987        ));
8988    }
8989}