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/// Per-child restart policy.
284///
285/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
286#[derive(
287    Serialize,
288    Deserialize,
289    Debug,
290    Clone,
291    Copy,
292    PartialEq,
293    Eq,
294    Hash,
295    gen_platform::TypedDispatcher,
296    gen_platform::Discriminant,
297    gen_platform::IsVariant,
298    gen_platform::FromStrKind,
299)]
300pub enum RestartPolicy {
301    /// Always restart the child, regardless of how it died. Used for
302    /// long-running services that must always be up.
303    Permanent,
304    /// Never restart. Used for one-shot work whose completion is
305    /// itself the success signal (`oneShot` triggers map here).
306    Temporary,
307    /// Restart only when the child died *abnormally* (non-zero exit
308    /// or unhandled exception). A clean exit completes the child.
309    Transient,
310}
311
312impl Default for RestartPolicy {
313    fn default() -> Self {
314        // Route the [`Default for RestartPolicy`] impl's return arm through
315        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
316        // `pub const` rather than a raw `Self::Permanent` arm — one source
317        // of truth for the Erlang/OTP-canonical `permanent` worker-child
318        // default across the two production consumers that currently
319        // dispatch on it (this impl at the [`RestartPolicy::default`] call
320        // and the serde-side `#[serde(default)]` on
321        // [`ChildSpec::restart`] that resolves an author-omitted
322        // `:children :restart` slot through `RestartPolicy::default()`).
323        // Peer of the sibling per-`:supervisor` axis
324        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
325        // route (95ffacc) — the two impls now share one substrate-primitive
326        // lift discipline, so any future coherent rebrand of the OTP-shape
327        // supervisor+child default set migrates through typed constants in
328        // lockstep instead of splitting a lifted supervisor half against
329        // an open-coded child half. Pinned by
330        // `restart_policy_default_routes_through_lifted_default` +
331        // `child_spec_serde_default_restart_routes_through_lifted_default`
332        // in the tests module.
333        SUPERVISOR_CHILD_RESTART_DEFAULT
334    }
335}
336
337impl RestartPolicy {
338    /// Exhaustive iteration surface for every consumer that walks the
339    /// closed three-arm [`RestartPolicy`] discriminator set (the future
340    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
341    /// per-child admission-webhook rejection body naming the accepted-
342    /// `:restart` list, a future `feira supervisor --restart …` CLI
343    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
344    /// over the slice, the future `feira app graph` per-child restart
345    /// column, any future round-trip fuzz harness that sweeps every
346    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
347    /// theory
348    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
349    /// might reach for once the three canonical OTP restart policies
350    /// stop covering the substrate's discovered load-shape) extends
351    /// this slice as one edit and every consumer picks up the new entry
352    /// by construction; the compiler-checked exhaustiveness on the
353    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
354    /// is the build-time guarantee that no arm forgets to grow.
355    ///
356    /// Peer of the sibling closed-set typed enums'
357    /// [`RestartStrategy::ALL`] (4eec29c) /
358    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
359    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
360    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
361    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
362    /// surfaces — the sixth (and the third and final M2 OTP-shape)
363    /// closed-set typed enum on the caixa surface to converge onto the
364    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
365    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
366    /// sibling-restart-strategy axis; this closes the per-child
367    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
368    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
369
370    /// Canonical PascalCase discriminator scalar this variant serializes
371    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
372    /// arms return the paired
373    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
374    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
375    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
376    /// constants so every substrate consumer that dispatches on the
377    /// per-child restart-decision policy (the future wasm-operator's
378    /// per-child post-exit restart-decision branch, the future M4
379    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
380    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
381    /// reconciliation scheduler's per-child-policy fan-out) reads the
382    /// same byte-string the `Serialize` derive emits — the pin test in
383    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
384    /// asserts the two paths agree, peer of the M2
385    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
386    /// sibling-restart-strategy axis and the M3
387    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
388    /// per-Aplicacao distribution-strategy axis — the third of three
389    /// OTP-shaped closed-enum discriminator axes on the caixa typed
390    /// surface to converge onto the same three-path-convergence
391    /// (`Serialize` derive → `as_str` helper → lifted constant)
392    /// drift-detection posture.
393    #[must_use]
394    pub const fn as_str(self) -> &'static str {
395        match self {
396            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
397            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
398            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
399        }
400    }
401
402    /// Substrate-canonical reverse projection on the `:children :restart`
403    /// closed-set axis — parses the `PascalCase` discriminator scalar
404    /// back to the typed variant, or `None` when `s` is outside the
405    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
406    /// the same lifted
407    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
408    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
409    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
410    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
411    /// of the round-trip migrate through one caixa-core edit on any
412    /// future arm addition.
413    ///
414    /// Prior to this lift the substrate carried only the forward
415    /// `Self → &str` projection on the OTP per-child restart-policy
416    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
417    /// impl routed through it, the `Serialize` derive that emits the
418    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
419    /// plus the kebab-case dispatcher-catalog identity via
420    /// [`Self::discriminant`] — every non-serde consumer that wanted to
421    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
422    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
423    /// "Transient" => …, _ => … }` cascade that expressed no
424    /// compile-time link back to the typed variant's canonical lifted
425    /// constant. A future variant rename or per-arm serde-attribute
426    /// drift would silently split the wire byte-string one non-serde
427    /// consumer parsed from the one the emitter wrote, with the failure
428    /// surfacing at the operator's reconcile posture (a `:temporary`
429    /// `oneShot` child being restarted on clean exit, treating the
430    /// successful-completion signal as failure and re-running the
431    /// completion-terminal one-shot indefinitely; a `:transient` child
432    /// that clean-exited being restarted, masking the clean-completion
433    /// contract) far from the rebrand commit and with no field naming
434    /// the drift.
435    ///
436    /// Distinct axis from the [`std::str::FromStr`] impl the
437    /// [`gen_platform::FromStrKind`] derive already installs on this
438    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
439    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
440    /// `"transient"` — the inverse of [`Self::discriminant`]), while
441    /// this method inverts the `PascalCase` wire byte-string
442    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
443    /// catalog identity live in kebab-case (where every peer catalog
444    /// identifier already lives) without forcing a wire-format rename
445    /// on the tatara-lisp author surface (`:restart Permanent`,
446    /// `PascalCase`) — the same two-axis distinction the sibling
447    /// [`RestartStrategy::from_wire`] (4eec29c) /
448    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
449    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
450    /// carry on their peer closed-set typed-enum wire round-trips.
451    ///
452    /// Same closed-set-reverse-projection discipline the sibling
453    /// [`RestartStrategy::from_wire`] (4eec29c) /
454    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
455    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
456    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
457    /// carry on the peer wire-side `str → Self` axes — extended onto
458    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
459    /// sixth substrate-side closed-set typed enum (and the third and
460    /// final OTP-shape closed-enum discriminator axis) to converge on
461    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
462    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
463    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
464    /// derive already installs on the sibling kebab-case axis. Returns
465    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
466    /// shapes: the caller picks the diagnostic form appropriate for
467    /// its use site.
468    #[must_use]
469    pub fn from_wire(s: &str) -> Option<Self> {
470        match s {
471            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
472            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
473            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
474            _ => None,
475        }
476    }
477}
478
479/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
480/// pretty-printed byte-string every consumer that formats the policy as
481/// user-facing text lands on (the future wasm-operator's per-child
482/// post-exit restart-decision diagnostic line, the future `feira app
483/// graph` per-child restart column, the future M4
484/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
485/// admission-webhook rejection body) reaches for the same lifted
486/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
487/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
488/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
489/// wire-format `Serialize` derive already emits under
490/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
491/// [`RestartPolicy::as_str`] helper already returns.
492///
493/// Pre-convergence the two paths structurally disagreed — the
494/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
495/// route (now retired here) sent [`std::fmt::Display`] through the
496/// gen-platform discriminant catalog string, which arrives kebab-case as
497/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
498/// (whose variant names each collapse to their own lowercase form under
499/// the kebab-case transform), while the wire format ran as `PascalCase`
500/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
501/// serde derive. Every consumer that formatted the policy for a
502/// diagnostic line, a graph column, or a rejection body under
503/// `format!("{v}")` therefore landed under a different byte-string than
504/// the wire format the operator's per-child-policy dispatch keyed off —
505/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
506/// diagnostic quoting `"permanent"` while the wire scalar the operator
507/// probed was `"Permanent"`) surfaced as a confused correlate at
508/// operator-log time far from the two-declaration site.
509///
510/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
511/// path: every `format!("{v}")` call reaches the same lifted
512/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
513/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
514/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
515/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
516/// byte-string per variant. A future variant rename or
517/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
518/// exactly one place, structurally.
519///
520/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
521/// (from `#[derive(gen_platform::Discriminant)]`) still returns
522/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
523/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
524/// registration keys the catalog off the same kebab identity. The two
525/// naming worlds now live on separate typed methods (`Display` /
526/// `as_str` for the wire byte-string, `discriminant` for the catalog
527/// identity) rather than sharing one `Display` route that structurally
528/// disagrees with the wire format.
529///
530/// Pin tests
531/// [`tests::restart_policy_display_routes_through_as_str_helper`]
532/// and
533/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
534/// assert the three paths agree byte-for-byte on every variant, so a
535/// future variant rename or per-arm serde attribute drift is a build
536/// error visible at caixa-core test time, not a silent per-consumer
537/// dispatch miss at apply / reconcile time.
538///
539/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
540/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
541/// and the sibling [`RestartStrategy`] `Display` impl on the
542/// per-supervisor sibling-restart-strategy axis — same three-path-
543/// convergence discipline, extended to close the third and final of
544/// three OTP-shaped closed-enum discriminator axes on the caixa typed
545/// surface.
546impl std::fmt::Display for RestartPolicy {
547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548        f.write_str(self.as_str())
549    }
550}
551
552// Fleet-wide dispatcher-catalog registrations for caixa's OTP
553// supervisor surface — two more typed shadows over Erlang/OTP
554// primitives the substrate now mechanically tracks (see
555// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
556// theory/TYPED-ABSORPTION.md for the absorption arc).
557gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
558gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
559
560/// One child entry in the supervisor's `:children` list.
561///
562/// Every child references another caixa by `:caixa <nome>` + version
563/// constraint. The supervisor materializes one ComputeUnit per entry.
564#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
565#[serde(rename_all = "camelCase")]
566pub struct ChildSpec {
567    /// The child caixa's `:nome`. Must resolve via the same dependency
568    /// resolution path as `:deps` (caixa-resolver).
569    pub caixa: String,
570
571    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
572    /// [`crate::dep::Dep::versao`].
573    pub versao: String,
574
575    /// Restart policy — an author-omitted slot degrades onto the
576    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
577    /// (`permanent`, the Erlang/OTP worker-child default) through the
578    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
579    /// to.
580    #[serde(default)]
581    pub restart: RestartPolicy,
582}
583
584impl ChildSpec {
585    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
586    /// accessor every consumer that reads the OTP-shape supervised
587    /// child's identity keys off — returns the author-declared
588    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
589    /// from the typed slot's own [`String`] storage.
590    ///
591    /// The `:children :caixa` slot carries the DNS-1123 label — the
592    /// child caixa's `:nome` — that every emitted cluster artifact
593    /// derives its `metadata.name` from verbatim: the rendered
594    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
595    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
596    /// identity, and the per-child K8s Service `metadata.name` the
597    /// future wasm-operator (M3) provisions for inter-child supervision-
598    /// tree wiring. Every downstream consumer that fans on the child's
599    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
600    /// per-child DNS-1123 gate at
601    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
602    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
603    /// [`validate_no_self_supervision`] cross-slot equality check
604    /// against the parent's `:nome`, every `SupervisorError` variant
605    /// carrying the offending child caixa verbatim for `feira lint`
606    /// rendering, the future wasm-operator's hierarchical reconciliation
607    /// scheduler's per-child ComputeUnit-name projection, the future M4
608    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
609    /// admission webhook).
610    ///
611    /// Prior to this lift the `.caixa` byte-string was accessed inline
612    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
613    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
614    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
615    /// carriers' `child.caixa.clone()`, the dedup key's
616    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
617    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
618    /// field-accesses that expressed no compile-time link back to the
619    /// typed slot. A future extension of the `:children :caixa` axis to
620    /// a richer author surface (a per-cluster alias table the operator
621    /// pins through a future `:placement`-scoped slot on the supervisor
622    /// tree, a namespace-qualified rewrite the M4 CR materializer
623    /// applies per-CR, a per-child overlay from the future `:children
624    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
625    /// acknowledges) would have had to be threaded through every
626    /// open-coded copy in lockstep or one consumer would silently
627    /// disagree with the peers on which caixa a given child resolves to
628    /// — a child-set lookup that treated the name as `"cart-worker"`
629    /// while the peer duplicate-detector treated it as
630    /// `"tenant-a/cart-worker"` would silently split the
631    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
632    /// self-supervision detector's parent-equality check, a two-consumer
633    /// split at the validator far from the source `caixa.lisp` with no
634    /// field naming the identity-drift root cause. Lifting the resolution
635    /// rule to a typed method on the substrate primitive means every
636    /// downstream consumer of the Supervisor's per-`:children` identity
637    /// surface reaches for exactly one typed dispatch — the resolver's
638    /// accept-set migrates as a unit on any future axis addition.
639    ///
640    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
641    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
642    /// mesh-slot surface — same "one typed dispatch on the substrate
643    /// primitive, thin projections at each consumer" discipline extended
644    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
645    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
646    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
647    /// accessor discipline for the shared substrate concept "another
648    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
649    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
650    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
651    /// slot family's typed-accessor discipline now spans both the
652    /// upgrade axis (`:upgrade-from`) and the supervision axis
653    /// (`:children`), matching the closed M3 mesh-slot accessor family's
654    /// shape. Named `nome()` to match the tatara-lisp author-surface
655    /// term the field's docstring already reaches for ("The child
656    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
657    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
658    /// discipline the substrate already carries — the accessor's name
659    /// maps directly onto the canonical caixa-identity vocabulary rather
660    /// than shadowing the field's storage-side `caixa` label.
661    #[must_use]
662    pub const fn nome(&self) -> &str {
663        self.caixa.as_str()
664    }
665
666    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
667    /// requirement scalar accessor every consumer that reads the OTP-shape
668    /// supervised child's version pin keys off — returns the author-declared
669    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
670    /// the typed slot's own [`String`] storage.
671    ///
672    /// The `:children :versao` slot carries the Cargo-shaped semver
673    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
674    /// which release of the supervised child caixa the OTP-shape supervisor
675    /// tree materializes against — the same requirement grammar the peer
676    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
677    /// shared [`crate::render::require_valid_versao_requirement`] cascade
678    /// and the shared [`crate::version::parse_requirement`] parser. Every
679    /// downstream consumer that fans on the child's version pin keys off
680    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
681    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
682    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
683    /// for `feira lint` rendering, every future per-cluster version-lock
684    /// overlay the caixa-operator's hierarchical reconciliation scheduler
685    /// pins through a future `:placement`-scoped supervisor-tree slot, the
686    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
687    /// per-child version resolver, the future wasm-operator's per-child
688    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
689    ///
690    /// Prior to this lift the `.versao` byte-string was accessed inline at
691    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
692    /// [`SupervisorSpec::validate`] requirement-gate call
693    /// `require_valid_versao_requirement(&child.versao, …)` and the
694    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
695    /// `versao: child.versao.clone()` — two open-coded field-accesses that
696    /// expressed no compile-time link back to the typed slot. A future
697    /// extension of the `:children :versao` axis to a richer author surface
698    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
699    /// flow, a lacre-projected concrete-version rewrite the operator
700    /// materializes at CR-admission time, a future `:children :versao-lock`
701    /// per-cluster override slot the wasm-operator's hierarchical
702    /// reconciliation scheduler authors per-CR) would have had to be
703    /// threaded through both open-coded copies in lockstep or one consumer
704    /// would silently disagree with the peer on which release constraint a
705    /// given child resolves to — the requirement-gate call reading
706    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
707    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
708    /// the actual gate rejection input, a two-consumer split at the
709    /// validator far from the source `caixa.lisp` with no field naming the
710    /// version-pin drift root cause. Lifting the resolution rule to a typed
711    /// method on the substrate primitive means every downstream
712    /// requirement-facing consumer of the Supervisor's per-`:children`
713    /// version-pin surface reaches for exactly one typed dispatch — the
714    /// resolver's accept-set migrates as a unit on any future axis addition.
715    ///
716    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
717    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
718    /// surface — same "one typed dispatch on the substrate primitive, thin
719    /// projections at each consumer" discipline extended onto the M2
720    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
721    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
722    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
723    /// one accessor discipline for the shared substrate concept "another
724    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
725    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
726    /// `:nome` scalar accessor — the pair
727    /// `(nome(), versao_requirement())` jointly projects the
728    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
729    /// that fans on per-child identity + version pin keys off, closing the
730    /// last unlifted per-`:children` `String`-carry axis so every downstream
731    /// per-`:children` reader now routes through a typed dispatch on the
732    /// substrate primitive. Named `versao_requirement()` rather than
733    /// `versao()` because the field's storage-side `.versao` label is
734    /// already the author-surface term (`:versao`); the accessor's name
735    /// carries the semantic role — the semver *requirement* string the
736    /// shared [`crate::version::parse_requirement`] entry-point consumes —
737    /// so a raw field access and a typed dispatch read differently at every
738    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
739    /// naming discipline verbatim.
740    #[must_use]
741    pub const fn versao_requirement(&self) -> &str {
742        self.versao.as_str()
743    }
744
745    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
746    /// per-child post-exit restart-decision policy scalar accessor every
747    /// consumer that dispatches on the supervised child's post-exit
748    /// reconcile posture keys off — returns the author-declared
749    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
750    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
751    /// storage.
752    ///
753    /// The `:children :restart` slot carries the closed-set OTP-shaped
754    /// per-child restart-decision policy discriminator
755    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
756    /// worker-child default; [`RestartPolicy::Transient`] — restart only
757    /// on abnormal exit, the OTP `transient` clean-completion-aware
758    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
759    /// `temporary` one-shot default) that every downstream consumer of
760    /// the Supervisor's per-child post-exit reconcile branch keys off.
761    /// Every future downstream consumer that fans on the per-child
762    /// restart-decision keys off this scalar (the future `feira app
763    /// graph` per-child restart column, the future wasm-operator's
764    /// per-child post-exit restart-decision branch, the future M4
765    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
766    /// admission webhook, the `caixa-operator`'s hierarchical
767    /// reconciliation scheduler's per-child post-exit reconcile branch,
768    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
769    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
770    /// pin threads through).
771    ///
772    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
773    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
774    /// scalar accessor and the M3 mesh-slot
775    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
776    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
777    /// — same "one typed dispatch on the substrate primitive,
778    /// `Copy`-projected closed-set enum-arm discriminator that partitions
779    /// the downstream renderer's per-arm fan-out" discipline extended
780    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
781    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
782    /// [`ChildSpec`] type — companion to the sibling per-`:children`
783    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
784    /// and the per-`:children` [`ChildSpec::versao_requirement`]
785    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
786    /// on the sibling `String`-carry axes. The triple
787    /// `(nome(), versao_requirement(), restart())` jointly projects the
788    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
789    /// tree consumer that fans on per-child identity + version pin +
790    /// restart-decision keys off, closing the last unlifted per-`:children`
791    /// axis so every downstream per-`:children` reader now routes through
792    /// a typed dispatch on the substrate primitive. Named `restart()` to
793    /// match the storage field's name and the author-surface
794    /// `:children :restart` slot term verbatim; the accessor's identity
795    /// name maps onto the canonical OTP-shape per-child restart-decision-
796    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
797    /// carries.
798    ///
799    /// Declared `pub const fn` to close the last non-`const`
800    /// `Copy`-return raw-field-getter posture on the M2
801    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
802    /// of the sibling M2 per-`:supervisor`
803    /// [`SupervisorSpec::estrategia`] (converted in this commit)
804    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
805    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
806    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
807    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
808    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
809    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
810    /// downstream substrate-side `const`-context consumer of the
811    /// per-`:children` restart-decision-policy scalar (a future
812    /// module-scope `const _:() = assert!(matches!(child.restart(),
813    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
814    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
815    /// admission-webhook `const fn` per-child restart-decision floor
816    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
817    /// composer over the substrate primitive that fans on the per-child
818    /// restart-decision policy at compile time) now reaches through the
819    /// same typed dispatch on the substrate primitive at const-eval
820    /// time as at runtime. A future non-`Copy`-return promotion of the
821    /// scalar (an `Option<RestartPolicy>`-shape migration on the
822    /// per-child restart-decision axis once heterogeneous per-cluster
823    /// restart-policy overlays land, a per-tenant restart-policy-alias
824    /// table the M4 CR materializer resolves per-CR) that would drop
825    /// the `const` qualifier fails the fail-before-pass-after pin
826    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
827    /// build time rather than surfacing as a downstream consumer
828    /// regression.
829    #[must_use]
830    pub const fn restart(&self) -> RestartPolicy {
831        self.restart
832    }
833}
834
835/// Supervisor-typed slots that live alongside the standard Caixa
836/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
837/// the manifest stays a single typed form; this struct exists for
838/// validation + conversion.
839#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
840#[serde(rename_all = "camelCase")]
841pub struct SupervisorSpec {
842    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
843    #[serde(default)]
844    pub estrategia: RestartStrategy,
845
846    /// Max restarts within [`Self::restart_window`] before the
847    /// supervisor itself terminates (and its parent supervisor decides
848    /// what to do). Default 5.
849    #[serde(default = "default_max_restarts")]
850    pub max_restarts: u32,
851
852    /// Sliding window for `max_restarts`. Authored as a duration
853    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
854    /// is rejected by [`Self::validate`] — Erlang/OTP's
855    /// `MaxIntensity / Period` invariant requires a positive window
856    /// (a zero-period supervisor either trips on the first failure or
857    /// never trips, depending on operator interpretation, neither of
858    /// which is the author's intent). Omit the slot to express "no
859    /// reset"; carry a positive duration to express the sliding window.
860    #[serde(
861        default,
862        skip_serializing_if = "Option::is_none",
863        with = "duration_codec"
864    )]
865    pub restart_window: Option<Duration>,
866
867    /// Static children. Empty for `SimpleOneForOne` (children added
868    /// dynamically); required for the other three strategies.
869    #[serde(default)]
870    pub children: Vec<ChildSpec>,
871}
872
873const fn default_max_restarts() -> u32 {
874    // Route the private serde-`#[serde(default = "…")]` helper through
875    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
876    // `pub const` rather than the raw `5` literal — one source of truth
877    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
878    // default across the two production consumers that currently
879    // dispatch on it (this helper via `#[serde(default = "…")]` on
880    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
881    // impl at line 962). Pinned by
882    // `default_max_restarts_helper_routes_through_lifted_default` +
883    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
884    // in the tests module; peer of the sibling caixa-core
885    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
886    // that now routes its author-omitted `:max-restarts` arm through
887    // the same lifted constant.
888    SUPERVISOR_MAX_RESTARTS_DEFAULT
889}
890
891/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
892/// count default for the `:supervisor :max-restarts` axis — the
893/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
894/// Erlang's worker-supervisor default, extracted as a typed `pub const`
895/// so every substrate-side consumer that resolves "what
896/// [`SupervisorSpec::max_restarts`] value does an author-omitted
897/// `:max-restarts` slot degrade onto?" reaches for exactly one
898/// substrate-primitive `u32`.
899///
900/// The `:max-restarts` default axis has two production consumers on the
901/// substrate side today (both prior to this lift folded onto raw `5`
902/// literals with no compile-time link back to a shared truth): the
903/// serde-`#[serde(default = "default_max_restarts")]` helper on
904/// [`SupervisorSpec::max_restarts`] that every author-omitted
905/// `:supervisor :max-restarts` slot lands in past the derive-macro's
906/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
907/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
908/// the composed [`SupervisorSpec`] altitude reaches through
909/// (`feira app graph`, the future wasm-operator's per-supervisor
910/// restart-intensity counter, the future M4
911/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
912/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
913/// A pair of open-coded `5`s across two files that expressed no
914/// compile-time link back to the shared OTP-canonical default — a
915/// future rebrand of the default (a tightening to Elixir's
916/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
917/// the operator pins through a future
918/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
919/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
920/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
921/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
922/// per-child-cohort roadmap lands) would have had to be threaded
923/// through both open-coded copies in lockstep or the wire-format
924/// author-omitted arm and the view-construction author-omitted arm
925/// would silently disagree on which restart-budget an omitted
926/// `:max-restarts` resolves to (an author writing `:supervisor
927/// (:max-restarts ())` would round-trip through serde with the new
928/// default while `supervisor_view` silently continued to compose the
929/// stale `5`, or vice versa), a two-consumer split at the composition
930/// boundary far from the source `caixa.lisp` with no field naming the
931/// default-drift root cause. Lifting the resolution rule to a typed
932/// `pub const` on the substrate primitive means every downstream
933/// consumer of the per-Supervisor default-restart-budget-count surface
934/// reaches for exactly one substrate-primitive `u32` — the resolver's
935/// accepted value migrates as a unit on any future axis change.
936///
937/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
938/// worker-supervisor default (the closest canonical OTP-shape
939/// production reference the substrate carries, matching the sibling
940/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
941/// this constant with on the paired sliding-window axis). Two orders of
942/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
943/// (the upper bracket on the same axis, sibling of this lower default;
944/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
945/// axis and now share one accessor discipline on the substrate) and
946/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
947/// restart floor — the "one restart, then escalate" default is
948/// deliberately loose enough to absorb a short burst of transient
949/// child failures without escalating past the supervisor's parent
950/// while remaining tight enough to trip the `MaxIntensity / Period`
951/// ratio's escalation on a genuinely-stuck child within the sibling
952/// `60s` sliding window.
953///
954/// Lifted as a typed `pub const` so the bound has exactly one source
955/// of truth — the serde-side wire-format author-omitted arm at
956/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
957/// struct-literal default field, and the caixa-core
958/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
959/// arm all read from one place. Same shape every other typed default
960/// in this crate carries (the sibling
961/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
962/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
963/// sibling `:restart-window` axis, and the peer
964/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
965/// per-renderer defaults on the caixa-flux / caixa-helm rendering
966/// axes).
967pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
968
969/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
970/// validated [`SupervisorSpec::max_restarts`] past
971/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
972///
973/// The typed field is `u32` (the zero-floor arm
974/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
975/// so a programmatic struct literal
976/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
977/// author-surface form (`:max-restarts 4294967295` or any
978/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
979/// cleanly through serde — a structurally unbounded `u32` ceiling. The
980/// runtime substrate consuming the value (Erlang/OTP's
981/// `MaxIntensity / Period` ratio, the future wasm-operator's
982/// per-supervisor restart-intensity counter, the M4
983/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
984/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
985/// escalation threshold is structurally so high that no realistic
986/// restarts-per-`:restart-window` traffic shape can reach it, the
987/// supervisor never escalates to its parent, and a bad child can loop
988/// inside the window indefinitely with the parent supervisor structurally
989/// never receiving the "this subtree has exceeded its restart budget"
990/// signal the typed slot is meant to express — the canonical
991/// "supervisor intensity declared, no escalation" footgun, exactly the
992/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
993/// on the `:politicas :circuit-breaker :max-failures` axis (both are
994/// "trip the next-higher protection layer after N events in a rolling
995/// window" counters with identical degenerate-at-the-high-end shape).
996///
997/// The `1000` ceiling matches the sibling
998/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
999/// peer — same "events-per-window trip threshold" semantics, same `u32`
1000/// type, same no-op-at-the-high-end failure mode) so the M4
1001/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1002/// and the future wasm-operator's per-supervisor restart-intensity
1003/// counter reach for either field knowing the value is in `1..=1000`
1004/// without re-validating at the reconciler layer. The cap sits two
1005/// orders of magnitude above every documented Erlang/OTP production
1006/// playbook recommendation (Learn You Some Erlang's
1007/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1008/// `max_restarts: 3` default, OTP's `supervisor` callback module
1009/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1010/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1011/// default) and below the clearly-pathological "effectively no
1012/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1013/// author can plausibly want at hyperscale (a long-running supervisor
1014/// over a very-flaky pool tolerating thousands of transient restarts
1015/// before escalating), but a hard wall above which the typed policy is
1016/// structurally a no-op carried verbatim on every emitted child-restart
1017/// reconciliation contract.
1018///
1019/// Lifted as a typed `pub const` so the bound has exactly one source of
1020/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1021/// materializer's admission webhook and the wasm-operator-side
1022/// per-supervisor restart-intensity reconciler read from one place. Same
1023/// shape every other typed upper bound in this crate carries
1024/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1025/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1026/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1027/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1028/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1029/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1030pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1031
1032/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1033/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1034/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1035/// (inclusive on both ends, integer-millisecond magnitudes by the
1036/// canonical-form gate immediately preceding).
1037///
1038/// The typed field is `Option<Duration>` (the zero-floor arm
1039/// [`SupervisorError::RestartWindowZero`] already rejects
1040/// `Some(Duration::ZERO)`, and the canonical-form arm
1041/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1042/// sub-millisecond residue), so a programmatic struct literal
1043/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1044/// .. }` — 24h) and the equivalent author-surface form
1045/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1046/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1047/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1048/// A `:restart-window` value far above the documented Erlang/OTP
1049/// `MaxIntensity / Period` production-playbook band (Learn You Some
1050/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1051/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1052/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1053/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1054/// degenerates the supervisor's restart-intensity counter into a
1055/// lifetime counter: the rolling failure-counting window is structurally
1056/// so long that transient restarts are never forgotten, so the
1057/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1058/// supervisor when the child has exceeded its restart budget *within
1059/// the recent window*" to "trip the parent when the child has exceeded
1060/// its restart budget *over its lifetime*" — every transient restart
1061/// counts against the budget forever, the supervisor's reset semantic
1062/// never reaches the child, and the typed `:restart-window` slot
1063/// becomes a no-op rolling window carried on every emitted hierarchical
1064/// reconciliation contract. The canonical
1065/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1066/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1067/// `:politicas :circuit-breaker :window` axis with identical shape (both
1068/// are "rolling failure-counting window with a per-`Period` reset" Duration
1069/// axes whose lifetime-counter degenerate at the high end is the same
1070/// "the reset semantic never fires" CSE invariant violation).
1071///
1072/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1073/// the shared duration codec emits (`"<n>h"` for any integer-hour
1074/// magnitude) — every value in the canonical authoring form's
1075/// `<integer><unit>` grammar at or below this cap renders to a clean
1076/// canonical string — and matches the three sibling typed-`Duration`
1077/// caps already lifted to this surface
1078/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1079/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1080/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1081/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1082/// per-supervisor `:supervisor :restart-window` — now share a single
1083/// uniform top edge at the codec's largest emitted unit so the next
1084/// typed-slot wiring (the future wasm-operator's per-supervisor
1085/// `MaxIntensity / Period` reconciler, the M4
1086/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1087/// webhook, the `caixa-operator`'s hierarchical reconciliation
1088/// scheduler) reaches for any of the four knowing the value is in
1089/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1090/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1091/// Riak Core / RabbitMQ production-playbook recommendation band
1092/// (`5s..=300s`) and below the clearly-pathological "rolling window
1093/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1094/// a value the author can plausibly want for a very-low-traffic
1095/// long-tail failure-restart window over a hyperscale-flaky child pool,
1096/// but a hard wall above which the rolling-window contract is
1097/// structurally a lifetime-counter contract.
1098///
1099/// Lifted as a typed `pub const` so the bound has exactly one source
1100/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1101/// materializer's admission webhook, the wasm-operator-side
1102/// per-supervisor `MaxIntensity / Period` reconciler, and the
1103/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1104/// from one place. Same shape every other typed upper bound in this
1105/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1106/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1107/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1108/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1109/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1110/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1111/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1112/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1113/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1114pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1115
1116/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1117/// default for the `:supervisor :restart-window` axis — the canonical
1118/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1119/// worker-supervisor default, extracted as a typed `pub const` so every
1120/// substrate-side consumer that resolves "what
1121/// [`SupervisorSpec::restart_window`] value does an author-omitted
1122/// `:restart-window` slot degrade onto?" reaches for exactly one
1123/// substrate-primitive [`Duration`].
1124///
1125/// The `:restart-window` default axis has one production consumer on the
1126/// substrate side today: the [`Default for SupervisorSpec`] impl's
1127/// struct-literal `restart_window` field, which prior to this lift folded
1128/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1129/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1130/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1131/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1132/// *not* fall back to this default on the sibling `:restart-window` axis
1133/// — an author-omitted `:supervisor :restart-window` composes to
1134/// `restart_window: None` (the shared codec's soft-swallow shape),
1135/// keeping author-declared intent ("no reset — never escalate on rolling
1136/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1137/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1138/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1139/// default was split across two files with no compile-time link between
1140/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1141/// `MaxIntensity` half at the substrate primitive while the `Period`
1142/// half rode as an open-coded literal at the composition site, so a
1143/// future coherent rebrand of the paired canonical (a tightening to
1144/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1145/// per-cluster overlay the operator pins through a future
1146/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1147/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1148/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1149/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1150/// roadmap lands) would have had to migrate the `MaxIntensity` half
1151/// through the lifted constant and the `Period` half through a raw
1152/// literal in lockstep or the two halves of the same OTP-canonical
1153/// default would silently drift out of pairing. Lifting the resolution
1154/// rule to a typed `pub const` on the substrate primitive means the
1155/// paired OTP-canonical default migrates as one unit on any future
1156/// axis change.
1157///
1158/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1159/// worker-supervisor default (the closest canonical OTP-shape
1160/// production reference the substrate carries, matching the paired
1161/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1162/// constant is the `Period` denominator of on the same
1163/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1164/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1165/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1166/// this lower default; both are typed [`Duration`] const bounds on the
1167/// `:supervisor :restart-window` axis and now share one accessor
1168/// discipline on the substrate) and above the OTP-`supervisor`
1169/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1170/// rolling window" default is deliberately loose enough to absorb a
1171/// short burst of transient child failures without escalating past the
1172/// supervisor's parent while remaining tight enough for the paired
1173/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1174/// stuck child within a human-scale observation window.
1175///
1176/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1177/// exactly one source of truth on each half — the sibling
1178/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1179/// `Period` `60s` half now share the same substrate-primitive lift
1180/// discipline. Same shape every other typed default in this crate
1181/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1182/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1183/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1184/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1185/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1186/// caixa-flux / caixa-helm rendering axes).
1187pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1188
1189/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1190/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1191/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1192/// worker-supervisor default, extracted as a typed `pub const` so every
1193/// substrate-side consumer that resolves "what
1194/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1195/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1196/// primitive [`RestartStrategy`].
1197///
1198/// The `:estrategia` default axis has three production consumers on the
1199/// substrate side today: the [`Default for RestartStrategy`] impl's
1200/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1201/// `estrategia` field, and the
1202/// [`crate::manifest::Caixa::supervisor_view`] fold's
1203/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1204/// collapse arm — three entry points onto the same OTP-canonical
1205/// `one_for_one` value that prior to this lift folded onto a raw
1206/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1207/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1208/// with no compile-time link back to the paired
1209/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1210/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1211/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1212/// triple was split across three altitudes with no compile-time link
1213/// between the halves: the `MaxIntensity` half rode through the lifted
1214/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1215/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1216/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1217/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1218/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1219/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1220/// intensity/period; an OTP `rest_for_one` widening once the substrate
1221/// discovers startup-order-coupled child cohorts as the more common
1222/// worker-supervisor default; a per-cluster overlay the operator pins
1223/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1224/// §III.2 supervision-canary roadmap acknowledges) would have had to
1225/// migrate the `MaxIntensity` + `Period` halves through the lifted
1226/// constants and the `one_for_one` half through an open-coded arm in
1227/// lockstep or the three halves of the same OTP-canonical default would
1228/// silently drift out of pairing. Lifting the resolution rule to a typed
1229/// `pub const` on the substrate primitive means the paired OTP-canonical
1230/// worker-supervisor default migrates as one unit on any future axis
1231/// change.
1232///
1233/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1234/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1235/// closest canonical OTP-shape production reference the substrate
1236/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1237/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1238/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1239/// failed child, leaving siblings untouched — is the default for tree-of-
1240/// independent-workers use cases the substrate's [`RestartStrategy`]
1241/// discriminator's own docstring already carries as the default arm; it
1242/// composes with the `{5, 60}` restart-intensity ratio to name the same
1243/// substrate-canonical "canonical worker-supervisor" shape the paired
1244/// halves close on their respective axes.
1245///
1246/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1247/// exactly one source of truth on each of its three halves — the sibling
1248/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1249/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1250/// this `one_for_one` strategy half now share the same substrate-
1251/// primitive lift discipline. Same shape every other typed default in
1252/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1253/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1254/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1255/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1256/// upper caps on the paired sibling axes, and the peer
1257/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1258/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1259pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1260
1261/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1262/// default for the `:children :restart` axis — the OTP `permanent`
1263/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1264/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1265/// `pub const` so every substrate-side consumer that resolves "what
1266/// [`ChildSpec::restart`] variant does an author-omitted `:children
1267/// :restart` slot degrade onto?" reaches for exactly one substrate-
1268/// primitive [`RestartPolicy`].
1269///
1270/// Completes the OTP-shape supervisor-tree default set at the substrate
1271/// primitive. The per-`:supervisor` axis already carries all three of its
1272/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1273/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1274/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1275/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1276/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1277/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1278/// the M2 `:supervisor` slot family. The split mattered because the two
1279/// axes resolve *together* on every author-omitted supervisor: a
1280/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1281/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1282/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1283/// `permanent` through an open-coded enum arm, so a future coherent
1284/// rebrand of the OTP-shape default set (an Elixir-shaped
1285/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1286/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1287/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1288/// once the substrate discovers clean-completion-aware children as the
1289/// more common child shape) would have had to migrate three halves
1290/// through typed constants and the fourth through a raw enum arm in
1291/// lockstep or the supervisor-level and child-level defaults would
1292/// silently drift apart.
1293///
1294/// The `:children :restart` default axis has two production consumers on
1295/// the substrate side today: the [`Default for RestartPolicy`] impl's
1296/// return arm, and the serde-side `#[serde(default)]` on
1297/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1298/// :restart` slot through that same impl. Both now key off this one
1299/// substrate primitive, so the future wasm-operator's per-child post-exit
1300/// restart-decision branch, the future M4
1301/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1302/// admission webhook, and the `caixa-operator`'s hierarchical
1303/// reconciliation scheduler's per-child fan-out all reach for one typed
1304/// identifier when they resolve an omitted per-child restart posture.
1305///
1306/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1307/// worker-child restart type — always restart the child regardless of how
1308/// it died, the canonical posture for long-running services that must
1309/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1310/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1311/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1312/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1313/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1314/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1315/// one-shot / clean-completion-aware postures an author declares
1316/// explicitly, never a posture an omitted slot should silently assume.
1317pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1318
1319impl Default for SupervisorSpec {
1320    fn default() -> Self {
1321        Self {
1322            // Route the struct-literal `estrategia` default arm through
1323            // the substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1324            // typed `pub const` rather than the transitively-derived
1325            // `RestartStrategy::default()` route — one source of truth
1326            // for the Erlang/OTP `one_for_one` half of Learn You Some
1327            // Erlang's `{one_for_one, intensity, 5, 60}` worker-
1328            // supervisor canonical default, paired with the sibling
1329            // `max_restarts: default_max_restarts()` arm below that
1330            // routes through the peer [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1331            // `MaxIntensity` half (b698ec0) and the sibling
1332            // `restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT)`
1333            // arm that routes through the peer
1334            // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half
1335            // (f7dcd0e). All three halves of the same OTP-canonical
1336            // default now share the same substrate-primitive lift
1337            // discipline so any future coherent rebrand of the paired
1338            // triple migrates through three typed constants in lockstep
1339            // instead of splitting two lifted halves against a
1340            // transitively-derived third. Pinned by
1341            // `supervisor_spec_default_estrategia_routes_through_lifted_default`.
1342            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1343            max_restarts: default_max_restarts(),
1344            // Route the struct-literal `restart_window` default arm
1345            // through the substrate-canonical
1346            // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] typed `pub const`
1347            // rather than a raw `Duration::from_secs(60)` literal — one
1348            // source of truth for the Erlang/OTP-canonical
1349            // `{intensity, 5, 60}` `Period` half of Learn You Some
1350            // Erlang's worker-supervisor default, paired with the
1351            // sibling `max_restarts: default_max_restarts()` arm above
1352            // that already routes through the peer
1353            // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half
1354            // (b698ec0). The two halves of the same OTP-canonical
1355            // default now share the same substrate-primitive lift
1356            // discipline so any future coherent rebrand of the paired
1357            // default (Elixir's `{max_restarts: 3, max_seconds: 5}`, a
1358            // per-cluster overlay via a future
1359            // `:restart-window-overrides` slot, a per-child-cohort
1360            // promotion) migrates through two typed constants in
1361            // lockstep instead of splitting a lifted `MaxIntensity` half
1362            // against an open-coded `Period` literal. Pinned by
1363            // `supervisor_spec_default_restart_window_routes_through_lifted_default`
1364            // in the tests module; peer of the sibling
1365            // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1366            // byte-parity pin on the paired `max_restarts` field.
1367            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1368            children: Vec::new(),
1369        }
1370    }
1371}
1372
1373impl SupervisorSpec {
1374    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1375    /// sibling-restart-strategy scalar accessor every consumer that
1376    /// dispatches on the supervisor's per-sibling restart-decision shape
1377    /// keys off — returns the author-declared `:supervisor :estrategia`
1378    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1379    /// the typed slot's own [`RestartStrategy`] storage.
1380    ///
1381    /// The `:supervisor :estrategia` slot carries the closed-set
1382    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1383    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1384    /// [`RestartStrategy::OneForAll`] — restart every child on any child
1385    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1386    /// [`RestartStrategy::RestForOne`] — restart the failed child and
1387    /// every child started after it, the Erlang/OTP `rest_for_one`
1388    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1389    /// dynamic children of the same shape, the Erlang/OTP
1390    /// `simple_one_for_one` per-session default) that every downstream
1391    /// consumer of the Supervisor's per-sibling restart-decision fan-out
1392    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1393    /// paired coherently with the sibling `:children` axis
1394    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1395    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1396    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1397    /// downstream consumer that reads the strategy keys off this scalar
1398    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1399    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1400    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1401    /// `estrategia:` field, the future `feira app graph` per-Supervisor
1402    /// strategy print line, the future wasm-operator's per-supervisor
1403    /// sibling-restart-strategy branch, the future M4
1404    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1405    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1406    /// reconciliation scheduler's per-strategy fan-out).
1407    ///
1408    /// Prior to this lift the `.estrategia` field was accessed inline at
1409    /// two production sites in `caixa-core/src/supervisor.rs` — the
1410    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1411    /// `match self.estrategia { … }` partition dispatch, and the
1412    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1413    /// carrier at `estrategia: self.estrategia` — two open-coded
1414    /// field-accesses that expressed no compile-time link back to the
1415    /// typed slot. A future extension of the `:supervisor :estrategia`
1416    /// axis to a richer author surface (a per-cluster strategy override
1417    /// the operator pins through a future `:supervisor :estrategia-overrides`
1418    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1419    /// acknowledges, a per-tenant strategy-alias table the M4 CR
1420    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1421    /// derivation the future adaptive-supervision engine computes from
1422    /// child-failure-history topology, a per-child-cohort strategy split
1423    /// the future `RestForCohort` extension acknowledged by the
1424    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1425    /// would have had to be threaded through every open-coded copy in
1426    /// lockstep — one consumer reading the raw variant while a peer read
1427    /// the operator-resolved variant would silently split the
1428    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1429    /// the actual partition-dispatch input the empty-children refusal
1430    /// arm reached under, a two-consumer split at the validator far from
1431    /// the source `caixa.lisp` with no field naming the strategy-drift
1432    /// root cause. Lifting the resolution rule to a typed method on the
1433    /// substrate primitive means every downstream consumer of the
1434    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1435    /// reaches for exactly one typed dispatch — the resolver's accept-set
1436    /// migrates as a unit on any future axis addition.
1437    ///
1438    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1439    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1440    /// per-`:placement` distribution-strategy axis — same "one typed
1441    /// dispatch on the substrate primitive, thin projections at each
1442    /// consumer" discipline extended onto the M2 supervisor-slot
1443    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1444    /// scalar axis. The two typed axes (`Placement::estrategia` on the
1445    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1446    /// Supervisor side) now share one accessor discipline for the shared
1447    /// substrate concept "a `Copy`-projected closed-set enum-arm
1448    /// discriminator that partitions the downstream renderer's per-arm
1449    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1450    /// `SupervisorSpec` type — companion to the sibling per-`:children`
1451    /// [`crate::ChildSpec::nome`] (57c61d0) /
1452    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1453    /// scalar accessors on the sibling per-`:children` `String`-carry
1454    /// axes. Named `estrategia()` to match the storage field's name and
1455    /// the peer [`crate::Placement::estrategia`] method-name discipline
1456    /// verbatim; the accessor's identity name maps onto the canonical
1457    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1458    /// docstring already carries.
1459    ///
1460    /// Declared `pub const fn` to close the M2 supervisor-slot
1461    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1462    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1463    /// (converted in this commit) `Copy`-composite-enum accessor, peer
1464    /// of the sibling M2 per-`:supervisor`
1465    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1466    /// already lifted, and mirror of the peer M3 mesh-slot
1467    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1468    /// `Copy`-return `pub const fn` scalar accessor whose method-name
1469    /// discipline this accessor was authored to match. Every downstream
1470    /// substrate-side `const`-context consumer of the per-`:supervisor`
1471    /// sibling-restart-strategy scalar (a future module-scope `const
1472    /// _:() = assert!(matches!(sup.estrategia(),
1473    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1474    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1475    /// admission-webhook `const fn` per-supervisor strategy-arm floor
1476    /// over a typed [`SupervisorSpec`], any future `const fn`
1477    /// supervisor-tree composer over the substrate primitive that fans
1478    /// on the sibling-restart-strategy at compile time) now reaches
1479    /// through the same typed dispatch on the substrate primitive at
1480    /// const-eval time as at runtime. A future non-`Copy`-return
1481    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1482    /// migration once the substrate grows per-cluster strategy overlays
1483    /// the [`SupervisorSpec`] docstring already anticipates, a
1484    /// per-tenant strategy-alias table the M4 CR materializer resolves
1485    /// per-CR) that would drop the `const` qualifier fails the
1486    /// fail-before-pass-after pin
1487    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1488    /// caixa-core build time rather than surfacing as a downstream
1489    /// consumer regression.
1490    #[must_use]
1491    pub const fn estrategia(&self) -> RestartStrategy {
1492        self.estrategia
1493    }
1494
1495    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1496    /// `MaxIntensity` restart-budget scalar accessor every consumer that
1497    /// reads the supervisor's per-`:restart-window` restart-budget count
1498    /// keys off — returns the author-declared `:supervisor :max-restarts`
1499    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1500    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1501    /// borrow of `&self` past the call). Non-optional (the `u32` field
1502    /// carries the restart-budget count as a required axis with a
1503    /// [`default_max_restarts`]-supplied default; the zero-floor arm
1504    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1505    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1506    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1507    ///
1508    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1509    /// `MaxIntensity` restart-budget count that pairs with the sibling
1510    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1511    /// restart-intensity ratio the supervisor trips its own escalation on
1512    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1513    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1514    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1515    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1516    /// upper-cap bracket at
1517    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1518    /// wasm-operator's per-supervisor restart-intensity counter's
1519    /// budget-vs-count comparator, the future M4
1520    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1521    /// webhook, the `caixa-operator`'s hierarchical reconciliation
1522    /// scheduler's per-supervisor escalation-decision branch, every
1523    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1524    /// offending count verbatim for `feira lint` rendering).
1525    ///
1526    /// Prior to this lift the `.max_restarts` field was accessed inline at
1527    /// one production site in `caixa-core/src/supervisor.rs` — the
1528    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1529    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1530    /// that expressed no compile-time link back to the typed slot. A
1531    /// future extension of the `:max-restarts` axis to a richer author
1532    /// surface (a per-cluster restart-budget override the operator pins
1533    /// through a future `:supervisor :max-restarts-overrides` slot the
1534    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1535    /// a per-tenant restart-budget-alias table the M4 CR materializer
1536    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
1537    /// the future adaptive-supervision engine computes from child-failure-
1538    /// history topology, a promotion of the plain `u32` count to a richer
1539    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1540    /// budget-partition slot comes into scope) would have had to be
1541    /// threaded through every open-coded copy in lockstep or the validate
1542    /// gate and the future M4 emit path would silently disagree on which
1543    /// restart-budget count a given supervisor resolves to — an author's
1544    /// `:max-restarts 5` would satisfy validate while the emit path
1545    /// silently read a drifted other value (a `:max-restarts 10000`
1546    /// no-op supervisor at the emit boundary would carry the author's
1547    /// declared `5` verbatim in `feira lint` output while the future
1548    /// wasm-operator's restart-intensity counter operated under the
1549    /// drifted count), a two-consumer split at the validator far from the
1550    /// source `caixa.lisp` with no field naming the restart-budget-drift
1551    /// root cause. Lifting the resolution rule to a typed method on the
1552    /// substrate primitive means every downstream consumer of the
1553    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1554    /// for exactly one typed dispatch — the resolver's accept-set migrates
1555    /// as a unit on any future axis addition.
1556    ///
1557    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1558    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1559    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1560    /// outlier-detection trip-threshold axis — same "one typed dispatch on
1561    /// the substrate primitive, thin projections at each consumer"
1562    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1563    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1564    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1565    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1566    /// one accessor discipline for the shared substrate concept "a
1567    /// `Copy`-projected required `u32` count that trips the next-higher
1568    /// protection layer after N events in a rolling window" — both are
1569    /// counters with identical degenerate-at-the-high-end shape and share
1570    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1571    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1572    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1573    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1574    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1575    /// the storage field's name verbatim and the peer
1576    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1577    /// accessor's identity maps onto the canonical OTP-shape supervision
1578    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1579    /// already carries.
1580    #[must_use]
1581    pub const fn max_restarts(&self) -> u32 {
1582        self.max_restarts
1583    }
1584
1585    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1586    /// `Period` sliding-window scalar accessor every consumer of the
1587    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1588    /// keys off — returns the author-declared `:supervisor :restart-window`
1589    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1590    /// the typed slot's own `Option<Duration>` storage (`Duration` is
1591    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1592    /// value; no borrow of `&self` past the call). `None` when the slot is
1593    /// absent (the canonical "never reset — every restart across the
1594    /// supervisor's lifetime counts against the sibling `:max-restarts`
1595    /// budget" sentinel the field's own docstring names and the peer
1596    /// `validate_accepts_none_restart_window` pin locks in on the
1597    /// [`SupervisorSpec::validate`] entry-side).
1598    ///
1599    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1600    /// `Period` sliding-observation-interval that pairs with the sibling
1601    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1602    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1603    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1604    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1605    /// default). The typed slot's `Option<Duration>` accept-set —
1606    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1607    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1608    /// `Period > 0`; a zero period either trips on the first failure or
1609    /// never trips depending on operator interpretation, neither of which
1610    /// is the author's intent — omit the slot to express "no reset";
1611    /// carry a positive duration to express the sliding window),
1612    /// integer-millisecond canonical form enforced through
1613    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1614    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1615    /// future wasm-operator's per-supervisor restart-intensity counter
1616    /// quantizes at milliseconds), upper-bounded by
1617    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1618    /// supervisor rolling window any operationally-reachable supervisor
1619    /// can honor without spanning multiple scheduler epochs the
1620    /// hierarchical-reconciliation scheduler treats as independent) —
1621    /// maps onto the future wasm-operator (M3) per-supervisor
1622    /// restart-intensity counter's rolling-observation-interval, the
1623    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1624    /// per-`spec.restartWindow` admission webhook, and the sibling
1625    /// `duration_codec`-serialized wire scalar every downstream consumer
1626    /// of the supervisor's per-`:supervisor` restart-intensity denominator
1627    /// keys off.
1628    ///
1629    /// Prior to this lift the `.restart_window` field was accessed inline
1630    /// at one production site in `caixa-core/src/supervisor.rs` — the
1631    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1632    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1633    /// open-coded field-access that expressed no compile-time link back to
1634    /// the typed slot. A future extension of the `:restart-window` axis to
1635    /// a richer author surface (a per-cluster restart-window override the
1636    /// operator pins through a future `:supervisor :restart-window-overrides`
1637    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1638    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
1639    /// materializer resolves per-CR, a per-supervisor dynamic
1640    /// restart-window derivation the future adaptive-supervision engine
1641    /// computes from child-failure-history topology, a promotion of the
1642    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
1643    /// pair once Erlang/OTP's per-child-cohort observation-interval-
1644    /// partition slot comes into scope) would have had to be threaded
1645    /// through every open-coded copy in lockstep or the validate gate and
1646    /// the future M4 emit path would silently disagree on which
1647    /// restart-window a given supervisor resolves to — an author's
1648    /// `:restart-window "60s"` would satisfy validate while the emit path
1649    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
1650    /// authored slot at the emit boundary would carry the author's
1651    /// declared window verbatim in `feira lint` output while the future
1652    /// wasm-operator's restart-intensity counter operated under a
1653    /// drifted window, or vice versa: an author's `:restart-window ()`
1654    /// would carry the "never reset" sentinel through validate while the
1655    /// emit path silently substituted a default sliding window), a
1656    /// two-consumer split at the validator far from the source
1657    /// `caixa.lisp` with no field naming the restart-window-drift root
1658    /// cause. Lifting the resolution rule to a typed method on the
1659    /// substrate primitive means every downstream consumer of the
1660    /// Supervisor's per-`:supervisor` restart-intensity-denominator
1661    /// surface reaches for exactly one typed dispatch — the resolver's
1662    /// accept-set migrates as a unit on any future axis addition.
1663    ///
1664    /// Third `Copy`-return accessor on the M2 supervisor-slot
1665    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
1666    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
1667    /// payload rather than a `Copy`-scalar, and the per-`:children`
1668    /// [`crate::ChildSpec::nome`] (57c61d0) /
1669    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1670    /// scalar accessors already close the per-element `String`-carry
1671    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
1672    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
1673    /// per-outermost-call wall-clock-deadline axis and the peer M3
1674    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
1675    /// accessor on the `:politicas` slot's per-call-deadline axis — all
1676    /// three share the shared substrate concept "a `Copy`-projected
1677    /// optional `Duration` that carries a positive integer-millisecond
1678    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
1679    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
1680    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
1681    /// bracket-helper the three axes each route through. Named
1682    /// `restart_window()` to match the storage field's name verbatim and
1683    /// the peer [`crate::LimitsSpec::wall_clock`] /
1684    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
1685    /// accessor's identity maps onto the canonical OTP-shape supervision
1686    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
1687    /// already carries.
1688    #[must_use]
1689    pub const fn restart_window(&self) -> Option<Duration> {
1690        self.restart_window
1691    }
1692
1693    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
1694    /// static-child-list slice accessor every consumer that walks the
1695    /// supervisor's declared child set keys off — returns the author-
1696    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
1697    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
1698    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
1699    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
1700    /// through). Non-optional: an empty slice is the load-bearing
1701    /// "author declared `:children ()`" sentinel every consumer of the
1702    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
1703    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
1704    /// three strategies require a non-empty slice — the paired
1705    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
1706    /// [`SupervisorError::NoChildren`] refusal cascade pins the
1707    /// partition on both arms).
1708    ///
1709    /// The `:supervisor :children` slot carries the OTP-shaped static
1710    /// child list the supervisor materializes one ComputeUnit per
1711    /// entry from — the Erlang/OTP `supervisor:init/1`'s
1712    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
1713    /// through the tatara-lisp `:children` author surface onto a typed
1714    /// `Vec<ChildSpec>` whose per-element `(nome(),
1715    /// versao_requirement(), restart)` triple the per-child
1716    /// [`SupervisorSpec::validate`] loop already gates through the
1717    /// lifted [`ChildSpec::nome`] (57c61d0) /
1718    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
1719    /// Every downstream consumer that fans on the static child list
1720    /// keys off this slice (the [`SupervisorSpec::validate`]
1721    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
1722    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
1723    /// per-child DNS-1123 / semver-requirement / duplicate-detection
1724    /// fan-out loop, every future wasm-operator (M3) per-supervisor
1725    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
1726    /// materialization loop, the future M4
1727    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1728    /// admission-webhook fan-out, the future `feira app graph`
1729    /// per-supervisor tree-print traversal).
1730    ///
1731    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
1732    /// inline at three production sites in `caixa-core/src/supervisor.rs`
1733    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
1734    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
1735    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
1736    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
1737    /// validate loop's `for child in &self.children` traversal head —
1738    /// three open-coded field-accesses that expressed no compile-time
1739    /// link back to the typed slot. A future extension of the
1740    /// `:supervisor :children` axis to a richer author surface (a
1741    /// per-cluster child-set overlay the operator pins through a future
1742    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
1743    /// supervision-canary roadmap acknowledges, a per-tenant
1744    /// child-set-alias table the M4 CR materializer resolves per-CR,
1745    /// a per-supervisor dynamic-child derivation the future adaptive-
1746    /// supervision engine computes from child-failure-history topology,
1747    /// a promotion of the plain `Vec<ChildSpec>` to a richer
1748    /// `{static, dynamic}` partition once Erlang/OTP's
1749    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
1750    /// would have had to be threaded through all three open-coded copies
1751    /// in lockstep or one consumer would silently disagree with the
1752    /// peers on which child-set a given supervisor resolves to — the
1753    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
1754    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
1755    /// would silently split the partition-dispatch's two-arm coherence
1756    /// (a supervisor that satisfies neither arm's precondition, or that
1757    /// satisfies both, at the cost of the paired
1758    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
1759    /// silently drifting from the per-child validate loop's actual
1760    /// traversal input), a three-consumer split at the validator far
1761    /// from the source `caixa.lisp` with no field naming the
1762    /// child-set-drift root cause. Lifting the resolution rule to a
1763    /// typed method on the substrate primitive means every downstream
1764    /// consumer of the Supervisor's per-`:supervisor` static-child-list
1765    /// surface reaches for exactly one typed dispatch — the resolver's
1766    /// accept-set migrates as a unit on any future axis addition.
1767    ///
1768    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
1769    /// — the seed for the same "one typed dispatch on the substrate
1770    /// primitive, thin projections at each consumer" discipline the
1771    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
1772    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
1773    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
1774    /// onto the first `Vec`-carry axis on the substrate. The four peer
1775    /// `Vec`-carry axes still unlifted at the time of this seed —
1776    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
1777    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
1778    /// (`Vec<Membro>` per-Aplicacao member list),
1779    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
1780    /// per-Aplicacao WIT-typed edge list),
1781    /// [`crate::UpgradeFromEntry::instructions`]
1782    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
1783    /// — inherit this accessor's discipline as future compounding runs
1784    /// migrate their consumers onto the shared slice-return shape.
1785    /// Fourth (and final) accessor on the M2 supervisor-slot
1786    /// `SupervisorSpec` type, sibling to the three `Copy`-return
1787    /// [`SupervisorSpec::estrategia`] (eafb619) /
1788    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
1789    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
1790    /// the last unlifted per-`:supervisor` field axis (the
1791    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
1792    /// per-`:supervisor` reader now routes through a typed dispatch on
1793    /// the substrate primitive. Named `children()` to match the storage
1794    /// field's name verbatim and the tatara-lisp author-surface term
1795    /// (`:children`) the field's own docstring already carries; the
1796    /// accessor's identity maps onto the canonical OTP-shape
1797    /// supervision vocabulary the [`SupervisorSpec::children`] field's
1798    /// docstring already reaches for ("Static children ..."). Returns
1799    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
1800    /// consumer of the child list treats it as a read-only sequence —
1801    /// the slice-view is the narrowest borrow that supports every
1802    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
1803    /// index, `.len()`) without leaking the backing `Vec`'s
1804    /// grow/push/reserve surface that no consumer of the typed view
1805    /// reaches for (the storage-side `Vec` remains reachable through
1806    /// the `pub children` field for the mutation-carrying
1807    /// `Caixa::supervisor_view` fold-in path in
1808    /// `manifest.rs:supervisor_view`).
1809    #[must_use]
1810    pub const fn children(&self) -> &[ChildSpec] {
1811        self.children.as_slice()
1812    }
1813
1814    /// Validate the supervisor's typed shape — strategy ↔ children
1815    /// invariants, max_restarts > 0, restart_window > 0 when set,
1816    /// per-child non-empty + duplicate-free names.
1817    ///
1818    /// Mirrors the value-shape discipline applied to every other
1819    /// typed slot:
1820    ///
1821    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
1822    ///     same "0 means the opposite of what you think" footgun
1823    ///     closed for `:politicas :timeout` (Envoy interprets a zero
1824    ///     timeout as `infinite`), `:politicas :circuit-breaker
1825    ///     :window`, and `:limits :wall-clock`. The
1826    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
1827    ///     `supervisor` requires `Period > 0`; a zero period either
1828    ///     trips on the first failure or never trips depending on
1829    ///     operator interpretation, neither of which is the
1830    ///     author's intent. Omit `:restart-window` to express "no
1831    ///     reset"; carry a positive duration to express the window.
1832    ///   - duplicate `:children` `:caixa` names are the same
1833    ///     graph-node-set / multiset distinction closed for
1834    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
1835    ///     and `:entrada :paths` (eb3456d). Two children with the
1836    ///     same `:caixa` materialize as two ComputeUnits with the
1837    ///     same name in the cluster's HelmRelease values, one
1838    ///     silently overwriting the other. Erlang/OTP's
1839    ///     `child_spec.id` is required-unique per supervisor;
1840    ///     pleme-io enforces the same set-not-multiset shape on
1841    ///     `:caixa` (the load-bearing identity in our renderer).
1842    pub fn validate(&self) -> Result<(), SupervisorError> {
1843        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
1844        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1845        // error carrier's `estrategia:` field through the lifted
1846        // [`SupervisorSpec::estrategia`] accessor rather than the raw
1847        // `self.estrategia` field access — the two production consumers
1848        // of the per-`:supervisor` sibling-restart-strategy scalar now
1849        // key off exactly one typed dispatch on the substrate primitive,
1850        // so any future rebrand on the axis (a per-cluster strategy
1851        // override the operator pins through a future `:supervisor
1852        // :estrategia-overrides` slot, a per-tenant strategy-alias table
1853        // the M4 CR materializer resolves per-CR) migrates as a single
1854        // caixa-core edit rather than a coordinated rewrite of the two
1855        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
1856        // (921fe1b) four-consumer migration on the per-`:placement`
1857        // distribution-strategy axis.
1858        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
1859        // dispatch's paired `.is_empty()` cross-slot refusal probes
1860        // (the `SimpleOneForOne`-arm
1861        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
1862        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1863        // refusal) through the lifted [`SupervisorSpec::children`]
1864        // slice-return accessor rather than the raw `self.children`
1865        // field access — the two paired production consumers of the
1866        // per-`:supervisor` static-child-list scalar-shape now key off
1867        // exactly one typed dispatch on the substrate primitive, so any
1868        // future rebrand on the axis (a per-cluster child-set overlay
1869        // the operator pins through a future `:supervisor
1870        // :children-overrides` slot, a per-tenant child-set-alias table
1871        // the M4 CR materializer resolves per-CR) migrates as a single
1872        // caixa-core edit rather than a coordinated rewrite of the
1873        // paired arms — first slice-return migration on any typed slot,
1874        // seed for the peer per-`:placement :clusters`,
1875        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
1876        // :instructions` `Vec`-carry axes.
1877        match self.estrategia() {
1878            RestartStrategy::SimpleOneForOne => {
1879                // SimpleOneForOne: children added at runtime. Static
1880                // list must be empty (one shape declared elsewhere).
1881                if !self.children().is_empty() {
1882                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
1883                }
1884            }
1885            _ => {
1886                if self.children().is_empty() {
1887                    return Err(SupervisorError::NoChildren {
1888                        estrategia: self.estrategia(),
1889                    });
1890                }
1891            }
1892        }
1893        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
1894        // axis. See [`crate::render::require_positive_bounded_u32`] for
1895        // the ordering discipline (zero-floor arm strictly precedes cap
1896        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
1897        // diagnostic with its counter-axis remediation directly named,
1898        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
1899        // cap-arm miss). Until this bracket landed the top edge ran all
1900        // the way to `u32::MAX` and a struct-literal
1901        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
1902        // equivalent author-surface `:max-restarts 100000` /
1903        // `:max-restarts 4294967295` typo landing in the slot) silently
1904        // passed validate. The runtime substrate consuming the value
1905        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
1906        // wasm-operator's per-supervisor restart-intensity counter, the
1907        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1908        // admission webhook) then turned a typed `:max-restarts`
1909        // policy into a no-op supervisor: the escalation threshold is
1910        // structurally so high that no realistic
1911        // restarts-per-`:restart-window` traffic shape can reach it,
1912        // the supervisor never escalates to its parent, and a bad
1913        // child can loop inside the window indefinitely with the
1914        // parent supervisor structurally never receiving the "this
1915        // subtree has exceeded its restart budget" signal the typed
1916        // slot is meant to express. The bracket set is
1917        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
1918        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
1919        // the sibling `:politicas :circuit-breaker :max-failures` axis:
1920        // both are "trip the next-higher protection layer after N
1921        // events in a rolling window" counters with identical
1922        // degenerate-at-the-high-end shape and now share one canonical
1923        // bracket helper. The bracket precedes the sibling
1924        // `:restart-window` zero-floor / canonical-millisecond arms so
1925        // an over-cap `max_restarts` paired with a structurally invalid
1926        // window surfaces the bracket diagnostic first, mirroring the
1927        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
1928        // ordering on the peer `:politicas :circuit-breaker` slot.
1929        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
1930        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
1931        // accessor rather than the raw `self.max_restarts` field access —
1932        // the one production consumer of the per-`:supervisor`
1933        // restart-budget-count scalar now keys off exactly one typed
1934        // dispatch on the substrate primitive, so any future rebrand on
1935        // the axis (a per-cluster restart-budget override the operator
1936        // pins through a future `:supervisor :max-restarts-overrides`
1937        // slot, a per-tenant restart-budget-alias table the M4 CR
1938        // materializer resolves per-CR) migrates as a single caixa-core
1939        // edit rather than a coordinated rewrite — sibling of the peer M3
1940        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
1941        // the per-`:politicas :circuit-breaker :max-failures` axis.
1942        crate::render::require_positive_bounded_u32(
1943            self.max_restarts(),
1944            SUPERVISOR_MAX_RESTARTS_MAX,
1945            || SupervisorError::ZeroMaxRestarts,
1946            |max_restarts| SupervisorError::MaxRestartsExceedsCap { max_restarts },
1947        )?;
1948        // Route the [`SupervisorSpec::validate`] `:restart-window`
1949        // zero-floor + integer-millisecond canonical-form + upper-cap
1950        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
1951        // accessor rather than the raw `self.restart_window` field access —
1952        // the one production consumer of the per-`:supervisor`
1953        // restart-intensity-denominator scalar now keys off exactly one
1954        // typed dispatch on the substrate primitive, so any future rebrand
1955        // on the axis (a per-cluster restart-window override the operator
1956        // pins through a future `:supervisor :restart-window-overrides`
1957        // slot, a per-tenant restart-window-alias table the M4 CR
1958        // materializer resolves per-CR) migrates as a single caixa-core
1959        // edit rather than a coordinated rewrite — sibling of the peer M2
1960        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
1961        // on the per-`:limits :wall-clock` axis and the peer M3
1962        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
1963        // per-`:politicas :timeout` axis.
1964        if let Some(w) = self.restart_window() {
1965            // Zero-floor + integer-millisecond canonical-form +
1966            // upper-cap bracket on the typed `:restart-window` axis.
1967            // See
1968            // [`crate::render::require_positive_canonical_bounded_duration`]
1969            // for the full three-arm ordering discipline (zero-floor
1970            // strictly precedes canonical-form so `Duration::ZERO`
1971            // surfaces the self-locating `RestartWindowZero`
1972            // diagnostic; canonical-form strictly precedes the cap arm
1973            // so a sub-millisecond above-cap value surfaces the more
1974            // fundamental round-trip-shape diagnostic first) and the
1975            // three peer typed-`Duration` sites that share this
1976            // canonical bracket ([`crate::MeshPolicy::timeout`],
1977            // [`crate::CircuitBreaker::window`],
1978            // [`crate::LimitsSpec::wall_clock`]). Every validated
1979            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1980            // (1ms..=1h), integer-millisecond granularity.
1981            crate::render::require_positive_canonical_bounded_duration(
1982                w,
1983                SUPERVISOR_RESTART_WINDOW_MAX,
1984                || SupervisorError::RestartWindowZero,
1985                |window| SupervisorError::RestartWindowNotCanonical { window },
1986                |window| SupervisorError::RestartWindowExceedsCap { window },
1987            )?;
1988        }
1989        // Route the per-child DNS-1123 / semver-requirement / duplicate-
1990        // detection fan-out loop through the lifted named per-slot gate
1991        // [`SupervisorSpec::validate_children`] rather than an inline
1992        // three-per-child cascade — every future consumer that wants to
1993        // re-check only the `:children` slot's per-entry axes (the M4
1994        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1995        // admission webhook re-validating one added/renamed child, the
1996        // future wasm-operator's per-child dynamic-add re-validator on
1997        // the `SimpleOneForOne` runtime-add path once dynamic-children
1998        // graduate to a typed slot, a future partial re-validator on a
1999        // per-`:children`-entry patch) reaches every per-entry axis
2000        // through one dispatch rather than re-inlining the three-arm
2001        // cascade in lockstep with `validate` or paying the peer
2002        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2003        // reach one entry check. Sibling of the peer M3 mesh-slot
2004        // per-slot gate family (`validate_membros` — the exact peer on
2005        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2006        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2007        // `validate_placement`; `validate_politicas` routing through
2008        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2009        // per-slot gate discipline now spans both the M3 mesh-slot
2010        // family and the M2 `:children` per-child-cascade axis on one
2011        // shape: one named per-slot gate per typed per-entry loop.
2012        self.validate_children()?;
2013        Ok(())
2014    }
2015
2016    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2017    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2018    /// gate, and duplicate-`:caixa` dedup arm into one call every
2019    /// consumer that wants to re-validate one `:children` entry (or the
2020    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2021    /// admits reaches through.
2022    ///
2023    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2024    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2025    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2026    /// duplicate-`:caixa` dedup), lifted to one named substrate
2027    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2028    /// materializer's admission webhook re-checking one added or renamed
2029    /// child, the future wasm-operator's per-child dynamic-add
2030    /// re-validator on the `SimpleOneForOne` runtime-add path once
2031    /// dynamic-children graduate to a typed slot, a future partial
2032    /// re-validator on a per-`:children`-entry patch — each reaches the
2033    /// three per-entry axes through this one dispatch rather than
2034    /// re-inlining the three-arm cascade in lockstep with `validate`
2035    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2036    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2037    /// reach one entry check.
2038    ///
2039    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2040    /// through [`SupervisorSpec::children`] rather than borrowing one
2041    /// threaded down from `validate`, the same posture the peer M3
2042    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2043    /// [`crate::AplicacaoSpec::validate_contratos`],
2044    /// [`crate::AplicacaoSpec::validate_entrada`],
2045    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2046    /// consumer that reaches this gate directly (without first calling
2047    /// `validate`) still runs the full per-child cascade — pinned by
2048    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2049    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2050    /// + `validate_children_is_self_contained_on_children_slot`.
2051    ///
2052    /// The three per-entry arms run in the same canonical order the
2053    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2054    /// the diagnostic every author-declared per-`:children` entry surfaces
2055    /// through `validate` is byte-equal to the diagnostic this gate
2056    /// surfaces when called directly — the equivalence-pin pair
2057    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2058    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2059    /// asserts the two altitudes discriminate the same set on every
2060    /// per-entry-covered input.
2061    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2062        let mut seen = std::collections::HashSet::new();
2063        for child in self.children() {
2064            // Every emitted cluster artifact's `metadata.name` for a
2065            // supervised child derives from this `:children :caixa` value
2066            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2067            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2068            // label value on every child's pod identity, and the per-
2069            // child K8s [`Service`][svc] `metadata.name` the future
2070            // wasm-operator (M3) provisions for inter-child supervision
2071            // tree wiring. Each apiserver-side schema on each landing
2072            // site enforces the DNS-1123 label rule on admission; a
2073            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2074            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2075            // UUID-shaped mistaken-identity slug) silently passes the
2076            // prior empty-/duplicate-only gate and the failure surfaces
2077            // at `kubectl apply` time as a `metadata.name: Invalid value`
2078            // rejection, far from the source caixa.lisp, with no field
2079            // naming the offending `:children` entry. Lifting the gate
2080            // to caixa-build time mirrors the `:membros :caixa` value-
2081            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2082            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2083            // identifier axis — the supervisor tree's child names —
2084            // through the lifted
2085            // [`crate::render::require_valid_dns_1123_label`] gate the
2086            // seven peer name axes (`:membros :caixa`, `:placement
2087            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2088            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2089            // route through, so drift between the eight axes' accepted
2090            // DNS-1123-label sets is structurally impossible.
2091            //
2092            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2093            crate::render::require_valid_dns_1123_label(
2094                child.nome(),
2095                || SupervisorError::EmptyChildName,
2096                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2097            )?;
2098            // The author surface for `:children :versao` is the same
2099            // Cargo-shaped semver requirement string `:deps :versao` and
2100            // `:membros :versao` carry — and the lacre pipeline resolves
2101            // all three axes through the same
2102            // [`crate::version::parse_requirement`] entry-point. The
2103            // shared [`crate::render::require_valid_versao_requirement`]
2104            // helper brackets the empty-first + parse cascade both peer
2105            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2106            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2107            // :versao`) route through, so drift between the three axes'
2108            // accepted requirement sets is structurally impossible and
2109            // the parse-side no-op the empty-first arm closes (semver's
2110            // empty parse yields an implicit `*`) lives in exactly one
2111            // predicate. Every `ChildSpec::versao` past validate is
2112            // round-trippable through [`crate::parse_requirement`]
2113            // without re-checking at the resolver layer, and the three
2114            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2115            // are now structurally equivalent by construction.
2116            crate::render::require_valid_versao_requirement(
2117                child.versao_requirement(),
2118                || SupervisorError::empty_child_version(child.nome()),
2119                |reason| {
2120                    SupervisorError::child_versao_invalid(
2121                        child.nome(),
2122                        child.versao_requirement(),
2123                        reason,
2124                    )
2125                },
2126            )?;
2127            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2128                SupervisorError::duplicate_child_caixa(child.nome())
2129            })?;
2130        }
2131        Ok(())
2132    }
2133}
2134
2135/// Cross-slot coherence gate on the supervision tree: no
2136/// `:children :caixa` entry may name the supervisor's own `:nome`.
2137///
2138/// A supervisor that lists itself as a child is a degenerate self-parent
2139/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2140/// specs reference *distinct* child processes; a supervisor is never its
2141/// own child), and the wasm-operator's hierarchical reconciliation would
2142/// otherwise be handed a node that is its own parent: a one-node cycle it
2143/// either rejects far from the source `caixa.lisp` or recurses on. Because
2144/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2145/// lacre closure root), a child whose `:caixa` equals the supervisor's
2146/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2147///
2148/// Lives outside [`SupervisorSpec::validate`] because the typed view
2149/// carries the children but not the parent `:nome`; mirrors the
2150/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2151/// (which likewise reads one slot against another at the
2152/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2153/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2154/// node to itself is structurally not a tree/mesh edge" discipline, here
2155/// on the supervision-tree axis.
2156pub fn validate_no_self_supervision(
2157    children: &[ChildSpec],
2158    parent_nome: &str,
2159) -> Result<(), SupervisorError> {
2160    for child in children {
2161        if child.nome() == parent_nome {
2162            return Err(SupervisorError::child_supervises_self(parent_nome));
2163        }
2164    }
2165    Ok(())
2166}
2167
2168#[derive(Debug, Error, PartialEq, Eq)]
2169pub enum SupervisorError {
2170    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2171    NoChildren { estrategia: RestartStrategy },
2172    #[error(
2173        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2174    )]
2175    SimpleOneForOneWithStaticChildren,
2176    #[error(":max-restarts must be > 0")]
2177    ZeroMaxRestarts,
2178    #[error(
2179        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2180         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2181         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2182         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2183         can reach it, so the supervisor never escalates to its parent and a bad child can \
2184         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2185         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2186         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2187         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2188         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2189         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2190         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2191         band) or restructure the supervision tree (split the flaky child into its own \
2192         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2193    )]
2194    MaxRestartsExceedsCap { max_restarts: u32 },
2195    #[error(
2196        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2197         requires Period > 0; a zero window either trips on the first failure or \
2198         never trips depending on operator interpretation. Omit :restart-window to \
2199         express `never reset`; carry a positive duration to express the window."
2200    )]
2201    RestartWindowZero,
2202    #[error(
2203        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2204         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2205         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2206         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2207         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2208    )]
2209    RestartWindowNotCanonical { window: Duration },
2210    #[error(
2211        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2212         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2213         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2214         failure-counting window is structurally so long that transient restarts are never \
2215         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2216         when the child has exceeded its restart budget within the recent window` to `trip the \
2217         parent when the child has exceeded its restart budget over its lifetime`, and the \
2218         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2219         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2220         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2221         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2222         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2223         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2224         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2225         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2226         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2227         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2228         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2229         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2230         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2231         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2232         hiding it behind a rolling-window declaration the cap arm rejects)"
2233    )]
2234    RestartWindowExceedsCap { window: Duration },
2235    #[error("child entry has empty :caixa name")]
2236    EmptyChildName,
2237    #[error(
2238        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2239         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2240         name / label value the child name lands in — the per-child \
2241         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2242         label value, and the future wasm-operator per-child Service `metadata.name` \
2243         — each apiserver-side schema rejects names that don't match; use a \
2244         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2245    )]
2246    ChildCaixaInvalid { caixa: String, reason: String },
2247    #[error("child {caixa:?} has empty :versao constraint")]
2248    EmptyChildVersion { caixa: String },
2249    #[error(
2250        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2251         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2252         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2253         `:membros :versao` carry; the lacre pipeline resolves all three \
2254         through the same parser)"
2255    )]
2256    ChildVersaoInvalid {
2257        caixa: String,
2258        versao: String,
2259        reason: String,
2260    },
2261    #[error(
2262        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2263         child_spec.id per supervisor; duplicate children materialize as duplicate \
2264         ComputeUnits in the rendered chart, one silently overwriting the other)"
2265    )]
2266    DuplicateChildCaixa { caixa: String },
2267    #[error(
2268        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2269         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2270         OTP child specs reference distinct child processes). Since every :nome is a \
2271         globally-unique substrate identity, a child naming the supervisor's own :nome \
2272         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2273         self-referential :children entry or rename it to the actual child caixa."
2274    )]
2275    ChildSupervisesSelf { caixa: String },
2276}
2277
2278// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2279// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2280// and [`validate_no_self_supervision`] onto one substrate primitive per
2281// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2282// `LayoutError`-envelope constructor families the peer
2283// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2284// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2285// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2286// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2287// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2288// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2289// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2290// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2291// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2292// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2293// variants on `{ de, para }`) already at that discipline on the peer
2294// `AplicacaoError` envelopes.
2295//
2296// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2297// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2298// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2299// self-supervision arm) opened the identical
2300// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2301// the exact "same block re-inlined at every consumer" shape the PRIME
2302// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2303// `AplicacaoError` families each closed on their sibling envelopes. The
2304// three variants share one `{ caixa: String }` shape, so the fold routes
2305// each wire-up site through one dispatch per typed variant.
2306//
2307// The macro below generates one static constructor per variant of shape
2308// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2309// collapses onto one dispatch:
2310// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2311// struct-literal on the same `&str` fixture. The uniform one-field
2312// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2313// macro — rather than at every wire-up site. Every constructor is
2314// `#[must_use]` so a caller who mistakenly discards the constructed error
2315// trips a compile warning at the wire-up site.
2316//
2317// Every future consumer that wants to construct one of these three
2318// variants outside `SupervisorSpec::validate_children` /
2319// `validate_no_self_supervision` — a deferred
2320// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2321// webhook re-checking one added/renamed child, a future
2322// `feira validate --supervisor` per-caixa admission verb, a per-child
2323// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2324// once dynamic-children graduate to a typed slot, a per-Supervisor
2325// overlay resolver rejecting a duplicate/self-supervising child against
2326// a cluster-local snapshot — now reaches each variant through one call
2327// rather than re-inlining the three-line struct-literal in lockstep
2328// with the three in-crate wire-up sites.
2329macro_rules! supervisor_caixa_only_ctors {
2330    ($($ctor:ident => $variant:ident),* $(,)?) => {
2331        impl SupervisorError {
2332            $(
2333                #[doc = concat!(
2334                    "Construct a [`SupervisorError::",
2335                    stringify!($variant),
2336                    "`] naming the offending `:children :caixa` (or ",
2337                    "supervisor `:nome`, on the self-supervision arm). ",
2338                    "Folds the uniform `Self::",
2339                    stringify!($variant),
2340                    " { caixa: caixa.to_string() }` one-field ",
2341                    "struct-literal onto one substrate primitive so ",
2342                    "every [`SupervisorSpec::validate_children`] / ",
2343                    "[`validate_no_self_supervision`] wire-up on this ",
2344                    "variant reads through one dispatch rather than the ",
2345                    "pre-lift open-coded struct-literal block."
2346                )]
2347                #[must_use]
2348                pub fn $ctor(caixa: &str) -> Self {
2349                    Self::$variant { caixa: caixa.to_string() }
2350                }
2351            )*
2352        }
2353    };
2354}
2355
2356supervisor_caixa_only_ctors! {
2357    empty_child_version => EmptyChildVersion,
2358    duplicate_child_caixa => DuplicateChildCaixa,
2359    child_supervises_self => ChildSupervisesSelf,
2360}
2361
2362// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2363// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2364// one substrate primitive per typed variant — the M2 supervisor-side siblings
2365// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2366// already lifted through the sibling
2367// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2368// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2369// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2370// String }` two-slot shape the peer seven-variant
2371// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2372// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2373// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2374// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2375// variant carries the `{ caixa: String, versao: String, reason: String }`
2376// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2377// carries on the same `:versao` value-shape.
2378//
2379// Each of the two wire-up sites opened the same closure-shaped
2380// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2381// [versao: child.versao_requirement().to_string(),] reason }` block inside
2382// the paired [`crate::render::require_valid_dns_1123_label`] and
2383// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2384// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2385// as a bug, on the same altitude the peer `AplicacaoError` /
2386// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2387// families already closed on their sibling envelopes.
2388//
2389// The two `#[must_use]` inherent constructors below fold each wire-up onto
2390// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2391// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2392// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2393// The uniform per-field `.to_string()` / `.into()` construction is spelled
2394// once — inside each ctor body — rather than at every wire-up site. The
2395// `reason: impl Into<String>` bound accepts both `&str` literals and
2396// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2397// diagnostic shape at the lift, matching the peer
2398// [`aplicacao_field_reason_ctors!`] and
2399// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2400// sibling envelopes.
2401//
2402// Every future consumer that wants to construct one of these two variants
2403// outside `SupervisorSpec::validate_children` — a deferred
2404// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2405// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2406// `feira validate --supervisor` per-caixa admission verb, a per-child
2407// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2408// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2409// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2410// cluster-local snapshot — now reaches each variant through one call rather
2411// than re-inlining the per-shape struct-literal block in lockstep with the
2412// two in-crate wire-up sites.
2413impl SupervisorError {
2414    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2415    /// offending `:children :caixa` value under the given `reason`. Folds
2416    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2417    /// reason: reason.into() }` two-slot struct-literal onto one substrate
2418    /// primitive so every wire-up on this variant reads through one
2419    /// dispatch, matching the peer
2420    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2421    /// sibling `AplicacaoError { caixa: String, reason: String }`
2422    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2423    /// outputs through the `impl Into<String>` bound.
2424    #[must_use]
2425    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2426        Self::ChildCaixaInvalid {
2427            caixa: caixa.to_string(),
2428            reason: reason.into(),
2429        }
2430    }
2431
2432    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2433    /// offending `:children :caixa` and its `:versao` requirement under
2434    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2435    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2436    /// reason.into() }` three-slot struct-literal onto one substrate
2437    /// primitive so every wire-up on this variant reads through one
2438    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2439    /// { caixa, versao, reason }` three-slot axis on the peer
2440    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2441    /// and `format!(…)` outputs through the `impl Into<String>` bound.
2442    #[must_use]
2443    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2444        Self::ChildVersaoInvalid {
2445            caixa: caixa.to_string(),
2446            versao: versao.to_string(),
2447            reason: reason.into(),
2448        }
2449    }
2450}
2451
2452/// Shared duration string codec for the typed slots that take a
2453/// duration (`restart_window`, `MeshPolicy::timeout`,
2454/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2455/// reuse it without duplicating the parser.
2456pub mod duration_codec {
2457    use super::Duration;
2458    use serde::{Deserializer, Serializer};
2459
2460    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2461        // Route through the canonical [`crate::render::serialize_option_via_str`]
2462        // — the substrate-side single-owner primitive for the forward
2463        // arm of the typed-magnitude codec family. See its docstring
2464        // for the full sibling roster.
2465        crate::render::serialize_option_via_str(v, s, render)
2466    }
2467
2468    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2469        // Route through the canonical [`crate::render::deserialize_option_via_str`]
2470        // — the substrate-side single-owner primitive for the reverse
2471        // arm of the typed-magnitude codec family. See its docstring
2472        // for the full sibling roster.
2473        crate::render::deserialize_option_via_str(d, parse)
2474    }
2475
2476    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2477        // Paired whitespace-rejection arm — same canonical-form
2478        // render-determinism discipline as the peer
2479        // `limits::parse_byte_size` / `limits::parse_duration` /
2480        // `limits::parse_millicores` /
2481        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2482        // byte-scan closes the WhatWG-conformant whitespace bytes
2483        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2484        // `char::is_whitespace` scan closes the strictly-complementary
2485        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2486        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2487        // codepoints) that `str::trim` at parse entry silently strips.
2488        // Either drift class would round-trip through `render` to a
2489        // *different* canonical form on next emit — breaking the
2490        // THEORY.md Part V render-determinism contract on three typed-
2491        // duration slots at once (`:supervisor :restart-window`,
2492        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2493        // via the shared codec.
2494        //
2495        // Routed through the lifted [`crate::render::reject_whitespace`]
2496        // primitive — the substrate-side single-owner paired-arm gate
2497        // every typed-magnitude codec in caixa-core shares.
2498        crate::render::reject_whitespace::<String, _, _>(
2499            s,
2500            |b| {
2501                format!(
2502                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2503                 authoring form for the typed duration slots routed through this shared codec \
2504                 (`:supervisor :restart-window`, `:politicas :timeout`, \
2505                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2506                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2507                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2508                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2509                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2510                 Part V render-determinism contract every typed slot carries. Strip every \
2511                 whitespace byte (write `\"30s\"` verbatim)"
2512                )
2513            },
2514            |ch| {
2515                format!(
2516                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2517                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2518                 duration slots routed through this shared codec (`:supervisor \
2519                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2520                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2521                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2522                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2523                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2524                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2525                 `White_Space` property, strictly wider than the ASCII byte set) silently \
2526                 strips it at parse entry, and the value round-trips through `render` to \
2527                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2528                 the THEORY.md Part V render-determinism contract every typed slot \
2529                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2530                 verbatim with only ASCII bytes)",
2531                    cp = ch as u32
2532                )
2533            },
2534        )?;
2535        let s = s.trim();
2536        // Routed through the lifted
2537        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
2538        // the single-owner split every ASCII-alphabetic-unit typed-
2539        // magnitude codec in caixa-core (`limits::parse_byte_size` /
2540        // `limits::parse_duration` / this shared duration codec) shares.
2541        // See its docstring for the full sibling roster on the same
2542        // primitive altitude.
2543        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
2544        let num_trim = num_part.trim();
2545        // The canonical authoring form for every typed slot routed
2546        // through this shared codec — `:supervisor :restart-window`,
2547        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
2548        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
2549        // non-negative integer with no decimal point and no leading
2550        // sign, so the parser's accepted set must match for
2551        // serialize/deserialize to round-trip without canonical-form
2552        // drift. Until this gate landed the parser accepted any
2553        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
2554        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
2555        // tripped the value to a *different* canonical string on the
2556        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
2557        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
2558        // — breaking the THEORY.md Part V render-determinism contract
2559        // on three typed slots at once. Same canonical-form discipline
2560        // `crate::limits::parse_duration` (818dd38, the immediate
2561        // predecessor on the peer `:limits :wall-clock` codec) applies;
2562        // this gate lifts the discipline onto the shared codec that
2563        // backs the remaining three typed-duration slots in caixa-core.
2564        //
2565        // Strict canonical form: every byte of the magnitude is an
2566        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
2567        // inputs the gate distinguishes "non-canonical-but-numeric"
2568        // (parses as f64 or i64 — surfaced with a self-locating
2569        // diagnostic naming the canonical authoring form, the
2570        // round-trip drift each rejected shape would produce on first
2571        // serialize, and the canonical-form remediation) from
2572        // "garbage" (parses as neither — surfaced with the existing
2573        // narrower "bad duration magnitude" wording so its diagnostic
2574        // shape remains stable for the parser-shape footgun case).
2575        // The pre-existing `num < 0.0` arm is now unreachable — the
2576        // digit-only gate strictly precedes magnitude parsing, and a
2577        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
2578        // non-canonical-but-numeric branch with the `-30` named
2579        // verbatim in the diagnostic rather than the prior
2580        // value-laundered "negative duration in \"-30s\"" wording.
2581        //
2582        // Routed through the lifted
2583        // [`crate::render::is_digit_only_magnitude`] predicate — the
2584        // same source of truth the four peer typed-magnitude codec
2585        // sites share.
2586        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
2587        if !digit_only {
2588            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
2589            if numeric {
2590                return Err(format!(
2591                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
2592                     canonical authoring form for the typed duration slots routed through \
2593                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2594                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2595                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
2596                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
2597                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
2598                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
2599                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
2600                     THEORY.md Part V render-determinism contract every typed slot carries. \
2601                     Pick an integer magnitude in the unit that divides cleanly (write \
2602                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
2603                ));
2604            }
2605            return Err(format!("bad duration magnitude in {s:?}"));
2606        }
2607        // Leading-zero arm — peer with the `rate_limit_codec` leading-
2608        // zero arm (4f46830) on the same canonical-form render-
2609        // determinism axis. The digit-only gate accepts `"030s"`,
2610        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
2611        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
2612        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
2613        // *different* canonical string on the next emit, breaking the
2614        // THEORY.md Part V render-determinism contract the same way
2615        // `"+30s"` did before the leading-`+` arm landed. The single-
2616        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
2617        // losslessly through `render` (`render(Duration::ZERO)` emits
2618        // `"0s"`) — the downstream semantic-zero gates (e.g.
2619        // `SupervisorError::ZeroRestartWindow` on
2620        // `:supervisor :restart-window`,
2621        // `AplicacaoError::PolicyTimeoutZero` /
2622        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
2623        // duration slots) refuse zero-magnitude authoring at the typed-
2624        // validate layer above, so the single-byte `"0"` stays in the
2625        // accepted set at this codec layer and the diagnostic
2626        // partitioning between canonical-form drift (this arm) and
2627        // semantic-zero (the downstream gates) remains stable.
2628        // Peer with the future leading-zero arms on the two remaining
2629        // typed-magnitude codecs the trajectory acknowledges:
2630        // `limits::parse_duration` backing `:limits :wall-clock`,
2631        // `limits::parse_byte_size` backing `:limits :memory` — each
2632        // carries the same canonical-form-drift class today; this
2633        // gate lands the discipline on the shared duration codec
2634        // first because the `rate_limit_codec` predecessor on the
2635        // same canonical-form-drift axis is the closest peer on the
2636        // trajectory.
2637        //
2638        // Routed through the lifted
2639        // [`crate::render::is_leading_zero_padded_magnitude`]
2640        // predicate — the same source of truth the four peer
2641        // typed-magnitude codec sites share.
2642        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
2643            return Err(format!(
2644                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
2645                 canonical authoring form for the typed duration slots routed through \
2646                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2647                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2648                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
2649                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
2650                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
2651                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
2652                 serialize — breaking the THEORY.md Part V render-determinism contract \
2653                 every typed slot carries. Strip the leading zeros (write \
2654                 `\"30s\"` instead of `\"030s\"`)"
2655            ));
2656        }
2657        // The digit-only gate guarantees every byte is `[0-9]`, and
2658        // the leading-zero arm above guarantees the magnitude is
2659        // either the single byte `"0"` or starts with `[1-9]`, so
2660        // the only way `u64::from_str` can fail here is overflow (the
2661        // magnitude exceeds `u64::MAX`). Surface that with an
2662        // overflow-shaped wording so the diagnostic names the offending
2663        // magnitude verbatim rather than collapsing onto the
2664        // non-canonical arm. The codec now operates on `u64` end-to-end
2665        // — every accepted magnitude is integer-exact; no f64 mantissa
2666        // drift between author-supplied magnitude and the consumer's
2667        // `Duration` value. Same shape `crate::limits::parse_duration`
2668        // (818dd38) carries on the peer `:limits :wall-clock` axis.
2669        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
2670            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
2671        })?;
2672        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
2673        // unit-arm dispatch through the canonical
2674        // [`crate::render::duration_from_integer_magnitude_and_unit`]
2675        // primitive — the substrate-side single-owner unit-dispatch
2676        // table every typed-duration codec in caixa-core routes
2677        // through (peer: `crate::limits::parse_duration` backing
2678        // `:limits :wall-clock`). Every unit conversion is integer-
2679        // exact for an integer magnitude; overflow surfaces via the
2680        // typed `DurationUnitError::Overflow { multiplier }`
2681        // discriminant so this arm reconstructs the pre-lift
2682        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
2683        // wording verbatim from `num` / `unit_trim` / the returned
2684        // `multiplier`, and the unknown-unit arm reconstructs the
2685        // pre-lift `"unknown duration unit \"<other>\""` wording from
2686        // the caller-scoped `unit_trim`. Load-bearing pinned by
2687        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
2688        let unit_trim = unit.trim();
2689        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
2690            |e| match e {
2691                crate::render::DurationUnitError::Overflow { multiplier } => format!(
2692                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
2693                ),
2694                crate::render::DurationUnitError::UnknownUnit => {
2695                    format!("unknown duration unit {unit_trim:?}")
2696                }
2697            },
2698        )?;
2699        Ok(dur)
2700    }
2701
2702    /// Render a [`Duration`] in the canonical pleme-io duration string
2703    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
2704    /// caixa typed-duration slot serializes to and the same form K8s
2705    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
2706    /// EnvoyConfig per-route timeouts both expect (an integer
2707    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
2708    /// `+`). Lifted to `pub` so caixa-side renderers
2709    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
2710    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
2711    /// emitter, the future caixa-otel collector pipeline emitter) can
2712    /// consume the same canonical formatter without re-inlining the
2713    /// magnitude/unit decision tree (and inheriting the same drift
2714    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
2715    /// downstream apply-time parsing in non-obvious ways).
2716    pub fn render(d: Duration) -> String {
2717        let total_ms = d.as_millis();
2718        if total_ms == 0 {
2719            return "0s".into();
2720        }
2721        if total_ms.is_multiple_of(3600 * 1000) {
2722            return format!("{}h", total_ms / (3600 * 1000));
2723        }
2724        if total_ms.is_multiple_of(60 * 1000) {
2725            return format!("{}m", total_ms / (60 * 1000));
2726        }
2727        if total_ms.is_multiple_of(1000) {
2728            return format!("{}s", total_ms / 1000);
2729        }
2730        format!("{total_ms}ms")
2731    }
2732
2733    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
2734    ///
2735    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
2736    /// largest divisor unit, so any sub-millisecond residue
2737    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
2738    /// §V.2.7 render-determinism contract:
2739    ///
2740    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
2741    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
2742    ///     `1_000_000` ns ≠ original `1_500_000` ns;
2743    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
2744    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
2745    ///     on every typed-`Duration` slot then rejects on re-validate.
2746    ///
2747    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
2748    /// the codec's round-trippable accepted set lives in exactly one place —
2749    /// every typed-`Duration` slot that routes through this shared codec
2750    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
2751    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
2752    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
2753    /// every typed-`Duration` slot whose own codec shares the same
2754    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
2755    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
2756    /// pair) calls this predicate from its `validate()` to bracket the
2757    /// accepted set against the codec's accepted set, structurally. Drift
2758    /// between the codec's granularity and any typed slot's accepted set is
2759    /// then a single-source-of-truth edit at this predicate rather than a
2760    /// silent round-trip break the next consumer discovers at apply time.
2761    ///
2762    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
2763    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
2764    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
2765    /// family — same "typed-slot's valid set matches its codec's accepted
2766    /// set, structurally" discipline carried at the codec layer.
2767    #[must_use]
2768    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
2769        d.subsec_nanos().is_multiple_of(1_000_000)
2770    }
2771}
2772
2773/// Required-Duration variant for fields that aren't Option<Duration>.
2774pub mod duration_codec_required {
2775    use super::Duration;
2776    use serde::{Deserialize, Deserializer, Serializer};
2777
2778    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
2779        s.serialize_str(&super::duration_codec::render(*v))
2780    }
2781
2782    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
2783        let s = String::deserialize(d)?;
2784        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
2785    }
2786}
2787
2788#[cfg(test)]
2789mod tests {
2790    use super::*;
2791
2792    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
2793        ChildSpec {
2794            caixa: name.into(),
2795            versao: ver.into(),
2796            restart,
2797        }
2798    }
2799
2800    #[test]
2801    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
2802        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
2803        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
2804        // posture. Each accessor projects the per-`:children :caixa`
2805        // / per-`:children :versao` [`String`] storage through the
2806        // `pub const fn` [`String::as_str`] (const-stable since Rust
2807        // 1.87, well within the workspace MSRV) — any future
2808        // accidental downgrade to non-`const` fails the corresponding
2809        // `<name>_via_const_fn` wrapper at caixa-core build time with
2810        // E0015 (`cannot call non-const method`), strictly stronger
2811        // than a runtime `assert!`. Sibling of the peer
2812        // per-M2/M3/universal-axis `String → &str` scalar-accessor
2813        // family pins on the sibling `const`-eval-surface passes
2814        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
2815        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
2816        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
2817        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
2818        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
2819        // [`crate::aplicacao::Entrada::destination`] at the M3
2820        // ingress axis,
2821        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
2822        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
2823        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
2824        // axis, and the per-`:contratos`
2825        // [`crate::aplicacao::WitContract::source`] /
2826        // [`crate::aplicacao::WitContract::destination`] /
2827        // [`crate::aplicacao::WitContract::world_ref`] trio the
2828        // sibling pin at 279823b already anchors).
2829        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
2830            c.nome()
2831        }
2832        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
2833            c.versao_requirement()
2834        }
2835        for (caixa, versao) in [
2836            ("worker-a", "^0.1"),
2837            ("worker-b", "~0.2.3"),
2838            ("collector", "*"),
2839        ] {
2840            let c = child(caixa, versao, RestartPolicy::Permanent);
2841            assert_eq!(nome_via_const_fn(&c), c.nome());
2842            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
2843            assert_eq!(c.nome(), caixa);
2844            assert_eq!(c.versao_requirement(), versao);
2845        }
2846    }
2847
2848    #[test]
2849    fn supervisor_children_slice_return_accessor_is_const_fn() {
2850        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
2851        // `const`-eval-surface posture. The accessor destructures the
2852        // per-`:children` `Vec<ChildSpec>` storage through the
2853        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
2854        // 1.66, well within the workspace MSRV) — any future
2855        // accidental downgrade to non-`const` fails
2856        // `children_via_const_fn` at caixa-core build time with E0015
2857        // (`cannot call non-const method`), strictly stronger than a
2858        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
2859        // `Vec → &[T]` slice-return accessor family pin
2860        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
2861        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
2862        // per-`:membros` / per-`:contratos` slice-return axes, and of
2863        // the peer M2 upgrade-appup axis pin
2864        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
2865        // on the per-`:upgrade-from :instructions` slice-return axis.
2866        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
2867            s.children()
2868        }
2869        // Sweep both the empty-children (leaf-supervisor with no
2870        // static children — the `SimpleOneForOne` dynamic-child
2871        // arm's canonical shape) and the populated-children
2872        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
2873        // arm's canonical shape) axes so the accessor carries a
2874        // const-dispatch pin on both arms.
2875        let s_empty = SupervisorSpec {
2876            estrategia: RestartStrategy::SimpleOneForOne,
2877            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2878            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2879            children: vec![],
2880        };
2881        assert!(children_via_const_fn(&s_empty).is_empty());
2882        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
2883        let s_full = SupervisorSpec {
2884            estrategia: RestartStrategy::OneForOne,
2885            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2886            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2887            children: vec![
2888                child("worker-a", "^0.1", RestartPolicy::Permanent),
2889                child("worker-b", "~0.2.3", RestartPolicy::Transient),
2890                child("collector", "*", RestartPolicy::Temporary),
2891            ],
2892        };
2893        assert_eq!(children_via_const_fn(&s_full).len(), 3);
2894        assert_eq!(children_via_const_fn(&s_full), s_full.children());
2895    }
2896
2897    #[test]
2898    fn default_has_one_for_one_and_5_restarts_in_60s() {
2899        let s = SupervisorSpec::default();
2900        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
2901        assert_eq!(s.max_restarts, 5);
2902        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
2903        assert!(s.children.is_empty());
2904    }
2905
2906    #[test]
2907    fn validate_one_for_one_requires_children() {
2908        let mut s = SupervisorSpec::default();
2909        s.children = vec![];
2910        assert!(matches!(
2911            s.validate().unwrap_err(),
2912            SupervisorError::NoChildren { .. }
2913        ));
2914        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
2915        s.validate().unwrap();
2916    }
2917
2918    #[test]
2919    fn validate_simple_one_for_one_forbids_static_children() {
2920        let mut s = SupervisorSpec {
2921            estrategia: RestartStrategy::SimpleOneForOne,
2922            ..SupervisorSpec::default()
2923        };
2924        s.children
2925            .push(child("w", "^0.1", RestartPolicy::Permanent));
2926        assert_eq!(
2927            s.validate().unwrap_err(),
2928            SupervisorError::SimpleOneForOneWithStaticChildren
2929        );
2930        s.children.clear();
2931        s.validate().unwrap();
2932    }
2933
2934    #[test]
2935    fn validate_rejects_zero_max_restarts() {
2936        let s = SupervisorSpec {
2937            max_restarts: 0,
2938            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2939            ..SupervisorSpec::default()
2940        };
2941        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
2942    }
2943
2944    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
2945    //
2946    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
2947    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
2948    // `:supervisor :max-restarts` axis — both fields are "trip the
2949    // next-higher protection layer after N events in a rolling window"
2950    // counters with identical degenerate-at-the-high-end shape, so the
2951    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
2952    // exactly as it lies in `1..=1000` on the breaker side.
2953
2954    #[test]
2955    fn validate_rejects_max_restarts_above_cap() {
2956        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
2957        // 1` is structurally one past the cap and silently passed
2958        // validate on every pre-gate codebase because the typed slot's
2959        // only check was the zero-floor arm. The no-op-supervisor vector
2960        // only surfaced at the runtime substrate (Erlang/OTP
2961        // MaxIntensity/Period ratio, the future wasm-operator's
2962        // per-supervisor restart-intensity counter) far from the source
2963        // caixa.lisp with no field naming the offending supervisor.
2964        let s = SupervisorSpec {
2965            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2966            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2967            ..SupervisorSpec::default()
2968        };
2969        assert_eq!(
2970            s.validate().unwrap_err(),
2971            SupervisorError::MaxRestartsExceedsCap {
2972                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2973            }
2974        );
2975    }
2976
2977    #[test]
2978    fn validate_rejects_max_restarts_far_above_cap() {
2979        // The `u32::MAX` worst case — the four-billion-restart
2980        // threshold a typo (`:max-restarts 4294967295`) or a
2981        // struct-literal copy-paste lands in the slot. Pin the cap
2982        // arm's coverage explicitly across the full `u32` overflow so
2983        // a future relaxation that drops the upper bound surfaces
2984        // here. Same shape every other typed-cap arm on this surface
2985        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
2986        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
2987        let s = SupervisorSpec {
2988            max_restarts: u32::MAX,
2989            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2990            ..SupervisorSpec::default()
2991        };
2992        assert_eq!(
2993            s.validate().unwrap_err(),
2994            SupervisorError::MaxRestartsExceedsCap {
2995                max_restarts: u32::MAX,
2996            }
2997        );
2998    }
2999
3000    #[test]
3001    fn validate_accepts_max_restarts_at_cap() {
3002        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3003        // must validate. The cap is inclusive on the top edge,
3004        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3005        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3006        // discipline on the sibling capped axes. Pin the boundary
3007        // explicitly so a future off-by-one tightening
3008        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3009        // here as a test failure rather than a silent contract
3010        // narrowing.
3011        let s = SupervisorSpec {
3012            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3013            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3014            ..SupervisorSpec::default()
3015        };
3016        s.validate()
3017            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3018    }
3019
3020    #[test]
3021    fn validate_accepts_max_restarts_typical_values() {
3022        // The documented production-playbook band positive-control
3023        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3024        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3025        // through the hyperscale band (200, 500, 1000) the cap
3026        // accepts. Pin the inclusive validated set explicitly so a
3027        // future tightening of the ceiling surfaces here.
3028        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3029            let s = SupervisorSpec {
3030                max_restarts: n,
3031                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3032                ..SupervisorSpec::default()
3033            };
3034            s.validate()
3035                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3036        }
3037    }
3038
3039    #[test]
3040    fn zero_max_restarts_takes_precedence_over_cap() {
3041        // The cross-arm ordering pin: `0` is structurally outside
3042        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3043        // (cap), but the zero-floor diagnostic is the more
3044        // self-locating one (it directly names the counter-axis
3045        // remediation), so the validate gate must fire on zero first.
3046        // Same shape every other zero-then-shape ordering on this
3047        // surface uses (PolicyRetriesZero then
3048        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3049        // PolicyBreakerMaxFailuresExceedsCap).
3050        let s = SupervisorSpec {
3051            max_restarts: 0,
3052            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3053            ..SupervisorSpec::default()
3054        };
3055        assert_eq!(
3056            s.validate().unwrap_err(),
3057            SupervisorError::ZeroMaxRestarts,
3058            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3059        );
3060    }
3061
3062    #[test]
3063    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3064        // The cross-arm ordering pin between the cap and the sibling
3065        // `:restart-window` gates (zero-window, canonical-window). A
3066        // supervisor carrying both an over-cap `max_restarts` AND a
3067        // structurally invalid window (zero, sub-ms) must surface the
3068        // cap diagnostic first — the cap arm is wired immediately
3069        // after the zero-restart arm and strictly before the window
3070        // arms, so the offending value the diagnostic names matches
3071        // the order the author would discover the gates by reading
3072        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3073        // order so a future refactor that reorders the arms surfaces
3074        // here as a test failure rather than a silent diagnostic
3075        // regression. Peer of
3076        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3077        // on the sibling `:politicas :circuit-breaker` slot.
3078        let s = SupervisorSpec {
3079            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3080            restart_window: Some(Duration::ZERO),
3081            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3082            ..SupervisorSpec::default()
3083        };
3084        assert_eq!(
3085            s.validate().unwrap_err(),
3086            SupervisorError::MaxRestartsExceedsCap {
3087                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3088            },
3089            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3090        );
3091    }
3092
3093    #[test]
3094    fn max_restarts_cap_diagnostic_carries_offending_value() {
3095        // The diagnostic-shape pin: the offending `u32` is carried
3096        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3097        // variant so the surfaced error message names the value the
3098        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3099        // supervisor-policy ceiling …"`), not just the cap. Same
3100        // self-locating diagnostic shape every other typed-cap arm on
3101        // this surface carries
3102        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3103        // the offending failure count verbatim,
3104        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3105        // retries count verbatim).
3106        let s = SupervisorSpec {
3107            max_restarts: 50_000,
3108            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3109            ..SupervisorSpec::default()
3110        };
3111        let err = s.validate().unwrap_err();
3112        assert!(
3113            matches!(
3114                err,
3115                SupervisorError::MaxRestartsExceedsCap {
3116                    max_restarts: 50_000
3117                }
3118            ),
3119            "got {err:?}"
3120        );
3121        let msg = err.to_string();
3122        assert!(
3123            msg.contains("50000"),
3124            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3125        );
3126    }
3127
3128    #[test]
3129    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3130        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3131        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3132        // half of Learn You Some Erlang's worker-supervisor default,
3133        // sibling of the `60s` `Period` half that the paired
3134        // [`Default for SupervisorSpec`] impl already pins on the
3135        // sibling `restart_window` axis. Pinning the literal here
3136        // surfaces a future rebrand (a tightening to Elixir's `3`,
3137        // a widening to a per-cluster overlay the operator pins
3138        // through a future `:max-restarts-overrides` slot) as a
3139        // deliberate test edit, not a silent contract migration.
3140        // Peer of the sibling
3141        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3142        // upper-bracket pin on the same axis.
3143        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3144    }
3145
3146    #[test]
3147    fn default_max_restarts_helper_routes_through_lifted_default() {
3148        // Composition pin: the private `default_max_restarts()`
3149        // serde-`#[serde(default = "…")]` helper on
3150        // [`SupervisorSpec::max_restarts`] must route through the
3151        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3152        // typed `pub const` rather than a raw `5` literal. Prior to
3153        // the lift the helper carried an inline `5` with no compile-
3154        // time link back to the shared default, so the wire-format
3155        // author-omitted arm and the caixa-core
3156        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3157        // arm could silently split on any future default rebrand.
3158        // Byte-parity against the lifted constant closes the split.
3159        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3160    }
3161
3162    #[test]
3163    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3164        // Composition pin: the [`Default for SupervisorSpec`] impl's
3165        // struct-literal `max_restarts` field must route through the
3166        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3167        // typed `pub const` (via the private helper this test's
3168        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3169        // already pins onto the constant). Structurally: every
3170        // `SupervisorSpec::default()` call must yield a
3171        // `max_restarts` field byte-equal to the lifted constant
3172        // (the two paired defaults — the serde-side wire-format arm
3173        // and the struct-literal default arm — cannot silently split
3174        // on any future default rebrand). Peer of the sibling
3175        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3176        // — this pin closes the byte-parity arm on the two paired
3177        // altitude entry points onto the shared substrate constant.
3178        assert_eq!(
3179            SupervisorSpec::default().max_restarts(),
3180            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3181        );
3182    }
3183
3184    #[test]
3185    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3186        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3187        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3188        // Learn You Some Erlang's worker-supervisor default, paired
3189        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3190        // `MaxIntensity` half this constant is the sliding-window
3191        // denominator of on the same `MaxIntensity / Period`
3192        // restart-intensity ratio. Pinning the literal here surfaces a
3193        // future coherent rebrand of the paired default (Elixir's
3194        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3195        // the operator pins through a future
3196        // `:restart-window-overrides` slot) as a deliberate test edit,
3197        // not a silent contract migration. Peer of the sibling
3198        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3199        // paired-half pin on the same OTP-canonical default and the
3200        // [`supervisor_restart_window_cap_pins_canonical_value`]
3201        // upper-bracket pin on the same axis.
3202        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3203    }
3204
3205    #[test]
3206    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3207        // Composition pin: the [`Default for SupervisorSpec`] impl's
3208        // struct-literal `restart_window` field must route through the
3209        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3210        // typed `pub const` rather than a raw
3211        // `Duration::from_secs(60)` literal. Prior to this lift the
3212        // paired `{intensity, 5, 60}` OTP-canonical default was split
3213        // across two altitudes with no compile-time link between the
3214        // halves — the `MaxIntensity` half rode through the lifted
3215        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3216        // `Period` half rode as an open-coded literal at the
3217        // composition site, so a future coherent rebrand of the paired
3218        // canonical would have had to migrate one half through the
3219        // constant and the other through a raw literal in lockstep.
3220        // Byte-parity against the lifted constant on the `Period` half
3221        // closes the split — the paired OTP-canonical default now
3222        // migrates as one unit on any future axis change. Peer of the
3223        // sibling
3224        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3225        // byte-parity pin on the paired `MaxIntensity` half.
3226        assert_eq!(
3227            SupervisorSpec::default().restart_window(),
3228            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3229        );
3230    }
3231
3232    #[test]
3233    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3234        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3235        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3236        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3237        // canonical default, paired with the sibling
3238        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3239        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3240        // this constant is the strategy discriminator of on the same
3241        // OTP-canonical worker-supervisor default. Pinning the arm here
3242        // surfaces a future coherent rebrand of the paired triple (Elixir's
3243        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3244        // intensity/period axes leaving this strategy arm untouched, an OTP
3245        // `rest_for_one` widening once the substrate discovers startup-
3246        // order-coupled child cohorts as the more common worker-supervisor
3247        // shape, a per-cluster overlay the operator pins through a future
3248        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3249        // supervision-canary roadmap acknowledges) as a deliberate test
3250        // edit, not a silent contract migration. Peer of the sibling
3251        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3252        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3253        // paired-half pins on the same OTP-canonical default.
3254        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3255    }
3256
3257    #[test]
3258    fn restart_strategy_default_routes_through_lifted_default() {
3259        // Composition pin: the [`Default for RestartStrategy`] impl's
3260        // return arm must route through the substrate-canonical
3261        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3262        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3263        // an inline `Self::OneForOne` with no compile-time link back to
3264        // the shared OTP-canonical `one_for_one` strategy the paired
3265        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3266        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3267        // `.unwrap_or_default()` (now
3268        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3269        // so a future rebrand of the OTP-canonical strategy default (an
3270        // OTP `rest_for_one` widening once the substrate discovers
3271        // startup-order-coupled child cohorts as the more common worker-
3272        // supervisor shape, a per-cluster overlay the operator pins
3273        // through a future `:estrategia-overrides` slot) would have had to
3274        // be threaded through the `Default` impl and the two peer routes
3275        // in lockstep or the three consumers would silently split. Byte-
3276        // parity against the lifted constant closes the split. Peer of
3277        // the sibling
3278        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3279        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3280        // composition pins on the paired `MaxIntensity` + `Period` halves.
3281        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3282    }
3283
3284    #[test]
3285    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3286        // Composition pin: the [`Default for SupervisorSpec`] impl's
3287        // struct-literal `estrategia` field must route through the
3288        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3289        // `pub const` (either directly, or via the
3290        // [`RestartStrategy::default`] impl that the sibling
3291        // `restart_strategy_default_routes_through_lifted_default` pin
3292        // already routes onto the constant). Structurally: every
3293        // `SupervisorSpec::default()` call must yield an `estrategia`
3294        // field byte-equal to the lifted constant (the three paired
3295        // defaults — the [`Default for RestartStrategy`] impl arm, the
3296        // struct-literal default arm here, and the
3297        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3298        // silently split on any future default rebrand). Peer of the
3299        // sibling
3300        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3301        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3302        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3303        // of the same `SupervisorSpec::default()` composed altitude.
3304        assert_eq!(
3305            SupervisorSpec::default().estrategia(),
3306            SUPERVISOR_ESTRATEGIA_DEFAULT,
3307        );
3308    }
3309
3310    #[test]
3311    fn supervisor_child_restart_default_pins_otp_canonical_value() {
3312        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3313        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3314        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3315        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3316        // half of the same OTP-shape supervisor-tree default set whose
3317        // per-`:supervisor` halves the sibling
3318        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3319        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3320        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3321        // arm here surfaces a future rebrand of the per-child default (an
3322        // OTP-`transient` widening once the substrate discovers clean-
3323        // completion-aware children as the more common child shape, a
3324        // per-cluster overlay the operator pins through a future
3325        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3326        // supervision-canary roadmap acknowledges) as a deliberate test
3327        // edit, not a silent contract migration. Peer of the sibling
3328        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3329        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3330        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3331        // value pins on the per-`:supervisor` halves.
3332        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3333    }
3334
3335    #[test]
3336    fn restart_policy_default_routes_through_lifted_default() {
3337        // Composition pin: the [`Default for RestartPolicy`] impl's return
3338        // arm must route through the substrate-canonical
3339        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3340        // than a raw `Self::Permanent` arm. Prior to the lift the impl
3341        // carried an inline `Self::Permanent` with no compile-time link
3342        // back to the OTP-shape supervisor-tree default set whose three
3343        // per-`:supervisor` halves already rode through lifted constants
3344        // — so a future coherent rebrand of the set would have had to
3345        // migrate three halves through typed constants and this fourth
3346        // through a raw enum arm in lockstep or the supervisor-level and
3347        // child-level defaults would silently drift apart. Byte-parity
3348        // against the lifted constant closes the split. Peer of the
3349        // sibling
3350        // [`restart_strategy_default_routes_through_lifted_default`]
3351        // composition pin on the per-`:supervisor` `:estrategia` axis.
3352        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3353    }
3354
3355    #[test]
3356    fn child_spec_serde_default_restart_routes_through_lifted_default() {
3357        // Composition pin: the serde-side `#[serde(default)]` on
3358        // [`ChildSpec::restart`] — the wire-format author-omitted
3359        // `:children :restart` arm — must resolve onto the substrate-
3360        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3361        // (via the [`Default for RestartPolicy`] impl the sibling
3362        // `restart_policy_default_routes_through_lifted_default` pin
3363        // already routes onto the constant). Structurally: a `ChildSpec`
3364        // deserialized from a payload that omits the `restart` key must
3365        // yield a `restart` field byte-equal to the lifted constant, so
3366        // the wire-format author-omitted arm and the
3367        // [`RestartPolicy::default`] impl arm cannot silently split on any
3368        // future default rebrand. Peer of the sibling
3369        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3370        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3371        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3372        // byte-parity pins on the per-`:supervisor` halves of the same
3373        // author-omitted-slot resolution surface.
3374        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3375            .expect("ChildSpec must deserialize with the restart key omitted");
3376        assert_eq!(
3377            omitted.restart(),
3378            SUPERVISOR_CHILD_RESTART_DEFAULT,
3379            "an author-omitted :children :restart slot must degrade onto \
3380             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3381             {:?}, expected {:?})",
3382            omitted.restart(),
3383            SUPERVISOR_CHILD_RESTART_DEFAULT,
3384        );
3385    }
3386
3387    #[test]
3388    fn supervisor_max_restarts_cap_pins_canonical_value() {
3389        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3390        // 1000 — the same ceiling the peer
3391        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3392        // `:politicas :circuit-breaker :max-failures` axis (both are
3393        // "trip the next-higher protection layer after N events in a
3394        // rolling window" counters with identical
3395        // degenerate-at-the-high-end shape; uniform top edge so the
3396        // M4 CR materializers and the wasm-operator reconciler reach
3397        // for either field knowing the value is in `1..=1000`). Two
3398        // orders of magnitude above every documented Erlang/OTP /
3399        // Elixir / Riak Core / RabbitMQ production-playbook
3400        // recommendation band and below the clearly-pathological
3401        // "effectively no escalation" floor (10_000, 100_000,
3402        // u32::MAX). Pinning the literal value here surfaces a future
3403        // drift (a relaxation to 10_000, a tightening to 100) as a
3404        // deliberate test edit, not a silent contract narrowing.
3405        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3406    }
3407
3408    #[test]
3409    fn validate_rejects_empty_child_name() {
3410        let s = SupervisorSpec {
3411            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3412            ..SupervisorSpec::default()
3413        };
3414        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3415    }
3416
3417    #[test]
3418    fn validate_rejects_empty_child_version() {
3419        let s = SupervisorSpec {
3420            children: vec![child("w", "", RestartPolicy::Permanent)],
3421            ..SupervisorSpec::default()
3422        };
3423        assert!(matches!(
3424            s.validate().unwrap_err(),
3425            SupervisorError::EmptyChildVersion { .. }
3426        ));
3427    }
3428
3429    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3430
3431    #[test]
3432    fn validate_rejects_invalid_child_versao_requirement() {
3433        // The fail-before-pass-after pin: a non-empty but malformed
3434        // semver requirement (`"^bad-version"`) silently passed
3435        // `validate()` on every pre-gate codebase because the prior
3436        // shape only refused the empty string. The parse failure
3437        // surfaced far downstream at lacre-resolve time with a
3438        // `semver::Error` that didn't name which `:children` entry
3439        // carried the typo. The new gate moves the check to caixa-build
3440        // time at the source caixa.lisp — the third `:versao` typed
3441        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3442        // structural parity.
3443        let s = SupervisorSpec {
3444            children: vec![
3445                child("worker", "^0.1", RestartPolicy::Permanent),
3446                child("cache", "^bad-version", RestartPolicy::Transient),
3447            ],
3448            ..SupervisorSpec::default()
3449        };
3450        let err = s.validate().unwrap_err();
3451        assert!(
3452            matches!(
3453                err,
3454                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3455                    if caixa == "cache" && versao == "^bad-version"
3456            ),
3457            "got {err:?}"
3458        );
3459    }
3460
3461    #[test]
3462    fn validate_rejects_child_versao_with_double_caret_typo() {
3463        // `"^^0.1"` is the canonical doubled-caret typo — looks
3464        // Cargo-shaped on first glance but fails the parser because
3465        // semver doesn't accept stacked operators. Pin this
3466        // adjacent-shape footgun explicitly so a future relaxation that
3467        // accepts "looks-canonical-but-isn't" forms surfaces here.
3468        let s = SupervisorSpec {
3469            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
3470            ..SupervisorSpec::default()
3471        };
3472        let err = s.validate().unwrap_err();
3473        assert!(
3474            matches!(
3475                err,
3476                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3477                    if caixa == "worker" && versao == "^^0.1"
3478            ),
3479            "got {err:?}"
3480        );
3481    }
3482
3483    #[test]
3484    fn validate_rejects_child_versao_with_v_prefixed_tag() {
3485        // `"v0.1"` is the canonical "git-tag-shape leaking into the
3486        // semver requirement slot" typo — an author copies the
3487        // publish-side git-tag string verbatim into `:versao`, but
3488        // Cargo's semver parser rejects the leading `v`. Same
3489        // adjacent-shape footgun pinned for `:membros :versao`
3490        // (9888b13).
3491        let s = SupervisorSpec {
3492            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
3493            ..SupervisorSpec::default()
3494        };
3495        let err = s.validate().unwrap_err();
3496        assert!(
3497            matches!(
3498                err,
3499                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3500                    if caixa == "worker" && versao == "v0.1"
3501            ),
3502            "got {err:?}"
3503        );
3504    }
3505
3506    #[test]
3507    fn validate_accepts_canonical_child_versao_forms() {
3508        // The Cargo-shaped requirement forms `:deps :versao` and
3509        // `:membros :versao` already accept via
3510        // `crate::parse_requirement` must pass the children gate
3511        // without re-validating at the resolver layer. Pin every leg so
3512        // a future tightening of the canonical set surfaces here as a
3513        // test failure.
3514        for form in [
3515            "^0.1",      // caret — minor-range pin (the most common shape)
3516            "~0.1.2",    // tilde — patch-range pin
3517            "0.1.0",     // exact — single-version pin
3518            "*",         // wildcard — any version (semver::VersionReq::STAR)
3519            ">=0.1, <2", // multi-range — comma-separated comparators
3520        ] {
3521            let s = SupervisorSpec {
3522                children: vec![child("worker", form, RestartPolicy::Permanent)],
3523                ..SupervisorSpec::default()
3524            };
3525            s.validate()
3526                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3527        }
3528    }
3529
3530    #[test]
3531    fn child_versao_empty_takes_precedence_over_invalid() {
3532        // Order pin: the existing `EmptyChildVersion` diagnostic (which
3533        // doesn't try to parse) fires before the new
3534        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
3535        // `:versao` keeps its narrower error message —
3536        // `parse_requirement` would also reject `""`, but the
3537        // empty-string arm is the more self-locating diagnostic for the
3538        // author. Same ordering discipline as
3539        // `membro_versao_empty_takes_precedence_over_invalid` in
3540        // aplicacao.rs.
3541        let s = SupervisorSpec {
3542            children: vec![child("worker", "", RestartPolicy::Permanent)],
3543            ..SupervisorSpec::default()
3544        };
3545        let err = s.validate().unwrap_err();
3546        assert!(
3547            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
3548            "got {err:?}"
3549        );
3550    }
3551
3552    #[test]
3553    fn child_versao_invalid_fires_before_duplicate_check() {
3554        // Order pin: a malformed requirement on a non-duplicate entry
3555        // surfaces *its own* diagnostic (which names the offending
3556        // `:versao` string), even when a later entry would otherwise
3557        // collapse onto an earlier name. The per-entry shape gate runs
3558        // inline before the duplicate-key insert — parallel to
3559        // `membro_versao_invalid_fires_before_duplicate_check` in
3560        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
3561        let s = SupervisorSpec {
3562            children: vec![
3563                child("worker", "^bad", RestartPolicy::Permanent),
3564                child("cache", "^0.1", RestartPolicy::Transient),
3565                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3566            ],
3567            ..SupervisorSpec::default()
3568        };
3569        let err = s.validate().unwrap_err();
3570        assert!(
3571            matches!(
3572                err,
3573                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
3574            ),
3575            "got {err:?}"
3576        );
3577    }
3578
3579    #[test]
3580    fn child_versao_invalid_diagnostic_carries_offending_versao() {
3581        // The diagnostic-shape pin: the error names the offending
3582        // `:versao` value verbatim so the author can grep their
3583        // caixa.lisp without re-running the build, and carries a
3584        // non-empty `reason` from `semver::VersionReq::parse` so the
3585        // parser's own wording flows through to the diagnostic.
3586        let s = SupervisorSpec {
3587            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
3588            ..SupervisorSpec::default()
3589        };
3590        let err = s.validate().unwrap_err();
3591        let SupervisorError::ChildVersaoInvalid {
3592            caixa,
3593            versao,
3594            reason,
3595        } = err
3596        else {
3597            panic!("expected ChildVersaoInvalid, got other variant");
3598        };
3599        assert_eq!(caixa, "worker");
3600        assert_eq!(versao, "not-a-req");
3601        assert!(
3602            !reason.is_empty(),
3603            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
3604        );
3605    }
3606
3607    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
3608
3609    #[test]
3610    fn validate_rejects_child_caixa_with_uppercase() {
3611        // The canonical "I copied the Servico's display name verbatim"
3612        // typo — child caixa names are lowercase per K8s DNS-1123 label
3613        // rule. The diagnostic names the offending name and suggests the
3614        // lower-cased fix in one edit, mirroring the
3615        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
3616        let s = SupervisorSpec {
3617            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
3618            ..SupervisorSpec::default()
3619        };
3620        let err = s.validate().unwrap_err();
3621        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3622            panic!("expected ChildCaixaInvalid, got other variant");
3623        };
3624        assert_eq!(caixa, "Worker");
3625        assert!(
3626            reason.contains("uppercase"),
3627            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
3628        );
3629        assert!(
3630            reason.contains("\"worker\""),
3631            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
3632        );
3633    }
3634
3635    #[test]
3636    fn validate_rejects_child_caixa_with_underscore() {
3637        // The canonical "I'm thinking of a Python module / Postgres
3638        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
3639        // label schema. K8s rejects `metadata.name: my_worker` at
3640        // admission time with an opaque `field is invalid` (no source-
3641        // citing diagnostic). The gate moves it to caixa-build time.
3642        let s = SupervisorSpec {
3643            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
3644            ..SupervisorSpec::default()
3645        };
3646        let err = s.validate().unwrap_err();
3647        assert!(
3648            matches!(
3649                err,
3650                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3651                    if caixa == "my_worker" && reason.contains('_')
3652            ),
3653            "got {err:?}"
3654        );
3655    }
3656
3657    #[test]
3658    fn validate_rejects_child_caixa_with_dot() {
3659        // A `:children :caixa` entry is a single DNS-1123 label, not a
3660        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
3661        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
3662        // (3f9d7a0) on the peer name axis.
3663        let s = SupervisorSpec {
3664            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
3665            ..SupervisorSpec::default()
3666        };
3667        let err = s.validate().unwrap_err();
3668        assert!(
3669            matches!(
3670                err,
3671                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3672                    if caixa == "team.worker" && reason.contains('.')
3673            ),
3674            "got {err:?}"
3675        );
3676    }
3677
3678    #[test]
3679    fn validate_rejects_child_caixa_with_leading_hyphen() {
3680        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
3681        // with an alphanumeric. The K8s apiserver rejects `-worker`
3682        // outright; the renderer would emit a `metadata.name: "-worker"`
3683        // that fails admission far from the source caixa.lisp.
3684        let s = SupervisorSpec {
3685            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
3686            ..SupervisorSpec::default()
3687        };
3688        let err = s.validate().unwrap_err();
3689        assert!(
3690            matches!(
3691                err,
3692                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3693                    if caixa == "-worker" && reason.contains("start and end")
3694            ),
3695            "got {err:?}"
3696        );
3697    }
3698
3699    #[test]
3700    fn validate_rejects_child_caixa_with_trailing_hyphen() {
3701        // The symmetric arm of the boundary rule. Pin separately so
3702        // both ends of the label are covered against a future relaxation
3703        // that only checks one boundary.
3704        let s = SupervisorSpec {
3705            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
3706            ..SupervisorSpec::default()
3707        };
3708        let err = s.validate().unwrap_err();
3709        assert!(
3710            matches!(
3711                err,
3712                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3713                    if caixa == "worker-"
3714            ),
3715            "got {err:?}"
3716        );
3717    }
3718
3719    #[test]
3720    fn validate_rejects_child_caixa_with_unicode() {
3721        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
3722        // (`xn--…`) by the author before it reaches K8s. The byte-by-
3723        // byte ASCII validity check rejects multi-byte UTF-8 sequences
3724        // by the first byte that fails the `[a-z0-9-]` predicate.
3725        let s = SupervisorSpec {
3726            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
3727            ..SupervisorSpec::default()
3728        };
3729        let err = s.validate().unwrap_err();
3730        assert!(
3731            matches!(
3732                err,
3733                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3734                    if caixa == "café"
3735            ),
3736            "got {err:?}"
3737        );
3738    }
3739
3740    #[test]
3741    fn validate_rejects_child_caixa_with_whitespace() {
3742        // Whitespace is the canonical "I pasted from a sketch / doc"
3743        // footgun. The apiserver rejects every `metadata.name` value
3744        // carrying whitespace; pin the gate fires at the right boundary.
3745        let s = SupervisorSpec {
3746            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
3747            ..SupervisorSpec::default()
3748        };
3749        let err = s.validate().unwrap_err();
3750        assert!(
3751            matches!(
3752                err,
3753                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3754                    if caixa == "my worker"
3755            ),
3756            "got {err:?}"
3757        );
3758    }
3759
3760    #[test]
3761    fn validate_rejects_child_caixa_too_long() {
3762        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
3763        // 63 bytes; the K8s apiserver rejects every `metadata.name`
3764        // axis over the limit at admission time. The diagnostic names
3765        // both the cap and the actual length so the author can shorten
3766        // in one edit, mirroring `rejects_membro_caixa_too_long`
3767        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
3768        let too_long = "a".repeat(64);
3769        let s = SupervisorSpec {
3770            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
3771            ..SupervisorSpec::default()
3772        };
3773        let err = s.validate().unwrap_err();
3774        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3775            panic!("expected ChildCaixaInvalid, got other variant");
3776        };
3777        assert_eq!(caixa, too_long);
3778        assert!(
3779            reason.contains("63"),
3780            "diagnostic must name the 63-byte cap (got: {reason:?})"
3781        );
3782        assert!(
3783            reason.contains("64"),
3784            "diagnostic must name the actual length (got: {reason:?})"
3785        );
3786    }
3787
3788    #[test]
3789    fn child_caixa_max_length_validates() {
3790        // The 63-byte boundary control pin — exactly-at-the-cap is
3791        // accepted, mirroring `membro_caixa_max_length_validates`
3792        // (3f9d7a0) and `placement_cluster_max_length_validates`
3793        // (6cbb900). Pinned separately so a future off-by-one tightening
3794        // surfaces here.
3795        let max_label = "a".repeat(63);
3796        let s = SupervisorSpec {
3797            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
3798            ..SupervisorSpec::default()
3799        };
3800        s.validate().unwrap();
3801    }
3802
3803    #[test]
3804    fn validate_accepts_canonical_child_caixa_forms() {
3805        // The realistic shapes a supervised child's `:caixa` carries —
3806        // single-word `worker`, version-suffixed `cache-v2`, single-char
3807        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
3808        // `payment-retry`, all-digit `0`. Pin every leg so a future
3809        // tightening (e.g. requiring a leading lowercase letter) surfaces
3810        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
3811        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
3812        // (6cbb900).
3813        for form in [
3814            "worker",
3815            "cache-v2",
3816            "a",
3817            "db",
3818            "2-pool",
3819            "payment-retry",
3820            "0",
3821        ] {
3822            let s = SupervisorSpec {
3823                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
3824                ..SupervisorSpec::default()
3825            };
3826            s.validate()
3827                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3828        }
3829    }
3830
3831    #[test]
3832    fn child_caixa_empty_takes_precedence_over_invalid() {
3833        // Order pin: the existing `EmptyChildName` diagnostic (which
3834        // doesn't try to parse the DNS-1123 shape) fires before the new
3835        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
3836        // its narrower error message — `is_dns_1123_label` would reject
3837        // the empty string too (boundary check on the first byte), but
3838        // the empty-string arm is the more self-locating diagnostic for
3839        // the author. Same ordering discipline as
3840        // `membro_caixa_empty_takes_precedence_over_invalid` in
3841        // aplicacao.rs.
3842        let s = SupervisorSpec {
3843            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3844            ..SupervisorSpec::default()
3845        };
3846        let err = s.validate().unwrap_err();
3847        assert_eq!(err, SupervisorError::EmptyChildName);
3848    }
3849
3850    #[test]
3851    fn child_caixa_invalid_fires_before_versao_check() {
3852        // Order pin: the per-axis shape gate runs inline before the
3853        // per-entry versao check, so a malformed `:caixa` on an entry
3854        // whose `:versao` would also fail surfaces the more self-
3855        // locating name-axis diagnostic first. Parallel to
3856        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
3857        // and `placement_cluster_invalid_fires_before_duplicate_check`
3858        // (6cbb900).
3859        let s = SupervisorSpec {
3860            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
3861            ..SupervisorSpec::default()
3862        };
3863        let err = s.validate().unwrap_err();
3864        assert!(
3865            matches!(
3866                err,
3867                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
3868            ),
3869            "got {err:?}"
3870        );
3871    }
3872
3873    #[test]
3874    fn child_caixa_invalid_fires_before_duplicate_check() {
3875        // Order pin: a malformed name on a non-duplicate entry surfaces
3876        // its own diagnostic, even when a later entry would otherwise
3877        // collapse onto an earlier name. The per-entry shape gate runs
3878        // inline before the duplicate-key HashSet insert, mirroring
3879        // `placement_cluster_invalid_fires_before_duplicate_check`
3880        // (6cbb900).
3881        let s = SupervisorSpec {
3882            children: vec![
3883                child("Worker", "^0.1", RestartPolicy::Permanent),
3884                child("cache", "^0.1", RestartPolicy::Transient),
3885                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3886            ],
3887            ..SupervisorSpec::default()
3888        };
3889        let err = s.validate().unwrap_err();
3890        assert!(
3891            matches!(
3892                err,
3893                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
3894            ),
3895            "got {err:?}"
3896        );
3897    }
3898
3899    #[test]
3900    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
3901        // The diagnostic-shape pin: the error names the offending
3902        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
3903        // the author can grep their caixa.lisp without re-running the
3904        // build. Mirrors the diagnostic-shape sweep on every prior
3905        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
3906        let s = SupervisorSpec {
3907            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
3908            ..SupervisorSpec::default()
3909        };
3910        let err = s.validate().unwrap_err();
3911        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3912            panic!("expected ChildCaixaInvalid, got other variant");
3913        };
3914        assert_eq!(caixa, "My_Worker");
3915        assert!(
3916            !reason.is_empty(),
3917            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
3918        );
3919    }
3920
3921    // ── value-shape: zero restart_window + duplicate child names ──────────
3922
3923    #[test]
3924    fn validate_accepts_none_restart_window() {
3925        // Omitted `:restart-window` is the "never reset" sentinel —
3926        // valid by design. Mirrors :limits axes where None = unbounded.
3927        let s = SupervisorSpec {
3928            restart_window: None,
3929            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3930            ..SupervisorSpec::default()
3931        };
3932        s.validate().unwrap();
3933    }
3934
3935    #[test]
3936    fn validate_rejects_zero_restart_window() {
3937        // Same "0 means the opposite of what you think" footgun closed
3938        // for :politicas :timeout (Envoy treats 0s as infinite) and
3939        // :limits :wall-clock (wasmtime traps before the call starts).
3940        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
3941        let s = SupervisorSpec {
3942            restart_window: Some(Duration::ZERO),
3943            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3944            ..SupervisorSpec::default()
3945        };
3946        assert_eq!(
3947            s.validate().unwrap_err(),
3948            SupervisorError::RestartWindowZero
3949        );
3950    }
3951
3952    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
3953    //
3954    // The fourth (and last) typed-`Duration` axis in caixa-core to get
3955    // the integer-millisecond canonical-form gate — peer with
3956    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
3957    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
3958    // path is already gated at the shared codec layer (see
3959    // `restart_window_serde_rejects_fractional_seconds`); this arm
3960    // closes the programmatic-struct-literal path the codec gate can't
3961    // see.
3962
3963    #[test]
3964    fn validate_rejects_sub_millisecond_restart_window() {
3965        // The fail-before-pass-after pin: a programmatic
3966        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
3967        // `validate` on every pre-gate codebase, then truncated to
3968        // `as_millis() == 1` on first serialize — the shared codec
3969        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
3970        // 1_000_000 ns, the typed `restart_window` no longer matches
3971        // its rendered form.
3972        let s = SupervisorSpec {
3973            restart_window: Some(Duration::from_micros(1500)),
3974            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3975            ..SupervisorSpec::default()
3976        };
3977        match s.validate().unwrap_err() {
3978            SupervisorError::RestartWindowNotCanonical { window } => {
3979                assert_eq!(window, Duration::from_micros(1500));
3980            }
3981            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
3982        }
3983    }
3984
3985    #[test]
3986    fn validate_rejects_one_nanosecond_restart_window() {
3987        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
3988        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
3989        // so the shared codec emits the literal `"0s"` — the next
3990        // serde round-trip would parse back to `Duration::ZERO`, which
3991        // the `RestartWindowZero` arm then rejects on re-validate. The
3992        // canonical-form gate at this layer surfaces a self-locating
3993        // diagnostic naming the offending Duration verbatim rather
3994        // than a downstream `RestartWindowZero` whose remediation
3995        // points at omitting the slot.
3996        let s = SupervisorSpec {
3997            restart_window: Some(Duration::from_nanos(1)),
3998            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3999            ..SupervisorSpec::default()
4000        };
4001        match s.validate().unwrap_err() {
4002            SupervisorError::RestartWindowNotCanonical { window } => {
4003                assert_eq!(window, Duration::from_nanos(1));
4004            }
4005            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4006        }
4007    }
4008
4009    #[test]
4010    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4011        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4012        // 1_000_001 ns is structurally past the integer-ms granularity
4013        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4014        // trip would truncate to `1ms` and the consumer would observe
4015        // a 1-ns drift on every emit. Same boundary the peer
4016        // `validate_rejects_nanosecond_past_canonical_boundary` test
4017        // in limits.rs pins for the `:limits :wall-clock` axis.
4018        let w = Duration::from_nanos(1_000_001);
4019        let s = SupervisorSpec {
4020            restart_window: Some(w),
4021            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4022            ..SupervisorSpec::default()
4023        };
4024        assert_eq!(
4025            s.validate().unwrap_err(),
4026            SupervisorError::RestartWindowNotCanonical { window: w }
4027        );
4028    }
4029
4030    #[test]
4031    fn validate_accepts_integer_millisecond_restart_window_values() {
4032        // The positive-control sweep: every `Duration` the shared
4033        // codec can round-trip losslessly — the canonical
4034        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4035        // pair emits and accepts — passes `validate` without
4036        // surfacing the new canonical-form arm. Mirrors
4037        // `validate_accepts_integer_millisecond_wall_clock_values` on
4038        // the sibling `:limits :wall-clock` axis.
4039        for w in [
4040            Duration::from_millis(1),
4041            Duration::from_millis(500),
4042            Duration::from_millis(1500),
4043            Duration::from_secs(1),
4044            Duration::from_secs(30),
4045            Duration::from_secs(60),
4046            Duration::from_secs(120),
4047            Duration::from_secs(3600),
4048        ] {
4049            let s = SupervisorSpec {
4050                restart_window: Some(w),
4051                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4052                ..SupervisorSpec::default()
4053            };
4054            s.validate()
4055                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4056        }
4057    }
4058
4059    #[test]
4060    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4061        // Cross-arm ordering pin: `Duration::ZERO` has
4062        // `subsec_nanos() == 0` and would otherwise pass the
4063        // canonical-form arm — the zero-floor arm must fire first so
4064        // the more self-locating `RestartWindowZero` diagnostic (with
4065        // its omit-axis remediation directly named) leads. Same
4066        // posture every peer zero-then-shape gate uses
4067        // (`WallClockZero` → `WallClockNotCanonical`,
4068        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4069        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4070        let s = SupervisorSpec {
4071            restart_window: Some(Duration::ZERO),
4072            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4073            ..SupervisorSpec::default()
4074        };
4075        assert_eq!(
4076            s.validate().unwrap_err(),
4077            SupervisorError::RestartWindowZero
4078        );
4079    }
4080
4081    #[test]
4082    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4083        // Diagnostic-shape pin: the canonical-form arm names the
4084        // offending `Duration` verbatim so the author's grep lands on
4085        // the field's value, not a generic "duration not canonical"
4086        // message. Same shape every other typed-canonical-form arm
4087        // on this surface carries (`WallClockNotCanonical` carries
4088        // the offending `Duration` verbatim,
4089        // `PolicyTimeoutNotCanonical` carries the offending
4090        // `Duration` verbatim).
4091        let w = Duration::from_micros(500);
4092        let s = SupervisorSpec {
4093            restart_window: Some(w),
4094            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4095            ..SupervisorSpec::default()
4096        };
4097        let err = s.validate().unwrap_err();
4098        let msg = err.to_string();
4099        assert!(
4100            msg.contains("500"),
4101            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4102        );
4103        assert!(
4104            msg.contains("sub-millisecond"),
4105            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4106        );
4107    }
4108
4109    #[test]
4110    fn restart_window_validated_value_round_trips_through_codec() {
4111        // The structural property the canonical-ms gate enforces:
4112        // every `SupervisorSpec::restart_window` past
4113        // `SupervisorSpec::validate` round-trips losslessly through
4114        // the shared duration codec (serialize → string →
4115        // deserialize → equal value). Pin this end-to-end so a future
4116        // change to either side (the validate gate's accepted
4117        // granularity, the codec's parse/render unit set) that breaks
4118        // the alignment surfaces here. Peer of
4119        // `wall_clock_validated_value_round_trips_through_codec` on
4120        // the sibling `:limits :wall-clock` axis.
4121        for w in [
4122            Duration::from_millis(1),
4123            Duration::from_millis(1500),
4124            Duration::from_secs(30),
4125            Duration::from_secs(3600),
4126        ] {
4127            let s = SupervisorSpec {
4128                restart_window: Some(w),
4129                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4130                ..SupervisorSpec::default()
4131            };
4132            s.validate().unwrap();
4133            let json = serde_json::to_string(&s).unwrap();
4134            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4135            assert_eq!(back.restart_window, Some(w));
4136        }
4137    }
4138
4139    // ── value-shape: upper cap on :restart-window ─────────────────────────
4140    //
4141    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4142    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4143    // `:politicas :timeout` (2e8ee7e), and `:politicas
4144    // :circuit-breaker :window` (379a814). Brackets the typed
4145    // `:restart-window` axis structurally: every validated value lies
4146    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4147    // granularity, closing the
4148    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4149    // zero-floor-and-canonical-form-only checks left open.
4150
4151    #[test]
4152    fn validate_rejects_restart_window_above_cap() {
4153        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4154        // structurally one canonical-tick past the
4155        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4156        // integer-millisecond magnitude the canonical-form arm above
4157        // accepts cleanly, that the shared duration codec round-trips
4158        // losslessly as `"3601s"`, and that silently passed validate on
4159        // every pre-gate codebase because the typed slot's only checks
4160        // were the zero-floor and canonical-form arms. The runtime
4161        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4162        // Period reconciler, the future wasm-operator's per-supervisor
4163        // restart-intensity counter) reaches for a `Duration` so long
4164        // no realistic restart-recovery pattern resets the counter,
4165        // far from the source caixa.lisp.
4166        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4167        let s = SupervisorSpec {
4168            restart_window: Some(w),
4169            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4170            ..SupervisorSpec::default()
4171        };
4172        assert_eq!(
4173            s.validate().unwrap_err(),
4174            SupervisorError::RestartWindowExceedsCap { window: w }
4175        );
4176    }
4177
4178    #[test]
4179    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4180        // Boundary case: exactly 1ms past the cap (the granularity the
4181        // canonical-form gate enforces). Catches a future "strictly
4182        // less than" half-measure and pins the diagnostic to name the
4183        // offending `Duration` verbatim. Peer of
4184        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4185        // `rejects_policy_timeout_one_millisecond_above_cap` /
4186        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4187        // on the sibling typed-`Duration` axes' top edges.
4188        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4189        let s = SupervisorSpec {
4190            restart_window: Some(w),
4191            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4192            ..SupervisorSpec::default()
4193        };
4194        assert_eq!(
4195            s.validate().unwrap_err(),
4196            SupervisorError::RestartWindowExceedsCap { window: w }
4197        );
4198    }
4199
4200    #[test]
4201    fn validate_rejects_restart_window_far_above_cap() {
4202        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4203        // `(:restart-window "7d")`, or any "I want a lifetime counter
4204        // but wrote a `<integer>h` magnitude anyway" typo — values the
4205        // canonical-form arm accepts as integer-millisecond magnitudes,
4206        // the codec round-trips losslessly through serde, but the
4207        // operator's `MaxIntensity / Period` reconciler cannot honor
4208        // as a meaningful rolling window. Until this gate landed
4209        // validate accepted them. Pin the common above-cap values (24h,
4210        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4211        // surfaces here.
4212        for w in [
4213            Duration::from_secs(86_400),    // 24h
4214            Duration::from_secs(604_800),   // 7d
4215            Duration::from_secs(1_000_000), // ~11.5 days
4216        ] {
4217            let s = SupervisorSpec {
4218                restart_window: Some(w),
4219                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4220                ..SupervisorSpec::default()
4221            };
4222            assert_eq!(
4223                s.validate().unwrap_err(),
4224                SupervisorError::RestartWindowExceedsCap { window: w }
4225            );
4226        }
4227    }
4228
4229    #[test]
4230    fn validate_accepts_restart_window_at_cap() {
4231        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4232        // (1h) — must validate. The cap is inclusive on the top edge,
4233        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4234        // [`crate::POLICY_TIMEOUT_MAX`] /
4235        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4236        // capped axes. Pin the boundary explicitly so a future
4237        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4238        // instead of `>`) surfaces here as a test failure rather than a
4239        // silent contract narrowing.
4240        let s = SupervisorSpec {
4241            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4242            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4243            ..SupervisorSpec::default()
4244        };
4245        s.validate()
4246            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4247    }
4248
4249    #[test]
4250    fn validate_accepts_restart_window_typical_values() {
4251        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4252        // per-supervisor production-playbook band positive-control
4253        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4254        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4255        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4256        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4257        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4258        // default recommend (5s..=300s) must pass, plus a sweep
4259        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4260        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4261        // on the sibling `:limits :wall-clock` axis.
4262        for w in [
4263            Duration::from_millis(1),
4264            Duration::from_millis(500),
4265            Duration::from_secs(1),
4266            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4267            Duration::from_secs(10), // Riak Core lower
4268            Duration::from_secs(30),
4269            Duration::from_secs(60),  // Learn You Some Erlang default
4270            Duration::from_secs(120), // OTP supervisor MaxT typical
4271            Duration::from_secs(300), // Riak Core upper
4272            Duration::from_secs(900), // 15m
4273            Duration::from_secs(1800),
4274            Duration::from_secs(3600), // exactly 1h, the cap
4275        ] {
4276            let s = SupervisorSpec {
4277                restart_window: Some(w),
4278                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4279                ..SupervisorSpec::default()
4280            };
4281            s.validate()
4282                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4283        }
4284    }
4285
4286    #[test]
4287    fn restart_window_zero_takes_precedence_over_cap() {
4288        // The cross-arm ordering pin: `Duration::ZERO` is structurally
4289        // outside both `>= 1ms` (zero-floor) and `<=
4290        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4291        // diagnostic is the more self-locating one (it directly names
4292        // the omit-axis remediation), so the validate gate must fire
4293        // on zero first. Same shape every other zero-then-cap ordering
4294        // on this surface uses (`WallClockZero` then
4295        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4296        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4297        // `PolicyBreakerWindowExceedsCap`).
4298        let s = SupervisorSpec {
4299            restart_window: Some(Duration::ZERO),
4300            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4301            ..SupervisorSpec::default()
4302        };
4303        assert_eq!(
4304            s.validate().unwrap_err(),
4305            SupervisorError::RestartWindowZero,
4306            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4307        );
4308    }
4309
4310    #[test]
4311    fn restart_window_canonical_takes_precedence_over_cap() {
4312        // The cross-arm ordering pin: a `Duration` that is *both*
4313        // sub-millisecond (non-canonical-form) and structurally above
4314        // the cap surfaces the canonical-form diagnostic first,
4315        // because the round-trip-shape break is the more fundamental
4316        // issue (the value can't even round-trip through the codec,
4317        // so the cap diagnostic naming `1ms..=1h` would be misleading
4318        // — there's no integer-ms form of the offending value). Pin
4319        // the order so a future refactor that reorders the arms
4320        // surfaces here as a test failure rather than a silent
4321        // diagnostic regression. Peer of
4322        // `wall_clock_canonical_takes_precedence_over_cap` /
4323        // `policy_timeout_canonical_takes_precedence_over_cap`.
4324        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4325        let s = SupervisorSpec {
4326            restart_window: Some(w),
4327            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4328            ..SupervisorSpec::default()
4329        };
4330        assert_eq!(
4331            s.validate().unwrap_err(),
4332            SupervisorError::RestartWindowNotCanonical { window: w },
4333            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4334        );
4335    }
4336
4337    #[test]
4338    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4339        // The cross-arm ordering pin between the `:max-restarts` cap
4340        // and the sibling `:restart-window` cap. A supervisor carrying
4341        // both an over-cap `max_restarts` AND an over-cap window must
4342        // surface the `MaxRestartsExceedsCap` diagnostic first — the
4343        // cap arm is wired immediately after the zero-restart arm and
4344        // strictly before every window-axis arm (zero / canonical /
4345        // cap), so the offending value the diagnostic names matches
4346        // the order the author would discover the gates by reading
4347        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4348        // order so a future refactor that reorders the arms surfaces
4349        // here as a test failure rather than a silent diagnostic
4350        // regression. Peer of
4351        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4352        // on the sibling zero / canonical window arms.
4353        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4354        let s = SupervisorSpec {
4355            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4356            restart_window: Some(w),
4357            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4358            ..SupervisorSpec::default()
4359        };
4360        assert_eq!(
4361            s.validate().unwrap_err(),
4362            SupervisorError::MaxRestartsExceedsCap {
4363                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4364            },
4365            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4366        );
4367    }
4368
4369    #[test]
4370    fn restart_window_cap_diagnostic_carries_offending_value() {
4371        // The diagnostic-shape pin: the offending `Duration` is
4372        // carried verbatim into the
4373        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4374        // surfaced error message names the value the author wrote,
4375        // not just the cap. Same self-locating diagnostic shape every
4376        // other typed-cap arm on this surface carries
4377        // (`WallClockExceedsCap` carries the offending `Duration`
4378        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4379        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4380        // the offending `Duration` verbatim).
4381        let w = Duration::from_secs(7200); // 2h
4382        let s = SupervisorSpec {
4383            restart_window: Some(w),
4384            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4385            ..SupervisorSpec::default()
4386        };
4387        let err = s.validate().unwrap_err();
4388        assert!(
4389            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4390            "got {err:?}"
4391        );
4392        let msg = err.to_string();
4393        assert!(
4394            msg.contains("7200"),
4395            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4396        );
4397    }
4398
4399    #[test]
4400    fn supervisor_restart_window_cap_pins_canonical_value() {
4401        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4402        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4403        // shared duration codec emits as a clean canonical string
4404        // (`"<n>h"`). Pinning the literal value here surfaces a future
4405        // drift (a relaxation to 24h, a tightening to 5m) as a
4406        // deliberate test edit, not a silent contract narrowing.
4407        //
4408        // The four typed-`Duration` caps on the validation surface
4409        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4410        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4411        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4412        // single uniform top edge at the codec's largest emitted unit
4413        // — a structural-property invariant the equality assertions
4414        // here enshrine, so a future drift on any of the four
4415        // surfaces as a deliberate test edit. Same shape every other
4416        // typed-cap value pin uses
4417        // (`wall_clock_cap_pins_canonical_value`,
4418        // `policy_timeout_cap_pins_canonical_value`,
4419        // `circuit_breaker_window_cap_pins_canonical_value`).
4420        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4421        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4422        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4423        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4424        assert_eq!(
4425            SUPERVISOR_RESTART_WINDOW_MAX,
4426            crate::POLICY_BREAKER_WINDOW_MAX
4427        );
4428    }
4429
4430    #[test]
4431    fn restart_window_cap_value_round_trips_through_codec() {
4432        // The codec round-trip property the cap arm preserves: the
4433        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4434        // through the shared duration codec — every value at the cap
4435        // serializes to the canonical `"1h"` form and parses back
4436        // identically. Pin the round-trip so a future change to the
4437        // codec's unit set or to the cap's magnitude that breaks the
4438        // round-trip property surfaces here. Peer of
4439        // `wall_clock_cap_value_round_trips_through_codec` on the
4440        // sibling `:limits :wall-clock` axis.
4441        let s = SupervisorSpec {
4442            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4443            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4444            ..SupervisorSpec::default()
4445        };
4446        s.validate().unwrap();
4447        let json = serde_json::to_string(&s).unwrap();
4448        assert!(
4449            json.contains("\"1h\""),
4450            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
4451        );
4452        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4453        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
4454    }
4455
4456    #[test]
4457    fn validate_rejects_duplicate_child_caixa() {
4458        // Two children with the same :caixa render to two ComputeUnits
4459        // with the same name in the cluster's HelmRelease values —
4460        // one silently overwrites the other. Erlang/OTP's child_spec.id
4461        // is required-unique per supervisor; same set-not-multiset
4462        // discipline applied here as for :membros / :placement
4463        // :clusters / :entrada :paths.
4464        let s = SupervisorSpec {
4465            children: vec![
4466                child("worker", "^0.1", RestartPolicy::Permanent),
4467                child("cache", "^0.1", RestartPolicy::Transient),
4468                child("worker", "^0.2", RestartPolicy::Permanent),
4469            ],
4470            ..SupervisorSpec::default()
4471        };
4472        let err = s.validate().unwrap_err();
4473        assert!(
4474            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
4475            "got {err:?}"
4476        );
4477    }
4478
4479    #[test]
4480    fn validate_duplicate_child_diagnostic_names_first_collision() {
4481        // Iteration walks the :children list in declaration order —
4482        // the diagnostic names the first repeat, deterministically,
4483        // even when multiple names duplicate.
4484        let s = SupervisorSpec {
4485            children: vec![
4486                child("a", "^0.1", RestartPolicy::Permanent),
4487                child("b", "^0.1", RestartPolicy::Permanent),
4488                child("a", "^0.1", RestartPolicy::Permanent),
4489                child("b", "^0.1", RestartPolicy::Permanent),
4490            ],
4491            ..SupervisorSpec::default()
4492        };
4493        let err = s.validate().unwrap_err();
4494        assert!(
4495            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
4496            "got {err:?}"
4497        );
4498    }
4499
4500    // ── self-supervision cross-slot gate ──────────────────────────
4501
4502    #[test]
4503    fn validate_no_self_supervision_rejects_self_referential_child() {
4504        // A supervisor whose `:children` lists its own `:nome` is a
4505        // one-node reconciliation cycle — rejected, naming the parent.
4506        let children = vec![
4507            child("worker", "^0.1", RestartPolicy::Permanent),
4508            child("orquestra", "^0.1", RestartPolicy::Permanent),
4509        ];
4510        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
4511        assert!(
4512            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
4513            "got {err:?}"
4514        );
4515    }
4516
4517    #[test]
4518    fn validate_no_self_supervision_accepts_distinct_children() {
4519        // Positive control: distinct child names (including a child that
4520        // is itself a supervisor — nested trees are valid OTP) pass.
4521        let children = vec![
4522            child("worker", "^0.1", RestartPolicy::Permanent),
4523            child("sub-tree", "^0.1", RestartPolicy::Permanent),
4524        ];
4525        validate_no_self_supervision(&children, "orquestra").unwrap();
4526    }
4527
4528    #[test]
4529    fn validate_no_self_supervision_empty_children_is_ok() {
4530        // SimpleOneForOne / no-static-children supervisors have nothing
4531        // to self-reference — the gate is vacuously satisfied.
4532        validate_no_self_supervision(&[], "orquestra").unwrap();
4533    }
4534
4535    #[test]
4536    fn validate_simple_one_for_one_skips_uniqueness_check() {
4537        // SimpleOneForOne supervisors carry no static children — the
4538        // duplicate-child loop never runs. A zero-window declaration
4539        // on a SimpleOneForOne supervisor still trips the window check
4540        // (window applies to dynamic children too).
4541        let s = SupervisorSpec {
4542            estrategia: RestartStrategy::SimpleOneForOne,
4543            restart_window: None,
4544            children: vec![],
4545            ..SupervisorSpec::default()
4546        };
4547        s.validate().unwrap();
4548        let s_zero = SupervisorSpec {
4549            estrategia: RestartStrategy::SimpleOneForOne,
4550            restart_window: Some(Duration::ZERO),
4551            children: vec![],
4552            ..SupervisorSpec::default()
4553        };
4554        assert_eq!(
4555            s_zero.validate().unwrap_err(),
4556            SupervisorError::RestartWindowZero
4557        );
4558    }
4559
4560    #[test]
4561    fn validate_zero_window_runs_after_max_restarts_check() {
4562        // Pin the order: max_restarts == 0 fires before
4563        // restart_window == 0s, so an author with both wrong sees the
4564        // counter-axis diagnostic first (matches the order in the
4565        // struct and in the doc comment).
4566        let s = SupervisorSpec {
4567            max_restarts: 0,
4568            restart_window: Some(Duration::ZERO),
4569            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4570            ..SupervisorSpec::default()
4571        };
4572        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4573    }
4574
4575    #[test]
4576    fn round_trip_all_strategies() {
4577        for &strat in RestartStrategy::ALL {
4578            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
4579            // shape partition through the [`gen_platform::IsVariant`]
4580            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
4581            // predicate rather than the raw
4582            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
4583            // open-coded pattern-match — same closed-set-typed-enum
4584            // arm-discriminator dispatch discipline the sibling
4585            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
4586            // (915a934) extended onto its two paired positive / negated
4587            // `matches!` filter sites, and the sibling
4588            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
4589            // predicate convergence (766ec63) extended onto the M3 mesh-
4590            // slot per-`:placement` distribution-strategy `matches!`
4591            // discriminator axis. See the sibling
4592            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
4593            // fixture and the peer `manifest::tests::
4594            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
4595            // fixture — all three sites (the last unlifted
4596            // `matches!`-based arm-discriminator axis on the OTP-shape
4597            // supervisor sibling-restart-strategy closed-set typed enum,
4598            // acknowledged in 915a934's Prior-commits footnote as the
4599            // outstanding follow-up) now consult one typed dispatch on
4600            // the substrate primitive.
4601            let s = SupervisorSpec {
4602                estrategia: strat,
4603                children: if strat.is_simple_one_for_one() {
4604                    vec![]
4605                } else {
4606                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
4607                },
4608                ..SupervisorSpec::default()
4609            };
4610            let json = serde_json::to_string(&s).unwrap();
4611            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4612            assert_eq!(s, back);
4613        }
4614    }
4615
4616    #[test]
4617    fn round_trip_all_restart_policies() {
4618        for policy in [
4619            RestartPolicy::Permanent,
4620            RestartPolicy::Temporary,
4621            RestartPolicy::Transient,
4622        ] {
4623            let c = child("w", "^0.1", policy);
4624            let json = serde_json::to_string(&c).unwrap();
4625            let back: ChildSpec = serde_json::from_str(&json).unwrap();
4626            assert_eq!(c, back);
4627        }
4628    }
4629
4630    #[test]
4631    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
4632        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
4633        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
4634        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
4635        // is the only variant that satisfies `.is_simple_one_for_one()`;
4636        // every static-children-bearing arm (`OneForOne` / `OneForAll`
4637        // / `RestForOne`) returns `false`. This pin makes the partition
4638        // invariant load-bearing at caixa-core test time so a future
4639        // derive regression (a hole that returns `false` for
4640        // `SimpleOneForOne` too, or a byte-collision that flips a second
4641        // variant to `true`) trips here rather than laundering the arm
4642        // at the three test-fixture builder sites (a hole flips the
4643        // `SimpleOneForOne` fixture to carry a non-empty children list
4644        // and the subsequent `SupervisorSpec::validate` would refuse the
4645        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
4646        // a collision flips a peer strategy's fixture to carry an empty
4647        // children list and the subsequent `validate` would refuse with
4648        // [`SupervisorError::NoChildren`] — either way, the pin fires
4649        // here, at the derive site, rather than at the fixture-refusal
4650        // site far away). Peer of the sibling
4651        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
4652        // (915a934) pin on the M2 OTP-appup axis and the sibling
4653        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
4654        // pin on the M0 `:kind` axis.
4655        let cases: &[(RestartStrategy, bool)] = &[
4656            (RestartStrategy::OneForOne, false),
4657            (RestartStrategy::OneForAll, false),
4658            (RestartStrategy::RestForOne, false),
4659            (RestartStrategy::SimpleOneForOne, true),
4660        ];
4661        for (variant, expected) in cases {
4662            assert_eq!(
4663                variant.is_simple_one_for_one(),
4664                *expected,
4665                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
4666                 return {expected} (partition invariant on the \
4667                 IsVariant-derived arm-discriminator predicate — every \
4668                 test-fixture site that partitions the `:children` slot \
4669                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
4670                 off this typed dispatch, so a derive regression must \
4671                 surface here rather than at the fixture-refusal site)"
4672            );
4673        }
4674    }
4675
4676    #[test]
4677    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
4678        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
4679        // fixture-shape partition against the pre-lift
4680        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
4681        // pattern-match every test-fixture builder site previously
4682        // coupled to inline. Asserts the two projections agree byte-for-
4683        // byte on every arm of the enum, so a future derive regression
4684        // that flipped either predicate's arm-set would surface here at
4685        // caixa-core test time rather than at the three fixture-builder
4686        // sites (`supervisor::tests::round_trip_all_strategies`,
4687        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
4688        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
4689        // far from the derive site. Same peer-shape byte-identity pin
4690        // every sibling `IsVariant`-derive-routed convergence carries on
4691        // the substrate's closed-set typed-enum surface (peer of
4692        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
4693        // on the M2 OTP-appup axis).
4694        for &strat in RestartStrategy::ALL {
4695            let via_predicate = strat.is_simple_one_for_one();
4696            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
4697            assert_eq!(
4698                via_predicate, via_matches,
4699                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
4700                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
4701                 the pre-lift open-coded pattern and the \
4702                 IsVariant-derived predicate are the same axis, \
4703                 one typed dispatch"
4704            );
4705        }
4706    }
4707
4708    #[test]
4709    fn duration_codec_round_trip_canonical_units() {
4710        // Note the canonical-form rule: durations serialize to the
4711        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
4712        // "60s" — but the round-trip preserves the underlying Duration.
4713        let cases = [
4714            ("30s", Duration::from_secs(30)),
4715            ("5m", Duration::from_secs(300)),
4716            ("1h", Duration::from_secs(3600)),
4717            ("500ms", Duration::from_millis(500)),
4718        ];
4719        for (lit, dur) in cases {
4720            let s = SupervisorSpec {
4721                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4722                restart_window: Some(dur),
4723                ..SupervisorSpec::default()
4724            };
4725            let json = serde_json::to_string(&s).unwrap();
4726            assert!(
4727                json.contains(&format!("\"{lit}\"")),
4728                "expected \"{lit}\" in {json}"
4729            );
4730            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4731            assert_eq!(back.restart_window, Some(dur));
4732        }
4733    }
4734
4735    #[test]
4736    fn duration_canonicalizes_to_largest_unit() {
4737        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
4738        // typed Duration still equals 60s on the way back.
4739        let s = SupervisorSpec {
4740            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4741            restart_window: Some(Duration::from_secs(60)),
4742            ..SupervisorSpec::default()
4743        };
4744        let json = serde_json::to_string(&s).unwrap();
4745        assert!(json.contains("\"1m\""), "{json}");
4746        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4747        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
4748    }
4749
4750    #[test]
4751    fn three_child_one_for_one_validates() {
4752        let s = SupervisorSpec {
4753            estrategia: RestartStrategy::OneForOne,
4754            max_restarts: 5,
4755            restart_window: Some(Duration::from_secs(60)),
4756            children: vec![
4757                child("worker", "^0.1", RestartPolicy::Permanent),
4758                child("cache", "^0.1", RestartPolicy::Transient),
4759                child("scratch", "^0.1", RestartPolicy::Temporary),
4760            ],
4761        };
4762        s.validate().unwrap();
4763    }
4764
4765    #[test]
4766    fn json_uses_pascal_case_for_strategy_and_policy() {
4767        // Variant names are PascalCase by default in serde, matching
4768        // tatara-lisp's enum convention (`:estrategia OneForOne`).
4769        let c = child("w", "^0.1", RestartPolicy::Permanent);
4770        let json = serde_json::to_string(&c).unwrap();
4771        assert!(json.contains("\"Permanent\""));
4772        assert!(!json.contains("\"permanent\""));
4773
4774        let s = SupervisorSpec {
4775            estrategia: RestartStrategy::OneForOne,
4776            children: vec![c],
4777            ..SupervisorSpec::default()
4778        };
4779        let json = serde_json::to_string(&s).unwrap();
4780        assert!(json.contains("\"estrategia\":\"OneForOne\""));
4781    }
4782
4783    // ── shared duration codec: integer-magnitude canonical-form gate ──
4784    //
4785    // The gate lifts the discipline `crate::limits::parse_duration`
4786    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
4787    // the shared codec backing the remaining three typed-duration
4788    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
4789    // `:politicas :circuit-breaker :window`. Every magnitude `render`
4790    // emits is a non-negative integer with no decimal point and no
4791    // leading sign, so the codec's accepted set must match for
4792    // serialize/deserialize to round-trip without canonical-form
4793    // drift.
4794
4795    #[test]
4796    fn parse_accepts_integer_canonical_units() {
4797        // Pin the happy-path: every canonical author shape `render`
4798        // ever emits parses to the same `Duration` value, so the
4799        // codec's accepted set is at least a superset of its emitted
4800        // set on the canonical-unit axis.
4801        for (lit, dur) in [
4802            ("30s", Duration::from_secs(30)),
4803            ("500ms", Duration::from_millis(500)),
4804            ("2m", Duration::from_secs(120)),
4805            ("1h", Duration::from_secs(3600)),
4806            ("0s", Duration::ZERO),
4807        ] {
4808            assert_eq!(
4809                duration_codec::parse(lit).unwrap(),
4810                dur,
4811                "parse({lit:?}) should be {dur:?}"
4812            );
4813        }
4814    }
4815
4816    #[test]
4817    fn parse_accepts_bare_integer_as_seconds() {
4818        // The `"s" | ""` arm: a bare integer with no unit is read as
4819        // seconds. Pin this so the unit-empty form keeps parsing (it
4820        // renders to `"<n>s"` on serialize — that's a unit-choice
4821        // drift the integer-magnitude gate does NOT close, matching
4822        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
4823        // the peer `:limits :memory` codec).
4824        assert_eq!(
4825            duration_codec::parse("30").unwrap(),
4826            Duration::from_secs(30)
4827        );
4828    }
4829
4830    #[test]
4831    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
4832        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
4833        // on first serialize — DRIFT. The integer-magnitude gate names
4834        // the offending `"1.5"` verbatim and points at the canonical
4835        // remediation `"1500ms"`.
4836        let err = duration_codec::parse("1.5s").unwrap_err();
4837        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
4838        assert!(
4839            err.contains("not a non-negative integer"),
4840            "missing canonical-form reason in {err:?}"
4841        );
4842        assert!(
4843            err.contains("\"1500ms\""),
4844            "missing canonical-form remediation in {err:?}"
4845        );
4846    }
4847
4848    #[test]
4849    fn parse_rejects_decimal_shaped_integer_seconds() {
4850        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
4851        // `1s` exactly, so the round-trip looks correct — but the
4852        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
4853        // decimal-shape-with-integer-value form so author intent is
4854        // never silently rewritten.
4855        let err = duration_codec::parse("1.0s").unwrap_err();
4856        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
4857        assert!(
4858            err.contains("not a non-negative integer"),
4859            "missing canonical-form reason in {err:?}"
4860        );
4861    }
4862
4863    #[test]
4864    fn parse_rejects_half_unit_minute() {
4865        // `"0.5m"` is the unit-fraction footgun — author writes a
4866        // human-readable half-minute, serde silently rewrites to
4867        // `"30s"` on next emit. The gate names the offending
4868        // magnitude `"0.5"` and points at the integer-in-smaller-unit
4869        // form.
4870        let err = duration_codec::parse("0.5m").unwrap_err();
4871        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
4872        assert!(
4873            err.contains("\"30s\""),
4874            "missing canonical-form remediation in {err:?}"
4875        );
4876    }
4877
4878    #[test]
4879    fn parse_rejects_leading_plus_sign() {
4880        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
4881        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
4882        // cleanly to 30s and round-tripped to `"30s"` on next emit
4883        // (DRIFT). The digit-only gate closes the leading-sign class
4884        // first; the diagnostic names `"+30"` verbatim.
4885        let err = duration_codec::parse("+30s").unwrap_err();
4886        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
4887        assert!(
4888            err.contains("not a non-negative integer"),
4889            "missing canonical-form reason in {err:?}"
4890        );
4891    }
4892
4893    #[test]
4894    fn parse_rejects_leading_minus_sign() {
4895        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
4896        // rejected with `"negative duration in \"-30s\""`. Under the
4897        // integer-magnitude gate the diagnostic is unified — `-30` is
4898        // non-digit-only, f64-numeric, and surfaces with the canonical-
4899        // form reason (no leading `+` / `-` sign) naming the offending
4900        // `"-30"` verbatim. Same diagnostic shape as every other
4901        // rejected non-integer magnitude.
4902        let err = duration_codec::parse("-30s").unwrap_err();
4903        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
4904        assert!(
4905            err.contains("not a non-negative integer"),
4906            "missing canonical-form reason in {err:?}"
4907        );
4908    }
4909
4910    #[test]
4911    fn parse_garbage_still_falls_through_to_bad_magnitude() {
4912        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
4913        // through to the narrower "bad duration magnitude" arm — the
4914        // canonical-form diagnostic is reserved for the parser-shape
4915        // footgun case, not the "not a number at all" case. Same
4916        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
4917        // the peer `:limits :memory` codec.
4918        let err = duration_codec::parse("--1s").unwrap_err();
4919        assert!(
4920            err.contains("bad duration magnitude"),
4921            "expected bad-magnitude wording in {err:?}"
4922        );
4923    }
4924
4925    #[test]
4926    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
4927        // The accepted set is now closed under `u64`-exact integer
4928        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
4929        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
4930        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
4931        // possible. Pin the integer-exact arms across the four unit
4932        // suffixes so a future refactor that reaches back for f64
4933        // (`from_secs_f64`, `mul_f64`) surfaces here.
4934        assert_eq!(
4935            duration_codec::parse("3600s").unwrap(),
4936            Duration::from_secs(3600)
4937        );
4938        assert_eq!(
4939            duration_codec::parse("60m").unwrap(),
4940            Duration::from_secs(3600)
4941        );
4942        assert_eq!(
4943            duration_codec::parse("1h").unwrap(),
4944            Duration::from_secs(3600)
4945        );
4946        assert_eq!(
4947            duration_codec::parse("999ms").unwrap(),
4948            Duration::from_millis(999)
4949        );
4950    }
4951
4952    #[test]
4953    fn restart_window_serde_rejects_fractional_seconds() {
4954        // The shared codec backs `SupervisorSpec::restart_window`
4955        // (`with = "duration_codec"`) — so the gate applies on serde
4956        // deserialize for the typed Supervisor slot. A
4957        // `{"restartWindow":"1.5s"}` payload that previously round-
4958        // tripped to a different canonical string on next serialize
4959        // is now refused at deserialize with the integer-magnitude
4960        // diagnostic.
4961        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4962            "restartWindow":"1.5s",
4963            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4964        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4965        let msg = err.to_string();
4966        assert!(
4967            msg.contains("not a non-negative integer"),
4968            "expected integer-magnitude diagnostic in {msg:?}"
4969        );
4970        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
4971    }
4972
4973    #[test]
4974    fn restart_window_serde_rejects_leading_plus() {
4975        // The `u64::from_str` leading-`+` permissiveness gap that
4976        // motivated the digit-only gate (the `f64`-side accepted
4977        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
4978        // is now closed on the shared codec — surfaces as a structured
4979        // diagnostic at the serde layer for every typed-duration slot.
4980        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4981            "restartWindow":"+30s",
4982            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4983        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4984        let msg = err.to_string();
4985        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
4986        assert!(
4987            msg.contains("not a non-negative integer"),
4988            "missing canonical-form reason in {msg:?}"
4989        );
4990    }
4991
4992    #[test]
4993    fn parse_rejects_leading_zero_magnitude() {
4994        // `"030s"` is digit-only, so the existing non-digit-only / sign
4995        // / fractional arm doesn't catch it — `u64::from_str("030")`
4996        // returns `Ok(30)`, so before this gate `"030s"` parsed to
4997        // `Duration::from_secs(30)` and round-tripped through `render`
4998        // to `"30s"` — a *different* canonical string on the next emit,
4999        // breaking the THEORY.md Part V render-determinism contract
5000        // exactly the way `"+30s"` did before the leading-`+` arm
5001        // landed. Peer with the `rate_limit_codec` leading-zero arm
5002        // (4f46830) on the same canonical-form-drift axis.
5003        let err = duration_codec::parse("030s").unwrap_err();
5004        assert!(
5005            err.contains("non-canonical leading zero"),
5006            "expected leading-zero diagnostic in {err:?}"
5007        );
5008        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5009        assert!(
5010            err.contains("\"30s\""),
5011            "missing canonical-form remediation in {err:?}"
5012        );
5013        assert!(
5014            err.contains("THEORY.md"),
5015            "missing render-determinism citation in {err:?}"
5016        );
5017    }
5018
5019    #[test]
5020    fn parse_rejects_multi_digit_zero_magnitude() {
5021        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5022        // digit-only, parse losslessly to `Duration::ZERO`, but render
5023        // back to `"0s"` (the single-byte canonical form) on the next
5024        // emit. The leading-zero arm refuses the drift class at the
5025        // codec layer; the semantic-zero gate downstream
5026        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5027        // the single-byte canonical form `"0s"` separately on the
5028        // typed-validate layer.
5029        let err = duration_codec::parse("00s").unwrap_err();
5030        assert!(
5031            err.contains("non-canonical leading zero"),
5032            "expected leading-zero diagnostic in {err:?}"
5033        );
5034        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5035    }
5036
5037    #[test]
5038    fn parse_rejects_leading_zero_per_hour_window() {
5039        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5040        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5041        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5042        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5043        // `h` / bare-integer-as-seconds) inherits the same gate.
5044        let err = duration_codec::parse("01h").unwrap_err();
5045        assert!(
5046            err.contains("non-canonical leading zero"),
5047            "expected leading-zero diagnostic in {err:?}"
5048        );
5049        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5050    }
5051
5052    #[test]
5053    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5054        // The `parse_accepts_bare_integer_as_seconds` happy-path
5055        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5056        // multi-byte starts-with-`0`, parses losslessly to
5057        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5058        // bare-integer surface accepts permissive unit-empty
5059        // shorthand but still must reject leading-zero padding.
5060        let err = duration_codec::parse("030").unwrap_err();
5061        assert!(
5062            err.contains("non-canonical leading zero"),
5063            "expected leading-zero diagnostic in {err:?}"
5064        );
5065        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5066    }
5067
5068    #[test]
5069    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5070        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5071        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5072        // each round-trips losslessly through `render`
5073        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5074        // accepts them. The downstream semantic-zero gates
5075        // (`SupervisorError::ZeroRestartWindow`,
5076        // `AplicacaoError::PolicyTimeoutZero`,
5077        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5078        // zero-magnitude authoring at the typed-validate layer above,
5079        // peer with the `rate_limit_codec` codec-layer / typed-
5080        // validate-layer partition for `"0/s"`.
5081        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5082        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5083        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5084    }
5085
5086    #[test]
5087    fn parse_accepts_canonical_magnitude_with_leading_one() {
5088        // The complementary boundary: a future tightening cannot
5089        // drift into rejecting valid canonical magnitudes that
5090        // happen to start with `1` (or any digit `[1-9]`). Pin
5091        // every canonical-unit suffix so the leading-zero arm
5092        // remains strictly narrower than the digit-only arm.
5093        assert_eq!(
5094            duration_codec::parse("100ms").unwrap(),
5095            Duration::from_millis(100)
5096        );
5097        assert_eq!(
5098            duration_codec::parse("100s").unwrap(),
5099            Duration::from_secs(100)
5100        );
5101        assert_eq!(
5102            duration_codec::parse("10m").unwrap(),
5103            Duration::from_secs(600)
5104        );
5105        assert_eq!(
5106            duration_codec::parse("10h").unwrap(),
5107            Duration::from_secs(36_000)
5108        );
5109    }
5110
5111    #[test]
5112    fn restart_window_serde_rejects_leading_zero() {
5113        // The shared codec backs `SupervisorSpec::restart_window`
5114        // (`with = "duration_codec"`) — so the leading-zero arm
5115        // applies on serde deserialize for the typed Supervisor slot.
5116        // A `{"restartWindow":"030s"}` payload that previously round-
5117        // tripped to a different canonical string on next serialize
5118        // is now refused at deserialize with the leading-zero
5119        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5120        // / `restart_window_serde_rejects_fractional_seconds` on the
5121        // same canonical-form-drift axis.
5122        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5123            "restartWindow":"030s",
5124            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5125        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5126        let msg = err.to_string();
5127        assert!(
5128            msg.contains("non-canonical leading zero"),
5129            "expected leading-zero diagnostic in {msg:?}"
5130        );
5131        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5132    }
5133
5134    #[test]
5135    fn parse_rejects_leading_whitespace() {
5136        // `" 30s"` — the canonical paste-from-aligned-doc /
5137        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5138        // gate the top-level `s.trim()` at parse entry silently ate
5139        // the leading space and parsed the value to
5140        // `Duration::from_secs(30)`, which then round-tripped through
5141        // `render` to `"30s"` (a *different* canonical string on the
5142        // next emit) — the exact canonical-form-drift class the
5143        // leading-`+` / leading-zero arms already close, extended
5144        // to the whitespace-byte class. Peer with the sibling
5145        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5146        // the M3 `:politicas` axis.
5147        let err = duration_codec::parse(" 30s").unwrap_err();
5148        assert!(
5149            err.contains("contains whitespace byte"),
5150            "expected whitespace diagnostic in {err:?}"
5151        );
5152        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5153        assert!(
5154            err.contains("THEORY.md"),
5155            "missing render-determinism contract citation in {err:?}"
5156        );
5157    }
5158
5159    #[test]
5160    fn parse_rejects_trailing_whitespace() {
5161        // `"30s "` — the canonical shell-history / trailing-space
5162        // paste footgun. Before this gate the top-level `s.trim()`
5163        // silently ate the trailing space and parsed to
5164        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5165        // next emit — same canonical-form drift as the leading-space
5166        // sibling, closed on the same whitespace-byte arm.
5167        let err = duration_codec::parse("30s ").unwrap_err();
5168        assert!(
5169            err.contains("contains whitespace byte"),
5170            "expected whitespace diagnostic in {err:?}"
5171        );
5172        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5173    }
5174
5175    #[test]
5176    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5177        // `"30 s"` — the canonical typographically-spaced author
5178        // shape (the same idiom every prose reference to a duration
5179        // renders as, mistakenly retained when the value is pasted
5180        // into a codec-shaped slot). Before this gate the per-part
5181        // `num_part.trim()` / `unit.trim()` calls silently ate the
5182        // whitespace between the magnitude and the unit and parsed
5183        // the value to `Duration::from_secs(30)`, round-tripping to
5184        // `"30s"` — the codec's *internal* whitespace-tolerance
5185        // vector, orthogonal to the leading / trailing surface but
5186        // the same canonical-form-drift class. Pins the arm as
5187        // strictly stronger than the pre-existing top-level
5188        // `s.trim()` behavior: it fires on whitespace anywhere in
5189        // the value, not just at the string boundary.
5190        let err = duration_codec::parse("30 s").unwrap_err();
5191        assert!(
5192            err.contains("contains whitespace byte"),
5193            "expected whitespace diagnostic in {err:?}"
5194        );
5195        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5196    }
5197
5198    #[test]
5199    fn parse_rejects_tab_byte() {
5200        // `"\t30s"` — the canonical paste-from-indented-doc /
5201        // paste-from-YAML-block-scalar footgun where a tab byte leads
5202        // the magnitude. Pins that the gate covers tab (`0x09`) as
5203        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5204        // members and both would be silently swallowed by `s.trim()`
5205        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5206        // space alone to the full ASCII-whitespace set (space `0x20`,
5207        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5208        // the tab arm as a representative of the non-space members.
5209        let err = duration_codec::parse("\t30s").unwrap_err();
5210        assert!(
5211            err.contains("contains whitespace byte"),
5212            "expected whitespace diagnostic in {err:?}"
5213        );
5214        assert!(
5215            err.contains("0x09"),
5216            "missing offending tab byte in {err:?}"
5217        );
5218    }
5219
5220    #[test]
5221    fn restart_window_serde_rejects_whitespace() {
5222        // The shared codec backs `SupervisorSpec::restart_window`
5223        // (`with = "duration_codec"`) — so the whitespace arm
5224        // applies on serde deserialize for the typed Supervisor slot.
5225        // A `{"restartWindow":" 30s"}` payload that previously round-
5226        // tripped to a different canonical string on next serialize
5227        // is now refused at deserialize with the whitespace-byte
5228        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5229        // / `restart_window_serde_rejects_leading_plus` /
5230        // `restart_window_serde_rejects_fractional_seconds` on the
5231        // same canonical-form-drift axis.
5232        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5233            "restartWindow":" 30s",
5234            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5235        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5236        let msg = err.to_string();
5237        assert!(
5238            msg.contains("contains whitespace byte"),
5239            "expected whitespace diagnostic in {msg:?}"
5240        );
5241        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5242    }
5243
5244    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5245    //
5246    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5247    // duration codec — closes the strictly-complementary class the
5248    // byte-scan cannot see, through the lifted
5249    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5250    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5251    // and `:politicas :circuit-breaker :window` simultaneously via
5252    // this shared codec.
5253
5254    #[test]
5255    fn duration_codec_parse_rejects_leading_nbsp() {
5256        // NBSP prefix — the strictly-complementary drift class the
5257        // ASCII byte-scan cannot see. `str::trim` strips it silently
5258        // and the value drifts to `"30s"` on next serialize.
5259        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5260        assert!(
5261            err.contains("non-ASCII Unicode whitespace character"),
5262            "expected non-ASCII whitespace diagnostic in {err:?}"
5263        );
5264        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5265    }
5266
5267    #[test]
5268    fn duration_codec_parse_rejects_trailing_line_separator() {
5269        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5270        // footgun.
5271        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5272        assert!(
5273            err.contains("non-ASCII Unicode whitespace character"),
5274            "expected non-ASCII whitespace diagnostic in {err:?}"
5275        );
5276        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5277    }
5278
5279    #[test]
5280    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5281        // Positive-control pin: every ASCII-only canonical form the
5282        // renderer emits stays accepted through the new arm.
5283        assert_eq!(
5284            duration_codec::parse("30s").unwrap(),
5285            Duration::from_secs(30)
5286        );
5287        assert_eq!(
5288            duration_codec::parse("500ms").unwrap(),
5289            Duration::from_millis(500)
5290        );
5291        assert_eq!(
5292            duration_codec::parse("1h").unwrap(),
5293            Duration::from_secs(3600)
5294        );
5295    }
5296
5297    #[test]
5298    fn restart_window_serde_rejects_non_ascii_whitespace() {
5299        // The shared codec backs `SupervisorSpec::restart_window` — so
5300        // the new non-ASCII Unicode whitespace arm applies on serde
5301        // deserialize for the typed Supervisor slot. A
5302        // `{"restartWindow":" 30s"}` payload that previously
5303        // survived the ASCII byte-scan (only ASCII whitespace was
5304        // refused) is now refused at deserialize with the
5305        // non-ASCII-whitespace-and-codepoint diagnostic.
5306        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5307            \"restartWindow\":\"\u{00A0}30s\",\
5308            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5309        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5310        let msg = err.to_string();
5311        assert!(
5312            msg.contains("non-ASCII Unicode whitespace character"),
5313            "expected non-ASCII whitespace diagnostic in {msg:?}"
5314        );
5315        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5316    }
5317
5318    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5319
5320    #[test]
5321    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5322        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5323        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5324        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5325        // name the exact camelCase JSON keys the
5326        // `#[serde(rename_all = "camelCase")]` attribute on
5327        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5328        // field carries `Some(_)` / non-empty) and pin that each canonical
5329        // byte-sequence appears verbatim in the JSON — a future accidental
5330        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5331        // name flip at the derive attribute (any of which would silently
5332        // break every downstream JSON consumer that reaches for one of the
5333        // four consts via `Value::get(...)`) surfaces here as a build-time
5334        // test failure at `supervisor.rs`, not as an apply-time
5335        // `.get(<stale-canonical-const>)` returning `None` far from the
5336        // derive-attr drift's commit. Peer with the sibling
5337        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5338        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5339        // M2 typed-slot family established, extended here to close the
5340        // top-level Supervisor axis.
5341        let spec = SupervisorSpec {
5342            estrategia: RestartStrategy::OneForOne,
5343            max_restarts: 5,
5344            restart_window: Some(Duration::from_secs(60)),
5345            children: vec![ChildSpec {
5346                caixa: "w".into(),
5347                versao: "^0.1".into(),
5348                restart: RestartPolicy::Permanent,
5349            }],
5350        };
5351        let json = serde_json::to_string(&spec).unwrap();
5352        for key in [
5353            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5354            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5355            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5356            crate::render::SUPERVISOR_KEY_CHILDREN,
5357        ] {
5358            let quoted = format!("\"{key}\"");
5359            assert!(
5360                json.contains(&quoted),
5361                "serialized SupervisorSpec must carry the lifted \
5362                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5363                 the JSON emission (got: {json})",
5364            );
5365        }
5366    }
5367
5368    #[test]
5369    fn supervisor_key_consts_are_pairwise_distinct() {
5370        // Cross-axis drift-detection pin: a future collapse of two
5371        // canonical top-level byte-strings onto the same value (e.g. an
5372        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5373        // also read `"estrategia"`) would silently reroute every
5374        // downstream probe on one axis onto the sibling axis's overlay
5375        // entry and pass every propagation-probe test that expected only
5376        // the stale axis's value. Peer of the sibling four-way distinct
5377        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5378        let all = [
5379            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5380            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5381            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5382            crate::render::SUPERVISOR_KEY_CHILDREN,
5383        ];
5384        for (i, a) in all.iter().enumerate() {
5385            for b in all.iter().skip(i + 1) {
5386                assert_ne!(
5387                    a, b,
5388                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5389                     canonical byte-sequences — got `{a}` == `{b}`",
5390                );
5391            }
5392        }
5393    }
5394
5395    #[test]
5396    fn supervisor_key_consts_are_lower_camel_case_shape() {
5397        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5398        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5399        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5400        // capital, no whitespace / dots) — the canonical shape the
5401        // `#[serde(rename_all = "camelCase")]` derive produces on
5402        // `SupervisorSpec`. A future flip to a non-camelCase attribute
5403        // at the derive surfaces both here (this test fails on the
5404        // stale-constant shape) and at
5405        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5406        // (that test fails on the mismatch between const and derive).
5407        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5408        // (d8b8b4f) on the sibling M2 `:limits` axis.
5409        for key in [
5410            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5411            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5412            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5413            crate::render::SUPERVISOR_KEY_CHILDREN,
5414        ] {
5415            assert!(
5416                !key.is_empty(),
5417                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5418            );
5419            let first = key.chars().next().unwrap();
5420            assert!(
5421                first.is_ascii_lowercase(),
5422                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5423                 (got {key:?}, leads with {first:?})",
5424            );
5425            assert!(
5426                key.chars().all(|c| c.is_ascii_alphanumeric()),
5427                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5428                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5429            );
5430        }
5431    }
5432
5433    #[test]
5434    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5435        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5436        // (camelCase JSON keys, no leading colon) must never collide
5437        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5438        // consts (kebab-case author-facing labels with leading colon)
5439        // that sit next to them at `caixa_core::render`. Both families
5440        // cover the same four typed Supervisor slots on two distinct
5441        // axes (author-side kebab vs renderer-side camelCase);
5442        // collapsing either family onto the other's byte-shape would
5443        // silently reroute the render-side probe onto the author-facing
5444        // surface, or vice versa. Peer of the byte-distinctness
5445        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5446        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5447        let pairs = [
5448            (
5449                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5450                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
5451            ),
5452            (
5453                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5454                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
5455            ),
5456            (
5457                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5458                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
5459            ),
5460            (
5461                crate::render::SUPERVISOR_KEY_CHILDREN,
5462                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
5463            ),
5464        ];
5465        for (json_key, author_key) in pairs {
5466            assert_ne!(
5467                json_key, author_key,
5468                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
5469                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
5470                 got JSON `{json_key}` == author `{author_key}`",
5471            );
5472        }
5473    }
5474
5475    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
5476
5477    #[test]
5478    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
5479        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
5480        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
5481        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
5482        // keys the `#[serde(rename_all = "camelCase")]` attribute on
5483        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
5484        // pin that each canonical byte-sequence appears verbatim in the
5485        // JSON — a future accidental `rename_all = "snake_case"` /
5486        // `"kebab-case"` / verbatim-field-name flip at the derive
5487        // attribute (any of which would silently break every downstream
5488        // JSON consumer that reaches for one of the three consts via
5489        // `Value::get(...)`) surfaces here as a build-time test failure at
5490        // `supervisor.rs`, not as an apply-time
5491        // `.get(<stale-canonical-const>)` returning `None` far from the
5492        // derive-attr drift's commit. Peer with the enclosing
5493        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5494        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
5495        // discipline the SupervisorSpec top-level lift established,
5496        // extended here to the sibling per-`:children` entry `ChildSpec`
5497        // derive so the last M2 typed-struct sub-block
5498        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
5499        // surface without a lifted serde-key peer joins the substrate's
5500        // "one canonical byte-string per typed serialized-key axis"
5501        // discipline.
5502        let c = ChildSpec {
5503            caixa: "worker".into(),
5504            versao: "^0.1".into(),
5505            restart: RestartPolicy::Permanent,
5506        };
5507        let json = serde_json::to_string(&c).unwrap();
5508        for key in [
5509            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5510            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5511            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5512        ] {
5513            let quoted = format!("\"{key}\"");
5514            assert!(
5515                json.contains(&quoted),
5516                "serialized ChildSpec must carry the lifted \
5517                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
5518                 in the JSON emission (got: {json})",
5519            );
5520        }
5521    }
5522
5523    #[test]
5524    fn supervisor_child_key_consts_are_pairwise_distinct() {
5525        // Cross-axis drift-detection pin: a future collapse of two
5526        // canonical `ChildSpec` per-entry byte-strings onto the same
5527        // value (e.g. an accidental copy-paste flip of
5528        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
5529        // silently reroute every downstream probe on one axis onto the
5530        // sibling axis's overlay entry and pass every propagation-probe
5531        // test that expected only the stale axis's value. Peer of the
5532        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
5533        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
5534        // pair (ce80ca0).
5535        let all = [
5536            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5537            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5538            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5539        ];
5540        for (i, a) in all.iter().enumerate() {
5541            for b in all.iter().skip(i + 1) {
5542                assert_ne!(
5543                    a, b,
5544                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
5545                     distinct canonical byte-sequences — got `{a}` == `{b}`",
5546                );
5547            }
5548        }
5549    }
5550
5551    #[test]
5552    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
5553        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
5554        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5555        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5556        // capital, no whitespace / dots) — the canonical shape the
5557        // `#[serde(rename_all = "camelCase")]` derive produces on
5558        // `ChildSpec`. A future flip to a non-camelCase attribute at the
5559        // derive surfaces both here (this test fails on the
5560        // stale-constant shape) and at
5561        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
5562        // (that test fails on the mismatch between const and derive).
5563        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
5564        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
5565        for key in [
5566            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5567            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5568            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5569        ] {
5570            assert!(
5571                !key.is_empty(),
5572                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
5573            );
5574            let first = key.chars().next().unwrap();
5575            assert!(
5576                first.is_ascii_lowercase(),
5577                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
5578                 byte (got {key:?}, leads with {first:?})",
5579            );
5580            assert!(
5581                key.chars().all(|c| c.is_ascii_alphanumeric()),
5582                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
5583                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5584            );
5585        }
5586    }
5587
5588    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
5589
5590    #[test]
5591    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
5592        // The fail-before-pass-after pin: pre-lift there was no
5593        // single-source binding between the [`RestartStrategy`] variant
5594        // name the un-`rename`d `Serialize` derive emits under
5595        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
5596        // every downstream cluster-side dispatcher (the future
5597        // wasm-operator's per-supervisor sibling-restart branch, the
5598        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5599        // admission-time enum-arm bind, the `caixa-operator`'s
5600        // hierarchical reconciliation scheduler's per-strategy fan-out)
5601        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
5602        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
5603        // override, or a variant rename in the source — would silently
5604        // rebrand the emitted scalar under one spelling while every
5605        // downstream dispatcher still probed the other, with the failure
5606        // surfacing at the operator's reconcile posture (subtrees coming
5607        // up under the `default()` `OneForOne` arm rather than the typed
5608        // slot's declared strategy — a bad child would then only take
5609        // itself down instead of the sibling set the author intended, so
5610        // shared-state children fall out of sync) far from the source
5611        // rebrand commit and with no field naming the drift. Pinning the
5612        // two paths (the `Serialize` derive's serialized string AND the
5613        // [`RestartStrategy::as_str`] helper) to the same four lifted
5614        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
5615        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
5616        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
5617        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
5618        // byte-strings makes any future drift on either endpoint fail
5619        // here at caixa-core build time. Peer of the M3
5620        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
5621        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
5622        // three-path-convergence discipline, extended to close the
5623        // OTP-shaped per-supervisor sibling-restart axis.
5624        for (variant, expected) in [
5625            (
5626                RestartStrategy::OneForOne,
5627                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5628            ),
5629            (
5630                RestartStrategy::OneForAll,
5631                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5632            ),
5633            (
5634                RestartStrategy::RestForOne,
5635                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5636            ),
5637            (
5638                RestartStrategy::SimpleOneForOne,
5639                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5640            ),
5641        ] {
5642            let json = serde_json::to_string(&variant).unwrap();
5643            assert_eq!(
5644                json,
5645                format!("\"{expected}\""),
5646                "RestartStrategy::{variant:?} must serialize to {expected:?}"
5647            );
5648            assert_eq!(
5649                variant.as_str(),
5650                expected,
5651                "RestartStrategy::{variant:?}.as_str() must return the lifted \
5652                 SUPERVISOR_ESTRATEGIA_* constant"
5653            );
5654        }
5655    }
5656
5657    #[test]
5658    fn supervisor_estrategia_consts_are_pairwise_distinct() {
5659        // Cross-arm drift-detection pin: a future collapse of two
5660        // canonical variant byte-strings onto the same value (e.g. an
5661        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
5662        // to also read `"OneForOne"`) would silently reroute every
5663        // downstream operator's per-strategy dispatch onto the sibling
5664        // arm's reconcile branch and pass every propagation-probe test
5665        // that expected only the stale arm's value — the mis-strategied
5666        // subtree would come up with the wrong sibling-restart posture
5667        // on every subsequent failure. Peer of the sibling four-way
5668        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
5669        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
5670        let all = [
5671            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5672            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5673            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5674            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5675        ];
5676        for (i, a) in all.iter().enumerate() {
5677            for (j, b) in all.iter().enumerate() {
5678                if i != j {
5679                    assert_ne!(
5680                        a, b,
5681                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
5682                         — got duplicate {a:?} at indices {i} and {j}",
5683                    );
5684                }
5685            }
5686        }
5687    }
5688
5689    #[test]
5690    fn restart_strategy_display_routes_through_as_str_helper() {
5691        // The fail-before-pass-after pin on the first half of the
5692        // three-path convergence: pre-convergence the sibling
5693        // OTP-shape typed enum [`RestartStrategy`] carried a
5694        // [`std::fmt::Display`] surface via its
5695        // `#[discriminant(also_display)]` gen-platform derive route,
5696        // which arrived kebab-case as `"one-for-one"` /
5697        // `"one-for-all"` / `"rest-for-one"` /
5698        // `"simple-one-for-one"` while the wire format ran as
5699        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
5700        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
5701        // Every consumer reaching for a strategy byte-string past the
5702        // wire format had to pick between three paths
5703        // ([`RestartStrategy::as_str`], the `Serialize` derive's
5704        // serialized string, or `format!("{v}")` on the
5705        // discriminant-Display route), any two of which a future
5706        // variant rename or `#[serde(rename_all = "kebab-case")]`
5707        // attribute would silently desynchronize. Wiring
5708        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
5709        // closes the third path: every `format!("{v}")` call reaches
5710        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5711        // const the wire format and the [`RestartStrategy::as_str`]
5712        // helper already route through, so a future variant rename
5713        // lands at exactly one place. Pin the routing here so a future
5714        // `impl std::fmt::Display for RestartStrategy`
5715        // reimplementation that hand-rolls the arms instead of
5716        // delegating to [`RestartStrategy::as_str`] fails at
5717        // caixa-core build time. Peer of the M3
5718        // `placement_strategy_display_routes_through_as_str_helper`
5719        // (cc8f749) which the M3 axis converged first.
5720        for &variant in RestartStrategy::ALL {
5721            assert_eq!(
5722                variant.to_string(),
5723                variant.as_str(),
5724                "RestartStrategy::{variant:?} Display must route through \
5725                 RestartStrategy::as_str (single source of truth: the lifted \
5726                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
5727            );
5728        }
5729    }
5730
5731    #[test]
5732    fn restart_strategy_display_matches_serialized_wire_byte_string() {
5733        // The fail-before-pass-after pin on the second half of the
5734        // three-path convergence: `Display` (user-facing text) agrees
5735        // byte-for-byte with the `Serialize` derive's wire format
5736        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
5737        // scalar) on every variant. Pre-convergence the two paths
5738        // were structurally independent — a future
5739        // `#[serde(rename_all = "kebab-case")]` attribute on the
5740        // enum would silently rebrand the emitted wire scalar
5741        // (`one-for-one`, `one-for-all`, `rest-for-one`,
5742        // `simple-one-for-one`) while every consumer that
5743        // pretty-prints the strategy (the future wasm-operator's
5744        // per-supervisor sibling-restart-strategy diagnostic line,
5745        // the future `feira app graph` per-supervisor strategy line,
5746        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5747        // materializer's admission-webhook rejection body) would
5748        // still emit the PascalCase form the `as_str` / `Display`
5749        // route returns, with the mismatch surfacing at consumer
5750        // parse time / operator dispatch time far from the source
5751        // rebrand commit. Pin the two paths byte-for-byte here so any
5752        // future serde-attribute or variant-rename drift is a
5753        // caixa-core-build-time test failure at this call, not a
5754        // silent per-consumer dispatch miss. Peer of the M3
5755        // `placement_strategy_display_matches_serialized_wire_byte_string`
5756        // (cc8f749) which the M3 axis converged first.
5757        for &variant in RestartStrategy::ALL {
5758            let wire = serde_json::to_string(&variant).unwrap();
5759            let unquoted = wire
5760                .strip_prefix('"')
5761                .and_then(|s| s.strip_suffix('"'))
5762                .expect("serialized RestartStrategy is a JSON string");
5763            assert_eq!(
5764                variant.to_string(),
5765                unquoted,
5766                "RestartStrategy::{variant:?} Display byte-string must match the \
5767                 Serialize derive's wire byte-string (three-path convergence: \
5768                 Display + as_str + Serialize all resolve to the same \
5769                 SUPERVISOR_ESTRATEGIA_* const)"
5770            );
5771        }
5772    }
5773
5774    #[test]
5775    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
5776        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
5777        // exhaustive-iteration surface: every variant appears exactly
5778        // once, and the slice length matches the arm count of the
5779        // closed set. Every consumer that walks the accepted-strategy
5780        // set (a future `feira supervisor --estrategia …` CLI-side
5781        // arg-parse's "did you mean" hint, a future M4 admission-
5782        // webhook's rejection body naming the accepted-`:estrategia`
5783        // list, the [`RestartStrategy::from_wire`] reverse-projection
5784        // consumers that iterate the accept-set for diagnostic
5785        // rendering) reads through this slice, so a future arm addition
5786        // that grows the enum but forgets to grow [`Self::ALL`]
5787        // silently truncates every downstream consumer's accept-set at
5788        // the same pre-addition boundary — this pin fails at caixa-core
5789        // build time on the pairwise-distinct + arm-count invariants.
5790        //
5791        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
5792        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
5793        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
5794        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5795        // pins on the peer closed-set typed-enum axes.
5796        let all: &[RestartStrategy] = RestartStrategy::ALL;
5797        assert_eq!(
5798            all.len(),
5799            4,
5800            "RestartStrategy::ALL must enumerate every variant of the \
5801             four-arm closed set (OneForOne, OneForAll, RestForOne, \
5802             SimpleOneForOne); got {all:?}"
5803        );
5804        for (i, a) in all.iter().enumerate() {
5805            for (j, b) in all.iter().enumerate() {
5806                if i != j {
5807                    assert_ne!(
5808                        a, b,
5809                        "RestartStrategy::ALL must carry every variant exactly \
5810                         once — got duplicate {a:?} at indices {i} and {j}"
5811                    );
5812                }
5813            }
5814        }
5815        for variant in [
5816            RestartStrategy::OneForOne,
5817            RestartStrategy::OneForAll,
5818            RestartStrategy::RestForOne,
5819            RestartStrategy::SimpleOneForOne,
5820        ] {
5821            assert!(
5822                all.contains(&variant),
5823                "RestartStrategy::ALL must contain {variant:?} — a future arm \
5824                 addition that grows the enum but forgets to grow the ALL slice \
5825                 silently truncates every downstream consumer's accept-set at \
5826                 the pre-addition boundary"
5827            );
5828        }
5829    }
5830
5831    #[test]
5832    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
5833        // Fail-before-pass-after pin on the forward accept-set of the
5834        // [`RestartStrategy::from_wire`] reverse projection: every
5835        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5836        // constant the [`RestartStrategy::as_str`] emitter walks parses
5837        // back to its paired variant. Any future arm addition that
5838        // grows the emitter's `as_str` match but forgets to grow the
5839        // parser's `from_wire` match silently splits the two halves of
5840        // the round-trip — the wire byte-string one non-serde consumer
5841        // parses from the one the emitter wrote — with the failure
5842        // surfacing at parse time far from the rebrand commit. Pinning
5843        // the four-arm accept-set here catches the drift at caixa-core
5844        // build time.
5845        //
5846        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
5847        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
5848        // accept-set pins on the peer closed-set typed-enum `str → Self`
5849        // axes.
5850        for (wire, expected) in [
5851            (
5852                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5853                RestartStrategy::OneForOne,
5854            ),
5855            (
5856                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5857                RestartStrategy::OneForAll,
5858            ),
5859            (
5860                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5861                RestartStrategy::RestForOne,
5862            ),
5863            (
5864                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5865                RestartStrategy::SimpleOneForOne,
5866            ),
5867        ] {
5868            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
5869                panic!(
5870                    "RestartStrategy::from_wire({wire:?}) must accept every \
5871                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
5872                     lifted canonical byte-string that RestartStrategy::{expected:?} \
5873                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
5874                )
5875            });
5876            assert_eq!(
5877                parsed, expected,
5878                "RestartStrategy::from_wire({wire:?}) must return \
5879                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
5880            );
5881        }
5882    }
5883
5884    #[test]
5885    fn restart_strategy_from_wire_round_trips_through_as_str() {
5886        // Fail-before-pass-after pin on the closed round-trip between
5887        // the forward [`RestartStrategy::as_str`] emitter and the
5888        // reverse [`RestartStrategy::from_wire`] parser: for every
5889        // variant in [`RestartStrategy::ALL`], parsing the emitter's
5890        // output must return exactly the same variant. Any per-arm
5891        // divergence — a future arm added to `as_str` but not
5892        // `from_wire`, an accidental copy-paste flip in one but not
5893        // the other — silently splits the emit and parse halves and
5894        // the failure surfaces at consumer parse time far from the
5895        // drift site. The `ALL`-iterating shape means a future arm
5896        // addition picks up the coverage by construction.
5897        //
5898        // Peer of the sibling
5899        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
5900        // (18c7342) round-trip pin on
5901        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
5902        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
5903        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
5904        for &variant in RestartStrategy::ALL {
5905            let wire = variant.as_str();
5906            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
5907                panic!(
5908                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
5909                     must be Some({variant:?}) — the two halves of the round-trip \
5910                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
5911                     got None on wire byte-string {wire:?}"
5912                )
5913            });
5914            assert_eq!(
5915                parsed, variant,
5916                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
5917                 must round-trip to the same variant; got {parsed:?}"
5918            );
5919        }
5920    }
5921
5922    #[test]
5923    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
5924        // Fail-before-pass-after pin on the closed-set refusal
5925        // discipline of [`RestartStrategy::from_wire`]: every
5926        // byte-string outside the four-arm accept-set returns `None`
5927        // rather than silently collapsing onto the [`Default`]
5928        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
5929        // exercised here sweeps the load-bearing drift shapes: the
5930        // empty string (a stripped serde-attribute drift), all-
5931        // whitespace strings (the canonical text-editor accidental
5932        // padding shape), the kebab-case dispatcher-catalog identities
5933        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
5934        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
5935        // derived [`std::str::FromStr`] accept-set, which parses the
5936        // *other* axis of this enum's two-axis split and must not leak
5937        // into the `from_wire` PascalCase-wire accept-set), the
5938        // lowercased single-word forms (`"oneforone"`), the padded
5939        // canonical scalar (`" OneForOne "`), the trailing-newline
5940        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
5941        // (`"AllForOne"` — the canonical typo direction).
5942        //
5943        // Peer of the sibling
5944        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
5945        // (2aa6d23) +
5946        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
5947        // (18c7342) refusal pins on the peer closed-set typed-enum
5948        // axes.
5949        for bad in [
5950            "",
5951            " ",
5952            "\n",
5953            "\t",
5954            "one-for-one",
5955            "one-for-all",
5956            "rest-for-one",
5957            "simple-one-for-one",
5958            "oneforone",
5959            "OneForOnes",
5960            "one_for_one",
5961            "one for one",
5962            "ONEFORONE",
5963            "OneForOne ",
5964            " OneForOne",
5965            " SimpleOneForOne ",
5966            "OneForOne\n",
5967            "restforone",
5968            "REST_FOR_ONE",
5969            "AllForOne",
5970            "Simple",
5971            "?",
5972        ] {
5973            assert!(
5974                RestartStrategy::from_wire(bad).is_none(),
5975                "RestartStrategy::from_wire({bad:?}) must return None — the \
5976                 parser's accept-set is exactly the four RestartStrategy::as_str \
5977                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
5978                 and this byte-string is outside that closed set"
5979            );
5980        }
5981    }
5982
5983    #[test]
5984    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
5985        // Fail-before-pass-after pin on the fourth path of the four-path
5986        // convergence: `from_wire` (the reverse projection) inverts the
5987        // `Serialize` derive's wire byte-string on every variant.
5988        // Together with the pre-existing three-path convergence
5989        // (`Display` + `as_str` + `Serialize` all resolve to the same
5990        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
5991        // pinned by
5992        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
5993        // this closes the round-trip: the wire byte-string the
5994        // `Serialize` derive emits parses back to the same variant
5995        // through `from_wire`, so any future serde-attribute or variant-
5996        // rename drift on the emit half now surfaces as a matched drift
5997        // on the parse half at caixa-core build time — the two halves
5998        // migrate as a unit through the lifted consts on any future
5999        // rename, and the round-trip cannot silently split.
6000        //
6001        // Peer of the sibling
6002        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6003        // (18c7342) wire-format pin on
6004        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6005        for &variant in RestartStrategy::ALL {
6006            let wire = serde_json::to_string(&variant).unwrap();
6007            let unquoted = wire
6008                .strip_prefix('"')
6009                .and_then(|s| s.strip_suffix('"'))
6010                .expect("serialized RestartStrategy is a JSON string");
6011            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6012                panic!(
6013                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6014                     Serialize derive's wire byte-string for \
6015                     RestartStrategy::{variant:?} — the four-path convergence \
6016                     (Display + as_str + Serialize + from_wire) resolves through \
6017                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6018                )
6019            });
6020            assert_eq!(
6021                parsed, variant,
6022                "RestartStrategy::from_wire of the Serialize derive's wire \
6023                 byte-string for RestartStrategy::{variant:?} must round-trip \
6024                 to the same variant; got {parsed:?}"
6025            );
6026        }
6027    }
6028
6029    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
6030
6031    #[test]
6032    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
6033        // The fail-before-pass-after pin: pre-lift there was no
6034        // single-source binding between the [`RestartPolicy`] variant
6035        // name the un-`rename`d `Serialize` derive emits under
6036        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
6037        // byte-string every downstream cluster-side dispatcher (the
6038        // future wasm-operator's per-child post-exit restart-decision
6039        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6040        // materializer's admission-time enum-arm bind, the
6041        // `caixa-operator`'s hierarchical reconciliation scheduler's
6042        // per-child-policy fan-out) probes verbatim. A future
6043        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
6044        // or a per-variant `#[serde(rename = "…")]` override, or a
6045        // variant rename in the source — would silently rebrand the
6046        // emitted scalar under one spelling while every downstream
6047        // dispatcher still probed the other, with the failure surfacing
6048        // at the operator's reconcile posture (children coming up under
6049        // the `default()` `Permanent` arm rather than the typed slot's
6050        // declared policy — a `:temporary` `oneShot` child would be
6051        // restarted on clean exit, treating the successful-completion
6052        // signal as failure and re-running the completion-terminal
6053        // one-shot indefinitely; a `:transient` child that clean-exited
6054        // would be restarted, masking the clean-completion contract)
6055        // far from the source rebrand commit and with no field naming
6056        // the drift. Pinning the two paths (the `Serialize` derive's
6057        // serialized string AND the [`RestartPolicy::as_str`] helper)
6058        // to the same three lifted
6059        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
6060        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
6061        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
6062        // byte-strings makes any future drift on either endpoint fail
6063        // here at caixa-core build time. Peer of the sibling
6064        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
6065        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6066        // and the M3
6067        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6068        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
6069        // same three-path-convergence discipline, extended to close the
6070        // third OTP-shaped closed-enum discriminator axis on the caixa
6071        // typed surface (per-child restart-decision policy).
6072        for (variant, expected) in [
6073            (
6074                RestartPolicy::Permanent,
6075                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6076            ),
6077            (
6078                RestartPolicy::Temporary,
6079                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6080            ),
6081            (
6082                RestartPolicy::Transient,
6083                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6084            ),
6085        ] {
6086            let json = serde_json::to_string(&variant).unwrap();
6087            assert_eq!(
6088                json,
6089                format!("\"{expected}\""),
6090                "RestartPolicy::{variant:?} must serialize to {expected:?}"
6091            );
6092            assert_eq!(
6093                variant.as_str(),
6094                expected,
6095                "RestartPolicy::{variant:?}.as_str() must return the lifted \
6096                 SUPERVISOR_CHILD_RESTART_* constant"
6097            );
6098        }
6099    }
6100
6101    #[test]
6102    fn supervisor_child_restart_consts_are_pairwise_distinct() {
6103        // Cross-arm drift-detection pin: a future collapse of two
6104        // canonical variant byte-strings onto the same value (e.g. an
6105        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
6106        // to also read `"Permanent"`) would silently reroute every
6107        // downstream operator's per-child-policy dispatch onto the
6108        // sibling arm's reconcile branch and pass every propagation-probe
6109        // test that expected only the stale arm's value — a `:transient`
6110        // child would come up under the `:permanent` restart-decision
6111        // posture on every subsequent clean exit, so a completion-terminal
6112        // child would be restarted indefinitely against its declared
6113        // policy. Peer of the sibling
6114        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
6115        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6116        // and the four-way distinct pin
6117        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
6118        // top-level `SUPERVISOR_KEY_*` axis.
6119        let all = [
6120            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6121            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6122            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6123        ];
6124        for (i, a) in all.iter().enumerate() {
6125            for (j, b) in all.iter().enumerate() {
6126                if i != j {
6127                    assert_ne!(
6128                        a, b,
6129                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
6130                         — got duplicate {a:?} at indices {i} and {j}",
6131                    );
6132                }
6133            }
6134        }
6135    }
6136
6137    #[test]
6138    fn restart_policy_display_routes_through_as_str_helper() {
6139        // The fail-before-pass-after pin on the first half of the
6140        // three-path convergence: pre-convergence [`RestartPolicy`]
6141        // carried a [`std::fmt::Display`] surface via its
6142        // `#[discriminant(also_display)]` gen-platform derive route,
6143        // which arrived kebab-case as `"permanent"` / `"temporary"`
6144        // / `"transient"` on this three-arm enum (whose variant
6145        // names each collapse to their own lowercase form under the
6146        // kebab-case transform) while the wire format ran as
6147        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
6148        // through the un-`rename`d serde derive. Every consumer
6149        // reaching for a policy byte-string past the wire format had
6150        // to pick between three paths ([`RestartPolicy::as_str`],
6151        // the `Serialize` derive's serialized string, or
6152        // `format!("{v}")` on the discriminant-Display route), any
6153        // two of which a future variant rename or
6154        // `#[serde(rename_all = "kebab-case")]` attribute would
6155        // silently desynchronize. Wiring [`std::fmt::Display`]
6156        // through [`RestartPolicy::as_str`] closes the third path:
6157        // every `format!("{v}")` call reaches the same lifted
6158        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
6159        // wire format and the [`RestartPolicy::as_str`] helper
6160        // already route through, so a future variant rename lands at
6161        // exactly one place. Pin the routing here so a future
6162        // `impl std::fmt::Display for RestartPolicy`
6163        // reimplementation that hand-rolls the arms instead of
6164        // delegating to [`RestartPolicy::as_str`] fails at
6165        // caixa-core build time. Peer of the sibling
6166        // [`restart_strategy_display_routes_through_as_str_helper`]
6167        // on the per-supervisor sibling-restart-strategy axis and
6168        // the M3
6169        // `placement_strategy_display_routes_through_as_str_helper`
6170        // (cc8f749) — the third of three OTP-shape closed-enum
6171        // discriminator axes on the caixa typed surface now
6172        // converged onto the same three-path
6173        // (Display → as_str → lifted const) discipline.
6174        for variant in [
6175            RestartPolicy::Permanent,
6176            RestartPolicy::Temporary,
6177            RestartPolicy::Transient,
6178        ] {
6179            assert_eq!(
6180                variant.to_string(),
6181                variant.as_str(),
6182                "RestartPolicy::{variant:?} Display must route through \
6183                 RestartPolicy::as_str (single source of truth: the lifted \
6184                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
6185            );
6186        }
6187    }
6188
6189    #[test]
6190    fn restart_policy_display_matches_serialized_wire_byte_string() {
6191        // The fail-before-pass-after pin on the second half of the
6192        // three-path convergence: `Display` (user-facing text) agrees
6193        // byte-for-byte with the `Serialize` derive's wire format
6194        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
6195        // scalar) on every variant. Pre-convergence the two paths
6196        // were structurally independent — a future
6197        // `#[serde(rename_all = "kebab-case")]` attribute on the
6198        // enum would silently rebrand the emitted wire scalar
6199        // (`permanent`, `temporary`, `transient`) while every
6200        // consumer that pretty-prints the policy (the future
6201        // wasm-operator's per-child post-exit restart-decision
6202        // diagnostic line, the future `feira app graph` per-child
6203        // restart column, the future M4
6204        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6205        // per-child admission-webhook rejection body) would still
6206        // emit the PascalCase form the `as_str` / `Display` route
6207        // returns, with the mismatch surfacing at consumer parse
6208        // time / operator dispatch time far from the source rebrand
6209        // commit. Pin the two paths byte-for-byte here so any future
6210        // serde-attribute or variant-rename drift is a
6211        // caixa-core-build-time test failure at this call, not a
6212        // silent per-consumer dispatch miss. Peer of the sibling
6213        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
6214        // on the per-supervisor sibling-restart-strategy axis and
6215        // the M3
6216        // `placement_strategy_display_matches_serialized_wire_byte_string`
6217        // (cc8f749).
6218        for variant in [
6219            RestartPolicy::Permanent,
6220            RestartPolicy::Temporary,
6221            RestartPolicy::Transient,
6222        ] {
6223            let wire = serde_json::to_string(&variant).unwrap();
6224            let unquoted = wire
6225                .strip_prefix('"')
6226                .and_then(|s| s.strip_suffix('"'))
6227                .expect("serialized RestartPolicy is a JSON string");
6228            assert_eq!(
6229                variant.to_string(),
6230                unquoted,
6231                "RestartPolicy::{variant:?} Display byte-string must match the \
6232                 Serialize derive's wire byte-string (three-path convergence: \
6233                 Display + as_str + Serialize all resolve to the same \
6234                 SUPERVISOR_CHILD_RESTART_* const)"
6235            );
6236        }
6237    }
6238
6239    #[test]
6240    fn restart_policy_all_enumerates_every_variant_exactly_once() {
6241        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
6242        // exhaustive-iteration surface: every variant appears exactly
6243        // once, and the slice length matches the arm count of the
6244        // closed set. Every consumer that walks the accepted-policy
6245        // set (a future `feira supervisor --restart …` CLI-side
6246        // arg-parse's "did you mean" hint, a future M4 admission-
6247        // webhook's per-child rejection body naming the accepted-
6248        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
6249        // projection consumers that iterate the accept-set for
6250        // diagnostic rendering) reads through this slice, so a future
6251        // arm addition that grows the enum but forgets to grow
6252        // [`Self::ALL`] silently truncates every downstream consumer's
6253        // accept-set at the same pre-addition boundary — this pin
6254        // fails at caixa-core build time on the pairwise-distinct +
6255        // arm-count invariants.
6256        //
6257        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
6258        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
6259        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6260        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6261        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6262        // pins on the peer closed-set typed-enum axes.
6263        let all: &[RestartPolicy] = RestartPolicy::ALL;
6264        assert_eq!(
6265            all.len(),
6266            3,
6267            "RestartPolicy::ALL must enumerate every variant of the \
6268             three-arm closed set (Permanent, Temporary, Transient); \
6269             got {all:?}"
6270        );
6271        for (i, a) in all.iter().enumerate() {
6272            for (j, b) in all.iter().enumerate() {
6273                if i != j {
6274                    assert_ne!(
6275                        a, b,
6276                        "RestartPolicy::ALL must carry every variant exactly \
6277                         once — got duplicate {a:?} at indices {i} and {j}"
6278                    );
6279                }
6280            }
6281        }
6282        for variant in [
6283            RestartPolicy::Permanent,
6284            RestartPolicy::Temporary,
6285            RestartPolicy::Transient,
6286        ] {
6287            assert!(
6288                all.contains(&variant),
6289                "RestartPolicy::ALL must contain {variant:?} — a future arm \
6290                 addition that grows the enum but forgets to grow the ALL slice \
6291                 silently truncates every downstream consumer's accept-set at \
6292                 the pre-addition boundary"
6293            );
6294        }
6295    }
6296
6297    #[test]
6298    fn restart_policy_from_wire_accepts_every_lifted_constant() {
6299        // Fail-before-pass-after pin on the forward accept-set of the
6300        // [`RestartPolicy::from_wire`] reverse projection: every
6301        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
6302        // constant the [`RestartPolicy::as_str`] emitter walks parses
6303        // back to its paired variant. Any future arm addition that
6304        // grows the emitter's `as_str` match but forgets to grow the
6305        // parser's `from_wire` match silently splits the two halves of
6306        // the round-trip — the wire byte-string one non-serde consumer
6307        // parses from the one the emitter wrote — with the failure
6308        // surfacing at the operator's reconcile posture (a `:temporary`
6309        // `oneShot` child restarted on clean exit, a `:transient` child
6310        // restarted after clean completion) far from the rebrand
6311        // commit. Pinning the three-arm accept-set here catches the
6312        // drift at caixa-core build time.
6313        //
6314        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
6315        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
6316        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6317        // accept-set pins on the peer closed-set typed-enum `str → Self`
6318        // axes.
6319        for (wire, expected) in [
6320            (
6321                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6322                RestartPolicy::Permanent,
6323            ),
6324            (
6325                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6326                RestartPolicy::Temporary,
6327            ),
6328            (
6329                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6330                RestartPolicy::Transient,
6331            ),
6332        ] {
6333            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6334                panic!(
6335                    "RestartPolicy::from_wire({wire:?}) must accept every \
6336                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
6337                     lifted canonical byte-string that RestartPolicy::{expected:?} \
6338                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
6339                )
6340            });
6341            assert_eq!(
6342                parsed, expected,
6343                "RestartPolicy::from_wire({wire:?}) must return \
6344                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
6345            );
6346        }
6347    }
6348
6349    #[test]
6350    fn restart_policy_from_wire_round_trips_through_as_str() {
6351        // Fail-before-pass-after pin on the closed round-trip between
6352        // the forward [`RestartPolicy::as_str`] emitter and the
6353        // reverse [`RestartPolicy::from_wire`] parser: for every
6354        // variant in [`RestartPolicy::ALL`], parsing the emitter's
6355        // output must return exactly the same variant. Any per-arm
6356        // divergence — a future arm added to `as_str` but not
6357        // `from_wire`, an accidental copy-paste flip in one but not
6358        // the other — silently splits the emit and parse halves and
6359        // the failure surfaces at consumer parse time far from the
6360        // drift site. The `ALL`-iterating shape means a future arm
6361        // addition picks up the coverage by construction.
6362        //
6363        // Peer of the sibling
6364        // [`restart_strategy_from_wire_round_trips_through_as_str`]
6365        // (4eec29c) round-trip pin on
6366        // [`RestartStrategy::from_wire`] and the M3
6367        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6368        // (18c7342) round-trip pin on
6369        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6370        for &variant in RestartPolicy::ALL {
6371            let wire = variant.as_str();
6372            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6373                panic!(
6374                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6375                     must be Some({variant:?}) — the two halves of the round-trip \
6376                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
6377                     got None on wire byte-string {wire:?}"
6378                )
6379            });
6380            assert_eq!(
6381                parsed, variant,
6382                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6383                 must round-trip to the same variant; got {parsed:?}"
6384            );
6385        }
6386    }
6387
6388    #[test]
6389    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
6390        // Fail-before-pass-after pin on the closed-set refusal
6391        // discipline of [`RestartPolicy::from_wire`]: every
6392        // byte-string outside the three-arm accept-set returns `None`
6393        // rather than silently collapsing onto the [`Default`]
6394        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
6395        // exercised here sweeps the load-bearing drift shapes: the
6396        // empty string (a stripped serde-attribute drift), all-
6397        // whitespace strings (the canonical text-editor accidental
6398        // padding shape), the kebab-case dispatcher-catalog identities
6399        // (`"permanent"` / `"temporary"` / `"transient"` — the
6400        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
6401        // accept-set, which parses the *other* axis of this enum's
6402        // two-axis split and must not leak into the `from_wire`
6403        // PascalCase-wire accept-set — a lowercase leak here would
6404        // silently accept the operator's kebab-case
6405        // dispatcher-catalog probe under the wire-axis parser and mis-
6406        // route a `:permanent` intent), the padded canonical scalar
6407        // (`" Permanent "`), the trailing-newline shapes
6408        // (`"Permanent\n"`), the uppercase-single-word forms
6409        // (`"PERMANENT"`), and neighboring-but-unknown arms
6410        // (`"Restart"` — the canonical typo direction toward the
6411        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
6412        //
6413        // Peer of the sibling
6414        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
6415        // (4eec29c) +
6416        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6417        // (2aa6d23) +
6418        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6419        // (18c7342) refusal pins on the peer closed-set typed-enum
6420        // axes.
6421        for bad in [
6422            "",
6423            " ",
6424            "\n",
6425            "\t",
6426            "permanent",
6427            "temporary",
6428            "transient",
6429            "PERMANENT",
6430            "TEMPORARY",
6431            "TRANSIENT",
6432            "Permanents",
6433            "Permanent ",
6434            " Permanent",
6435            " Transient ",
6436            "Permanent\n",
6437            "perma",
6438            "Trans",
6439            "OneForOne",
6440            "Restart",
6441            "?",
6442        ] {
6443            assert!(
6444                RestartPolicy::from_wire(bad).is_none(),
6445                "RestartPolicy::from_wire({bad:?}) must return None — the \
6446                 parser's accept-set is exactly the three RestartPolicy::as_str \
6447                 outputs (Permanent, Temporary, Transient), and this \
6448                 byte-string is outside that closed set"
6449            );
6450        }
6451    }
6452
6453    #[test]
6454    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
6455        // Fail-before-pass-after pin on the fourth path of the four-path
6456        // convergence: `from_wire` (the reverse projection) inverts the
6457        // `Serialize` derive's wire byte-string on every variant.
6458        // Together with the pre-existing three-path convergence
6459        // (`Display` + `as_str` + `Serialize` all resolve to the same
6460        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
6461        // pinned by
6462        // [`restart_policy_display_matches_serialized_wire_byte_string`])
6463        // this closes the round-trip: the wire byte-string the
6464        // `Serialize` derive emits parses back to the same variant
6465        // through `from_wire`, so any future serde-attribute or variant-
6466        // rename drift on the emit half now surfaces as a matched drift
6467        // on the parse half at caixa-core build time — the two halves
6468        // migrate as a unit through the lifted consts on any future
6469        // rename, and the round-trip cannot silently split.
6470        //
6471        // Peer of the sibling
6472        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6473        // (4eec29c) wire-format pin on
6474        // [`RestartStrategy::from_wire`] and the M3
6475        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6476        // (18c7342) wire-format pin on
6477        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6478        for &variant in RestartPolicy::ALL {
6479            let wire = serde_json::to_string(&variant).unwrap();
6480            let unquoted = wire
6481                .strip_prefix('"')
6482                .and_then(|s| s.strip_suffix('"'))
6483                .expect("serialized RestartPolicy is a JSON string");
6484            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
6485                panic!(
6486                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
6487                     Serialize derive's wire byte-string for \
6488                     RestartPolicy::{variant:?} — the four-path convergence \
6489                     (Display + as_str + Serialize + from_wire) resolves through \
6490                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
6491                )
6492            });
6493            assert_eq!(
6494                parsed, variant,
6495                "RestartPolicy::from_wire of the Serialize derive's wire \
6496                 byte-string for RestartPolicy::{variant:?} must round-trip \
6497                 to the same variant; got {parsed:?}"
6498            );
6499        }
6500    }
6501
6502    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
6503    //
6504    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
6505    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
6506    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
6507    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
6508    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
6509    // the peer per-`:upgrade-from :from` axis. The three pins jointly
6510    // brace the accessor against every future silent detour that would
6511    // desynchronize it from the raw `.caixa` field access every consumer
6512    // previously open-coded.
6513
6514    #[test]
6515    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
6516        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
6517        // [`ChildSpec::nome`] must return the `:children :caixa` field
6518        // byte-for-byte across every DNS-1123-label value the upstream
6519        // [`crate::render::require_valid_dns_1123_label`] gate at
6520        // `SupervisorSpec::validate` admits. Peer of the sibling
6521        // `membro_nome_returns_caixa_byte_equal_across_permutations`
6522        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
6523        // substrate-primitive accessor must byte-equal the raw field
6524        // access verbatim across every author-declared value" discipline
6525        // extended to the M2 supervisor-tree per-`:children` arm. Pins
6526        // against a future silent detour that re-normalized the child
6527        // identity (an accidental `.to_lowercase()` — every `:children
6528        // :caixa` is validated as a DNS-1123 label upstream, so any
6529        // re-normalization is redundant + a drift surface between the
6530        // validator and the accessor), a namespace-prefix rewrite (an
6531        // accidental `format!("{namespace}/{caixa}")` per-CR
6532        // fully-qualified rewrite that didn't land on the peer axes), or
6533        // a per-cluster alias stamp the future wasm-operator's
6534        // hierarchical reconciliation scheduler authors on one consumer
6535        // without the others. Five values sweep the accept-set the
6536        // DNS-1123 gate upstream admits (short single-word / dashed /
6537        // v-suffixed / mixed-digit child names).
6538        for name in [
6539            "worker",
6540            "cache-server",
6541            "scratch-job",
6542            "orders-v2",
6543            "session-8080",
6544        ] {
6545            let c = ChildSpec {
6546                caixa: name.into(),
6547                versao: "^0.1".into(),
6548                restart: RestartPolicy::Permanent,
6549            };
6550            assert_eq!(
6551                c.nome(),
6552                name,
6553                "ChildSpec::nome must return :children :caixa verbatim \
6554                 (got {:?}, expected {name:?})",
6555                c.nome(),
6556            );
6557            assert_eq!(
6558                c.nome(),
6559                c.caixa.as_str(),
6560                "ChildSpec::nome must byte-equal the .caixa field access",
6561            );
6562        }
6563    }
6564
6565    #[test]
6566    fn child_spec_nome_borrows_from_caixa_storage() {
6567        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
6568        // `&str` slice that borrows from the typed slot's own [`String`]
6569        // storage — same-address invariant with `c.caixa.as_str()`. Pins
6570        // against a future silent detour that allocated a fresh `String`
6571        // (`self.caixa.clone()` in the body would type-check but silently
6572        // drop the borrow, and every downstream consumer that assumed
6573        // the returned slice outlives `&self` would break on a stale-
6574        // reference use-after-free — the [`crate::render::insert_first_seen`]
6575        // dedup key at [`SupervisorSpec::validate`], the
6576        // [`validate_no_self_supervision`] equality check against the
6577        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
6578        // borrow — each would silently misbehave if this accessor
6579        // produced a detached copy). Peer of the sibling
6580        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
6581        // M3 per-`:membros` axis and the
6582        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
6583        // first M2 slot scalar accessor.
6584        let c = ChildSpec {
6585            caixa: "worker".into(),
6586            versao: "^0.1".into(),
6587            restart: RestartPolicy::Permanent,
6588        };
6589        let name = c.nome();
6590        let caixa_slice = c.caixa.as_str();
6591        assert_eq!(
6592            name.as_ptr(),
6593            caixa_slice.as_ptr(),
6594            "ChildSpec::nome must borrow from the .caixa String's backing \
6595             storage — a fresh allocation here means the accessor no \
6596             longer names the substrate-primitive typed dispatch and \
6597             every downstream consumer would silently carry a detached \
6598             copy",
6599        );
6600        assert_eq!(
6601            name.len(),
6602            caixa_slice.len(),
6603            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
6604             as well as in address",
6605        );
6606    }
6607
6608    #[test]
6609    fn validate_gates_child_nome_through_lifted_accessor() {
6610        // Bilateral coherence pin: every `:children :caixa` that
6611        // [`SupervisorSpec::validate`] accepts is one
6612        // [`crate::render::require_valid_dns_1123_label`] accepts on the
6613        // accessor-projected value, and vice versa on the reject side.
6614        // This closes the "the validator reads through the accessor"
6615        // contract structurally — a future silent detour that made the
6616        // accessor return a different byte-string than the validator
6617        // gates against would surface here as a coverage mismatch, not
6618        // as an apply-time DNS-1123 rejection at
6619        // `metadata.name: Invalid value` far from the caixa.lisp source.
6620        // Peer of the M2 sibling
6621        // `validate_parses_prior_versao_through_lifted_accessor`
6622        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
6623        // `validate_membros` peer discipline.
6624        //
6625        // Accept-set sweep: five DNS-1123-label values the upstream gate
6626        // admits.
6627        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
6628            let s = SupervisorSpec {
6629                children: vec![ChildSpec {
6630                    caixa: ok_name.into(),
6631                    versao: "^0.1".into(),
6632                    restart: RestartPolicy::Permanent,
6633                }],
6634                ..SupervisorSpec::default()
6635            };
6636            s.validate().unwrap_or_else(|e| {
6637                panic!(
6638                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
6639                     (upstream DNS-1123 gate accepts it): got {e:?}",
6640                );
6641            });
6642            let c = ChildSpec {
6643                caixa: ok_name.into(),
6644                versao: "^0.1".into(),
6645                restart: RestartPolicy::Permanent,
6646            };
6647            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
6648                .unwrap_or_else(|()| {
6649                    panic!(
6650                        "require_valid_dns_1123_label must accept the accessor-projected \
6651                     :children :caixa {ok_name:?}",
6652                    );
6653                });
6654        }
6655        // Reject-set sweep: five DNS-1123-label-violating shapes the
6656        // upstream gate refuses (empty / uppercase / underscore / dot /
6657        // leading-hyphen). Every rejection at the validator must
6658        // correspond to a rejection when the accessor's projected value
6659        // is fed back through the shared gate.
6660        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
6661            let s = SupervisorSpec {
6662                children: vec![ChildSpec {
6663                    caixa: bad_name.into(),
6664                    versao: "^0.1".into(),
6665                    restart: RestartPolicy::Permanent,
6666                }],
6667                ..SupervisorSpec::default()
6668            };
6669            let err = s.validate().unwrap_err();
6670            assert!(
6671                matches!(
6672                    err,
6673                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
6674                ),
6675                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
6676                 via the DNS-1123 gate: got {err:?}",
6677            );
6678            let c = ChildSpec {
6679                caixa: bad_name.into(),
6680                versao: "^0.1".into(),
6681                restart: RestartPolicy::Permanent,
6682            };
6683            assert!(
6684                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
6685                    .is_err(),
6686                "require_valid_dns_1123_label must reject the accessor-projected \
6687                 :children :caixa {bad_name:?}",
6688            );
6689        }
6690    }
6691
6692    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
6693    //
6694    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
6695    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
6696    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
6697    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
6698    // trio on the peer per-`:children` `String`-carry axis. The three pins
6699    // jointly brace the accessor against every future silent detour that
6700    // would desynchronize it from the raw `.versao` field access the
6701    // requirement gate + error carrier previously open-coded.
6702    //
6703    // Closes the last unlifted per-`:children` `String`-carry axis: the
6704    // pair (`nome`, `versao_requirement`) now jointly projects the
6705    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
6706    // consumer that fans on per-child identity + version pin reads,
6707    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
6708    // pair discipline verbatim.
6709    #[test]
6710    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
6711        // The canonical per-`:children` child-`:versao`-scalar pin:
6712        // [`ChildSpec::versao_requirement`] must return the `:children
6713        // :versao` field byte-for-byte across every Cargo-shaped semver
6714        // requirement value the upstream
6715        // [`crate::render::require_valid_versao_requirement`] gate admits.
6716        // Peer of the sibling
6717        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
6718        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
6719        // substrate-primitive accessor must byte-equal the raw field
6720        // access verbatim across every author-declared value" discipline
6721        // extended to the M2 supervisor-tree per-`:children` arm. Pins
6722        // against a future silent detour that re-canonicalized the
6723        // requirement (an accidental `.to_string()` via
6724        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
6725        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
6726        // silently drifted the error carrier's quoted requirement away
6727        // from the source `caixa.lisp`, an accidental whitespace trim on
6728        // `"^ 0.1"` that no consumer ever produced from the field-access
6729        // side, an accidental per-cluster lacre-projected concrete-version
6730        // rewrite that didn't land on the peer requirement-gate call).
6731        // Five values sweep the accept-set the shared
6732        // [`crate::render::require_valid_versao_requirement`] gate admits
6733        // (caret / tilde / exact / wildcard / bare-major).
6734        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6735            let c = ChildSpec {
6736                caixa: "worker".into(),
6737                versao: req.into(),
6738                restart: RestartPolicy::Permanent,
6739            };
6740            assert_eq!(
6741                c.versao_requirement(),
6742                req,
6743                "ChildSpec::versao_requirement must return :children :versao \
6744                 verbatim (got {:?}, expected {req:?})",
6745                c.versao_requirement(),
6746            );
6747            assert_eq!(
6748                c.versao_requirement(),
6749                c.versao.as_str(),
6750                "ChildSpec::versao_requirement must byte-equal the .versao \
6751                 field access",
6752            );
6753        }
6754    }
6755
6756    #[test]
6757    fn child_spec_versao_requirement_borrows_from_versao_storage() {
6758        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
6759        // return a `&str` slice that borrows from the typed slot's own
6760        // [`String`] storage — same-address invariant with
6761        // `c.versao.as_str()`. Pins against a future silent detour that
6762        // allocated a fresh `String` (`self.versao.clone()` in the body
6763        // would type-check but silently drop the borrow, and every
6764        // downstream consumer that assumed the returned slice outlives
6765        // `&self` — the [`crate::render::require_valid_versao_requirement`]
6766        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
6767        // `.to_string()` carrier's byte-length assumption — would silently
6768        // misbehave if this accessor produced a detached copy). Peer of
6769        // the sibling `child_spec_nome_borrows_from_caixa_storage`
6770        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
6771        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
6772        // pin on the peer per-`:membros` `:versao` axis.
6773        let c = ChildSpec {
6774            caixa: "worker".into(),
6775            versao: "^0.1".into(),
6776            restart: RestartPolicy::Permanent,
6777        };
6778        let req = c.versao_requirement();
6779        let versao_slice = c.versao.as_str();
6780        assert_eq!(
6781            req.as_ptr(),
6782            versao_slice.as_ptr(),
6783            "ChildSpec::versao_requirement must borrow from the .versao \
6784             String's backing storage — a fresh allocation here means the \
6785             accessor no longer names the substrate-primitive typed \
6786             dispatch and every downstream consumer would silently carry \
6787             a detached copy",
6788        );
6789        assert_eq!(
6790            req.len(),
6791            versao_slice.len(),
6792            "ChildSpec::versao_requirement and .versao.as_str() must \
6793             byte-equal in length as well as in address",
6794        );
6795    }
6796
6797    #[test]
6798    fn validate_gates_child_versao_through_lifted_accessor() {
6799        // Bilateral coherence pin: every `:children :versao` that
6800        // [`SupervisorSpec::validate`] accepts is one
6801        // [`crate::render::require_valid_versao_requirement`] accepts on
6802        // the accessor-projected value, and vice versa on the reject side.
6803        // This closes the "the validator reads through the accessor"
6804        // contract structurally — a future silent detour that made the
6805        // accessor return a different byte-string than the validator gates
6806        // against would surface here as a coverage mismatch, not as a
6807        // resolver-time semver-parse rejection at lacre-closure time far
6808        // from the caixa.lisp source. Peer of the sibling
6809        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
6810        // the per-`:children :caixa` axis and the M2
6811        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
6812        // on the peer per-`:upgrade-from :from` axis.
6813        //
6814        // Accept-set sweep: five Cargo-shaped semver requirement values
6815        // the upstream gate admits (caret / tilde / exact / wildcard /
6816        // bare-major).
6817        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6818            let s = SupervisorSpec {
6819                children: vec![ChildSpec {
6820                    caixa: "worker".into(),
6821                    versao: ok_req.into(),
6822                    restart: RestartPolicy::Permanent,
6823                }],
6824                ..SupervisorSpec::default()
6825            };
6826            s.validate().unwrap_or_else(|e| {
6827                panic!(
6828                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
6829                     (upstream versao-requirement gate accepts it): got {e:?}",
6830                );
6831            });
6832            let c = ChildSpec {
6833                caixa: "worker".into(),
6834                versao: ok_req.into(),
6835                restart: RestartPolicy::Permanent,
6836            };
6837            crate::render::require_valid_versao_requirement(
6838                c.versao_requirement(),
6839                || (),
6840                |_reason| (),
6841            )
6842            .unwrap_or_else(|()| {
6843                panic!(
6844                    "require_valid_versao_requirement must accept the accessor-projected \
6845                     :children :versao {ok_req:?}",
6846                );
6847            });
6848        }
6849        // Reject-set sweep: five requirement-violating shapes the upstream
6850        // gate refuses. The empty string closes the empty-first arm of the
6851        // shared [`crate::render::require_valid_versao_requirement`]
6852        // cascade; the four non-empty arms exercise distinct semver-parse
6853        // failure modes the M3 peer per-`:membros` reject-set already pins
6854        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
6855        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
6856        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
6857        // shared parser routing means the same reject-set must fail
6858        // identically at the M2 supervisor-tree per-`:children` accessor
6859        // arm here. Every rejection at the validator must correspond to a
6860        // rejection when the accessor's projected value is fed back
6861        // through the shared gate.
6862        //
6863        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
6864        // `"not-a-semver"` are intentionally *not* in the reject-set: the
6865        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
6866        // and the identifier-tail arm's grammar admits some non-canonical
6867        // shapes — matching what the M3 peer test suite already documents
6868        // as the shared parser's accept-set edges.)
6869        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
6870            let s = SupervisorSpec {
6871                children: vec![ChildSpec {
6872                    caixa: "worker".into(),
6873                    versao: bad_req.into(),
6874                    restart: RestartPolicy::Permanent,
6875                }],
6876                ..SupervisorSpec::default()
6877            };
6878            let err = s.validate().unwrap_err();
6879            assert!(
6880                matches!(
6881                    err,
6882                    SupervisorError::EmptyChildVersion { .. }
6883                        | SupervisorError::ChildVersaoInvalid { .. }
6884                ),
6885                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
6886                 via the versao-requirement gate: got {err:?}",
6887            );
6888            let c = ChildSpec {
6889                caixa: "worker".into(),
6890                versao: bad_req.into(),
6891                restart: RestartPolicy::Permanent,
6892            };
6893            assert!(
6894                crate::render::require_valid_versao_requirement(
6895                    c.versao_requirement(),
6896                    || (),
6897                    |_reason| (),
6898                )
6899                .is_err(),
6900                "require_valid_versao_requirement must reject the accessor-projected \
6901                 :children :versao {bad_req:?}",
6902            );
6903        }
6904    }
6905
6906    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
6907    //
6908    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
6909    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
6910    // already project the `String`-carry `(caixa, versao)` fields; the
6911    // `Copy`-composite-enum `restart` field is the third and final axis).
6912    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
6913    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
6914    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
6915    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
6916    // strategy scalar accessor — same "one typed dispatch on the substrate
6917    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
6918    // extended onto the M2 supervisor-slot per-`:children` restart-decision
6919    // axis. The pin below covers the accessor's byte-equal projection
6920    // against the raw field access across every variant in the closed
6921    // accept-set (`Permanent`, `Transient`, `Temporary`).
6922
6923    #[test]
6924    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
6925        // The canonical per-`:children` restart-decision-policy-scalar
6926        // pin: [`ChildSpec::restart`] must return the `:children :restart`
6927        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
6928        // typed slot's own [`RestartPolicy`] storage across every variant
6929        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
6930        // Pins against a future silent detour that re-derived the policy
6931        // from a peer axis (an accidental fallback to
6932        // `if is_supervisor_child { Permanent } else { Temporary }` that
6933        // collapsed the child's kind axis into the restart discriminator),
6934        // a variant remap the operator authors on one consumer without the
6935        // other, or a stale-derive detour that substituted
6936        // [`RestartPolicy::default`] when the field held any explicit
6937        // variant (which would silently collapse the distinction between
6938        // "author explicitly declared `:restart Permanent`" and "author
6939        // omitted the slot and inherited the default" the future
6940        // per-cluster restart-decision override slot depends on).
6941        //
6942        // Peer of the sibling per-`:supervisor`
6943        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6944        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
6945        // axis and the M3
6946        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
6947        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
6948        // — same "the substrate-primitive accessor must byte-equal the raw
6949        // field access verbatim across every author-declared value"
6950        // discipline extended onto the M2 supervisor-slot per-`:children`
6951        // restart-decision-policy axis, closing the last unlifted axis on
6952        // the per-`:children` [`ChildSpec`] type.
6953        for restart in [
6954            RestartPolicy::Permanent,
6955            RestartPolicy::Transient,
6956            RestartPolicy::Temporary,
6957        ] {
6958            let c = ChildSpec {
6959                caixa: "worker".into(),
6960                versao: "^0.1".into(),
6961                restart,
6962            };
6963            assert_eq!(
6964                c.restart(),
6965                restart,
6966                "ChildSpec::restart must return :children :restart \
6967                 verbatim (got {:?}, expected {restart:?})",
6968                c.restart(),
6969            );
6970            assert_eq!(
6971                c.restart(),
6972                c.restart,
6973                "ChildSpec::restart accessor and .restart field access \
6974                 must byte-equal — the accessor is the substrate-primitive \
6975                 typed dispatch every downstream per-child restart-\
6976                 decision consumer must route through",
6977            );
6978        }
6979    }
6980
6981    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
6982    //
6983    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
6984    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
6985    // distribution-strategy accessor discipline onto the M2 supervisor-slot
6986    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
6987    // scalar axis. The two pins below cover (1) the accessor's byte-equal
6988    // projection against the raw field access across every variant in the
6989    // closed accept-set, and (2) the two-consumer coherence between the
6990    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
6991    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
6992    // carrier's `estrategia:` field — peer of the sibling M3
6993    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
6994    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
6995    // pair on the per-`:placement` distribution-strategy axis.
6996
6997    #[test]
6998    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
6999        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
7000        // pin: [`SupervisorSpec::estrategia`] must return the
7001        // `:supervisor :estrategia` field verbatim as a
7002        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
7003        // [`RestartStrategy`] storage across every variant in the closed
7004        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
7005        // `SimpleOneForOne`). Pins against a future silent detour that
7006        // re-derived the strategy from a peer axis (an accidental
7007        // fallback to `if children.is_empty() { SimpleOneForOne } else {
7008        // OneForOne }` collapse that read the children-count axis into
7009        // the strategy discriminator), a variant remap the operator
7010        // authors on one consumer without the other, or a stale-derive
7011        // detour that substituted [`RestartStrategy::default`] when the
7012        // field held any explicit variant (which would silently collapse
7013        // the distinction between "author explicitly declared
7014        // `:estrategia OneForOne`" and "author omitted the slot and
7015        // inherited the default" the future per-cluster strategy override
7016        // slot depends on). Peer of the sibling M3
7017        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7018        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
7019        // axis — same "the substrate-primitive accessor must byte-equal
7020        // the raw field access verbatim across every author-declared
7021        // value" discipline extended onto the M2 supervisor-slot
7022        // per-`:supervisor` sibling-restart-strategy axis.
7023        for &estrategia in RestartStrategy::ALL {
7024            // `SimpleOneForOne` requires `children.is_empty()`; the peer
7025            // three strategies require a non-empty static children list.
7026            // Build each shape coherently so the pin's fixture would
7027            // itself pass [`SupervisorSpec::validate`] once fed through
7028            // the sibling coherence pin below — the byte-equal projection
7029            // asserted here is a strictly weaker property (a `Copy` field
7030            // read) that does not depend on `validate` running, but
7031            // keeping the fixture validate-clean means a future extension
7032            // of the pin to exercise `validate` end-to-end does not have
7033            // to re-author the children shape.
7034            //
7035            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7036            // shape partition through the [`gen_platform::IsVariant`]
7037            // derive-generated
7038            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
7039            // than the raw `matches!(estrategia, RestartStrategy::
7040            // SimpleOneForOne)` open-coded pattern-match — same closed-
7041            // set-typed-enum arm-discriminator dispatch discipline the
7042            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
7043            // convergence (915a934) extended onto its two paired positive
7044            // / negated `matches!` sites and the peer
7045            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7046            // predicate convergence (766ec63) extended onto the M3 mesh-
7047            // slot per-`:placement` distribution-strategy discriminator
7048            // axis. See the sibling `round_trip_all_strategies` and the
7049            // peer `manifest::tests::
7050            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7051            // fixture for the two peer sites the same lift closes on.
7052            let children = if estrategia.is_simple_one_for_one() {
7053                Vec::new()
7054            } else {
7055                vec![ChildSpec {
7056                    caixa: "worker".into(),
7057                    versao: "^0.1".into(),
7058                    restart: RestartPolicy::Permanent,
7059                }]
7060            };
7061            let s = SupervisorSpec {
7062                estrategia,
7063                children,
7064                ..SupervisorSpec::default()
7065            };
7066            assert_eq!(
7067                s.estrategia(),
7068                estrategia,
7069                "SupervisorSpec::estrategia must return :supervisor :estrategia \
7070                 verbatim (got {:?}, expected {estrategia:?})",
7071                s.estrategia(),
7072            );
7073            assert_eq!(
7074                s.estrategia(),
7075                s.estrategia,
7076                "SupervisorSpec::estrategia accessor and .estrategia field \
7077                 access must byte-equal — the accessor is the substrate-\
7078                 primitive typed dispatch every downstream sibling-restart-\
7079                 strategy consumer must route through",
7080            );
7081        }
7082    }
7083
7084    #[test]
7085    fn validate_reads_through_lifted_estrategia_accessor() {
7086        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
7087        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
7088        // dispatch (which reads through [`SupervisorSpec::estrategia`]
7089        // to fan across the strategy-arm shape-gate cascades) and the
7090        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
7091        // error carrier's `estrategia:` field (which reads through
7092        // [`SupervisorSpec::estrategia`] to name the strategy the empty
7093        // `:children` list was declared against) must both key off the
7094        // lifted accessor, so any future rebrand on the typed slot's
7095        // reader shape lands at exactly one place. Pins the two-site
7096        // coherence by exercising the `NoChildren` error surface end-to-
7097        // end across every non-`SimpleOneForOne` variant and asserting
7098        // the surfaced `estrategia:` field byte-equals the accessor's
7099        // return. Peer of the sibling M3
7100        // `validate_placement_reads_through_lifted_estrategia_accessor`
7101        // (921fe1b) three-consumer coherence pin on the per-`:placement`
7102        // distribution-strategy axis.
7103        for estrategia in [
7104            RestartStrategy::OneForOne,
7105            RestartStrategy::OneForAll,
7106            RestartStrategy::RestForOne,
7107        ] {
7108            let s = SupervisorSpec {
7109                estrategia,
7110                children: Vec::new(),
7111                ..SupervisorSpec::default()
7112            };
7113            let err = s.validate().unwrap_err();
7114            match err {
7115                SupervisorError::NoChildren { estrategia: e } => {
7116                    assert_eq!(
7117                        e,
7118                        s.estrategia(),
7119                        "NoChildren.estrategia must byte-equal \
7120                         SupervisorSpec::estrategia() — the empty-`:children` \
7121                         refusal reads through the lifted accessor",
7122                    );
7123                    assert_eq!(
7124                        e, estrategia,
7125                        "NoChildren.estrategia must carry the author-declared \
7126                         :supervisor :estrategia variant verbatim (got {e:?}, \
7127                         expected {estrategia:?})",
7128                    );
7129                }
7130                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
7131            }
7132        }
7133    }
7134
7135    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
7136    //
7137    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
7138    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
7139    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
7140    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
7141    // The two pins below cover (1) the accessor's byte-equal projection
7142    // against the raw field access across every representative value in
7143    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
7144    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
7145    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
7146    // zero-floor / cap composition — the validate gate and the accessor
7147    // must route through the same substrate-primitive typed dispatch, so
7148    // any future silent detour that had the accessor perform a
7149    // bounds-collapsing clamp would fail here at caixa-core build time.
7150    // Peer of the sibling M3
7151    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7152    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
7153
7154    #[test]
7155    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
7156        // The canonical per-`:supervisor` restart-budget-count scalar pin:
7157        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
7158        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
7159        // typed slot's own `u32` storage, byte-equal to the raw field
7160        // access across every representative value in the accept-set —
7161        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
7162        // accept-set the surrounding [`SupervisorSpec::validate`] gate
7163        // carves out on the sibling `ZeroMaxRestarts` refusal),
7164        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
7165        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
7166        // (a past-the-guard sentinel that pins the accessor doesn't
7167        // perform a silent bounds-collapse into `1` on the zero arm —
7168        // validate rejects zero but the accessor must ship the raw slot
7169        // verbatim so a validate-time gate regression surfaces at the
7170        // emit boundary rather than being silently absorbed), `u32::MAX`
7171        // (a past-the-guard sentinel that pins the accessor doesn't
7172        // perform a silent bounds-collapse through
7173        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
7174        //
7175        // Peer of the sibling M3
7176        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7177        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
7178        // required-scalar axis — same "the substrate-primitive accessor
7179        // must byte-equal the raw field access verbatim across every
7180        // value in the `u32` accept-set" discipline extended onto the M2
7181        // supervisor-slot per-`:supervisor` restart-budget-count axis.
7182        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
7183            let s = SupervisorSpec {
7184                max_restarts,
7185                ..SupervisorSpec::default()
7186            };
7187            assert_eq!(
7188                s.max_restarts(),
7189                max_restarts,
7190                "SupervisorSpec::max_restarts must return :supervisor \
7191                 :max-restarts verbatim (got {}, expected {max_restarts})",
7192                s.max_restarts(),
7193            );
7194            assert_eq!(
7195                s.max_restarts(),
7196                s.max_restarts,
7197                "SupervisorSpec::max_restarts accessor and .max_restarts \
7198                 field access must byte-equal — the accessor is the \
7199                 substrate-primitive typed dispatch every downstream \
7200                 restart-budget-count consumer must route through",
7201            );
7202        }
7203    }
7204
7205    #[test]
7206    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
7207        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
7208        // zero-floor + upper-cap bracket must key off
7209        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
7210        // field access. Structurally: a `SupervisorSpec { max_restarts:
7211        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
7212        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7213        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
7214        // (with the offending count carried verbatim from the accessor
7215        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
7216        // lower boundary of the accept-set) plus a `SupervisorSpec {
7217        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
7218        // boundary) must pass validate. The four together jointly pin the
7219        // accessor + validate-gate composition: any future silent detour
7220        // that had the accessor return a fresh `1` on the zero arm (a
7221        // `.max_restarts().max(1)` collapse) would silently absorb the
7222        // `ZeroMaxRestarts` refusal at the accessor boundary and the
7223        // validate gate would accept a struct-literal `SupervisorSpec {
7224        // max_restarts: 0, .. }` — the composition pin catches that at
7225        // caixa-core build time.
7226        //
7227        // Peer of the sibling M3
7228        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
7229        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
7230        // composition axis — same "the validate / shape-gate predicate
7231        // must route through the substrate-primitive typed dispatch"
7232        // discipline extended onto the peer M2 supervisor-slot
7233        // required-`u32` composition axis.
7234        let child = ChildSpec {
7235            caixa: "worker".into(),
7236            versao: "^0.1".into(),
7237            restart: RestartPolicy::Permanent,
7238        };
7239        // Zero-floor arm.
7240        let s = SupervisorSpec {
7241            max_restarts: 0,
7242            children: vec![child.clone()],
7243            ..SupervisorSpec::default()
7244        };
7245        assert_eq!(
7246            s.validate().unwrap_err(),
7247            SupervisorError::ZeroMaxRestarts,
7248            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
7249             — the accessor and the validate gate must route through the \
7250             same substrate-primitive typed dispatch on the zero-floor arm",
7251        );
7252        // Cap arm — the surfaced `max_restarts:` field must byte-equal
7253        // the accessor's return so a future rebrand on the accessor
7254        // lands in the diagnostic without a coordinated rewrite.
7255        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
7256        let s = SupervisorSpec {
7257            max_restarts: over_cap,
7258            children: vec![child.clone()],
7259            ..SupervisorSpec::default()
7260        };
7261        match s.validate().unwrap_err() {
7262            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
7263                assert_eq!(
7264                    max_restarts,
7265                    s.max_restarts(),
7266                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
7267                     SupervisorSpec::max_restarts() — the cap-arm refusal \
7268                     reads through the lifted accessor",
7269                );
7270                assert_eq!(
7271                    max_restarts, over_cap,
7272                    "MaxRestartsExceedsCap.max_restarts must carry the \
7273                     author-declared :supervisor :max-restarts value \
7274                     verbatim (got {max_restarts}, expected {over_cap})",
7275                );
7276            }
7277            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
7278        }
7279        // Lower + upper accept-set boundaries.
7280        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
7281            let s = SupervisorSpec {
7282                max_restarts,
7283                children: vec![child.clone()],
7284                ..SupervisorSpec::default()
7285            };
7286            assert!(
7287                s.validate().is_ok(),
7288                "validate must accept max_restarts == {max_restarts} \
7289                 (an accept-set boundary of \
7290                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
7291            );
7292        }
7293    }
7294
7295    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
7296    //
7297    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
7298    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
7299    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
7300    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
7301    // supervisor-slot per-`:supervisor` restart-intensity-denominator
7302    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
7303    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
7304    // per-`:supervisor` scalar-value axis. The three pins below cover
7305    // (1) the accessor's byte-equal projection against the raw field
7306    // access across every representative value in the `Option<Duration>`
7307    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
7308    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
7309    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
7310    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
7311    // `if let Some(w) = self.restart_window() { … }` bracket-arm
7312    // composition — the validate gate and the accessor must route through
7313    // the same substrate-primitive typed dispatch, so any future silent
7314    // detour that had the accessor perform a bounds-collapsing clamp
7315    // would fail here at caixa-core build time, and (3) the accessor's
7316    // by-copy idempotence pin — the returned `Option<Duration>` must
7317    // outlive `&self` and two successive calls must return byte-equal
7318    // values. Peer of the sibling M2
7319    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7320    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
7321    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7322    // (7073d0f) pin on the per-`:politicas :timeout` axis.
7323
7324    #[test]
7325    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
7326        // The canonical per-`:supervisor` restart-intensity-denominator
7327        // scalar pin: [`SupervisorSpec::restart_window`] must return the
7328        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
7329        // `Option<Duration>`, `Copy`-projected from the typed slot's own
7330        // `Option<Duration>` storage, byte-equal to the raw field access
7331        // across every representative value in the accept-set — `None`
7332        // (the "never reset — every restart across the supervisor's
7333        // lifetime counts against the sibling `:max-restarts` budget"
7334        // sentinel the field's own docstring names and the peer
7335        // `validate_accepts_none_restart_window` pin locks in on the
7336        // [`SupervisorSpec::validate`] entry-side),
7337        // `Some(Duration::from_millis(1))` (the structural minimum a
7338        // validated `:restart-window` may carry, the integer-millisecond
7339        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
7340        // everything sub-ms; `Duration::ZERO` is separately rejected by
7341        // [`SupervisorError::RestartWindowZero`]),
7342        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
7343        // surrounding [`SupervisorSpec::validate`] gate carves out on the
7344        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
7345        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
7346        // accessor doesn't perform a silent bounds-collapse into `None` on
7347        // the zero-Duration arm — validate rejects zero but the accessor
7348        // must ship the raw slot verbatim so a validate-time gate
7349        // regression surfaces at the emit boundary rather than being
7350        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
7351        // sentinel that pins the accessor doesn't perform a silent
7352        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
7353        // return path).
7354        //
7355        // Peer of the sibling M2
7356        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7357        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
7358        // sibling M3
7359        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7360        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
7361        // substrate-primitive accessor must byte-equal the raw field
7362        // access verbatim across every value in the `Option<Duration>`
7363        // accept-set" discipline extended onto the M2 supervisor-slot
7364        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
7365        // silent detour that re-derived the restart-window from a peer
7366        // axis (an accidental `.max_restarts.into()` collapse that read
7367        // the restart-budget-count as a duration — the two axes serve
7368        // different halves of the `MaxIntensity / Period` restart-
7369        // intensity ratio, and confusing them silently inverts the
7370        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
7371        // "zero means never reset" collapse (the canonical
7372        // `Option<Duration>` → `Duration` collapse footgun the
7373        // [`SupervisorError::RestartWindowZero`] validate arm guards on
7374        // the peer zero-floor axis; a zero period either trips on the
7375        // first failure or never trips depending on operator
7376        // interpretation, neither of which is the author's "never reset"
7377        // intent that `None` expresses structurally), or a per-arm
7378        // variant swap that landed on one consumer without the other.
7379        for restart_window in [
7380            None,
7381            Some(Duration::from_millis(1)),
7382            Some(SUPERVISOR_RESTART_WINDOW_MAX),
7383            Some(Duration::ZERO),
7384            Some(Duration::MAX),
7385        ] {
7386            let s = SupervisorSpec {
7387                restart_window,
7388                ..SupervisorSpec::default()
7389            };
7390            assert_eq!(
7391                s.restart_window(),
7392                restart_window,
7393                "SupervisorSpec::restart_window must return :supervisor \
7394                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
7395                s.restart_window(),
7396            );
7397            assert_eq!(
7398                s.restart_window(),
7399                s.restart_window,
7400                "SupervisorSpec::restart_window accessor and \
7401                 .restart_window field access must byte-equal — the \
7402                 accessor is the substrate-primitive typed dispatch every \
7403                 downstream restart-intensity-denominator consumer must \
7404                 route through",
7405            );
7406        }
7407    }
7408
7409    #[test]
7410    fn validate_restart_window_bracket_arm_routes_through_accessor() {
7411        // Composition pin: [`SupervisorSpec::validate`]'s
7412        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
7413        // zero-floor + integer-millisecond canonical-form + upper-cap
7414        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
7415        // the raw `.restart_window` field access. Structurally: a
7416        // `SupervisorSpec { restart_window: None, .. }` must pass the
7417        // arm gate structurally (the `if let Some(_)` shape returns
7418        // early on the `None` arm — the accessor and the validate gate
7419        // must agree on `None → skip the bracket cascade` so an authored
7420        // `:restart-window ()` structurally routes through the "never
7421        // reset" sentinel path), a `SupervisorSpec { restart_window:
7422        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
7423        // refusal exactly, a `SupervisorSpec { restart_window:
7424        // Some(Duration::from_micros(1500)), .. }` must surface the
7425        // `RestartWindowNotCanonical` refusal exactly (with the offending
7426        // duration carried verbatim from the accessor return), a
7427        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
7428        // + Duration::from_millis(1)), .. }` must surface the
7429        // `RestartWindowExceedsCap` refusal exactly (with the offending
7430        // duration carried verbatim from the accessor return), and a
7431        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
7432        // .. }` (the lower boundary of the accept-set) plus a
7433        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7434        // .. }` (the upper boundary) must pass validate. The six together
7435        // jointly pin the accessor + validate-gate composition: any future
7436        // silent detour that had the accessor return a fresh `None` on any
7437        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
7438        // collapse) would silently absorb the `RestartWindowZero` refusal
7439        // at the accessor boundary and the validate gate would accept a
7440        // struct-literal `SupervisorSpec { restart_window:
7441        // Some(Duration::ZERO), .. }` — the composition pin catches that
7442        // at caixa-core build time.
7443        //
7444        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
7445        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
7446        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
7447        // accessor-composition pin on the per-`:politicas :timeout` axis —
7448        // same "the validate / shape-gate predicate must route through
7449        // the substrate-primitive typed dispatch" discipline extended
7450        // onto the peer M2 supervisor-slot optional-`Duration` axis.
7451        let child = ChildSpec {
7452            caixa: "worker".into(),
7453            versao: "^0.1".into(),
7454            restart: RestartPolicy::Permanent,
7455        };
7456        // None arm — must not surface any :restart-window-shaped refusal;
7457        // the `if let Some(_)` bracket returns early on `None` structurally.
7458        let s = SupervisorSpec {
7459            restart_window: None,
7460            children: vec![child.clone()],
7461            ..SupervisorSpec::default()
7462        };
7463        assert!(
7464            s.validate().is_ok(),
7465            "validate must accept restart_window: None (the never-reset \
7466             sentinel) — the `if let Some(_)` bracket returns early on \
7467             the None arm and the accessor must agree",
7468        );
7469        // Zero-floor arm.
7470        let s = SupervisorSpec {
7471            restart_window: Some(Duration::ZERO),
7472            children: vec![child.clone()],
7473            ..SupervisorSpec::default()
7474        };
7475        assert_eq!(
7476            s.validate().unwrap_err(),
7477            SupervisorError::RestartWindowZero,
7478            "validate must reject restart_window == Some(Duration::ZERO) \
7479             with RestartWindowZero — the accessor and the validate gate \
7480             must route through the same substrate-primitive typed \
7481             dispatch on the zero-floor arm",
7482        );
7483        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
7484        // byte-equal the accessor's return so a future rebrand on the
7485        // accessor lands in the diagnostic without a coordinated rewrite.
7486        let sub_ms = Duration::from_micros(1500);
7487        let s = SupervisorSpec {
7488            restart_window: Some(sub_ms),
7489            children: vec![child.clone()],
7490            ..SupervisorSpec::default()
7491        };
7492        match s.validate().unwrap_err() {
7493            SupervisorError::RestartWindowNotCanonical { window } => {
7494                assert_eq!(
7495                    Some(window),
7496                    s.restart_window(),
7497                    "RestartWindowNotCanonical.window must byte-equal \
7498                     SupervisorSpec::restart_window().unwrap() — the \
7499                     non-canonical-arm refusal reads through the lifted \
7500                     accessor",
7501                );
7502                assert_eq!(
7503                    window, sub_ms,
7504                    "RestartWindowNotCanonical.window must carry the \
7505                     author-declared :supervisor :restart-window value \
7506                     verbatim (got {window:?}, expected {sub_ms:?})",
7507                );
7508            }
7509            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7510        }
7511        // Cap arm — the surfaced `window:` field must byte-equal the
7512        // accessor's return.
7513        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
7514        let s = SupervisorSpec {
7515            restart_window: Some(over_cap),
7516            children: vec![child.clone()],
7517            ..SupervisorSpec::default()
7518        };
7519        match s.validate().unwrap_err() {
7520            SupervisorError::RestartWindowExceedsCap { window } => {
7521                assert_eq!(
7522                    Some(window),
7523                    s.restart_window(),
7524                    "RestartWindowExceedsCap.window must byte-equal \
7525                     SupervisorSpec::restart_window().unwrap() — the \
7526                     cap-arm refusal reads through the lifted accessor",
7527                );
7528                assert_eq!(
7529                    window, over_cap,
7530                    "RestartWindowExceedsCap.window must carry the \
7531                     author-declared :supervisor :restart-window value \
7532                     verbatim (got {window:?}, expected {over_cap:?})",
7533                );
7534            }
7535            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
7536        }
7537        // Lower + upper accept-set boundaries.
7538        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
7539            let s = SupervisorSpec {
7540                restart_window: Some(restart_window),
7541                children: vec![child.clone()],
7542                ..SupervisorSpec::default()
7543            };
7544            assert!(
7545                s.validate().is_ok(),
7546                "validate must accept restart_window == Some({restart_window:?}) \
7547                 (an accept-set boundary of \
7548                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
7549            );
7550        }
7551    }
7552
7553    #[test]
7554    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
7555        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
7556        // `Option<Duration>` by copy — `Duration` is `Copy` (so
7557        // `Option<Duration>` is `Copy`) and the accessor must return by
7558        // value, not by reference. Peer of the sibling M2
7559        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
7560        // per-`:limits :wall-clock` axis and the sibling M3
7561        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
7562        // per-`:politicas :timeout` axis, extended onto the peer M2
7563        // supervisor-slot `Option<Duration>` copy-invariant shape — the
7564        // accessor's returned `Option<Duration>` must outlive `&self`
7565        // (multiple calls must return equal values from a dropped-`&self`
7566        // copy, since the returned Option carries no borrow), and calling
7567        // the accessor twice on the same SupervisorSpec must yield the
7568        // same `Option<Duration>` verbatim (idempotent, no side effects
7569        // on `&self`).
7570        //
7571        // Pins against a future silent detour that returned
7572        // `Option<&Duration>` (which would type-check but silently break
7573        // every downstream caller — the future wasm-operator's
7574        // per-supervisor restart-intensity counter consumes `Duration` by
7575        // value and `&Duration` would fold to a detached copy at the call
7576        // site), an accidental `Option::as_ref()` projection
7577        // (`self.restart_window.as_ref()` would also type-check but
7578        // return `Option<&Duration>`), or a one-arm-only accessor that
7579        // reads `Some(*w)` in the Some arm but reads a fresh
7580        // `Default::default()` (which would collapse to `Duration::ZERO`,
7581        // not `None`) in the None arm — a footgun the
7582        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
7583        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
7584        // requires `Period > 0` and `None` structurally expresses "never
7585        // reset" instead.
7586        for restart_window in [
7587            None,
7588            Some(Duration::from_millis(1)),
7589            Some(Duration::from_secs(60)),
7590            Some(SUPERVISOR_RESTART_WINDOW_MAX),
7591        ] {
7592            let s = SupervisorSpec {
7593                restart_window,
7594                ..SupervisorSpec::default()
7595            };
7596            let first = s.restart_window();
7597            let second = s.restart_window();
7598            assert_eq!(
7599                first, second,
7600                "SupervisorSpec::restart_window must be idempotent — two \
7601                 successive calls on the same &self must return the \
7602                 same Option<Duration>",
7603            );
7604            assert_eq!(
7605                first, restart_window,
7606                "SupervisorSpec::restart_window must return :supervisor \
7607                 :restart-window verbatim by copy — got {first:?}, \
7608                 expected {restart_window:?}",
7609            );
7610        }
7611    }
7612
7613    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
7614    //
7615    // The [`SupervisorSpec::children`] accessor lift is the seed of the
7616    // slice-return (`&[T]`) accessor discipline on the substrate — the four
7617    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
7618    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
7619    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
7620    // access at the time of this seed, and inherit this pin family's
7621    // discipline as future compounding runs migrate their consumers. The
7622    // three pins below cover (1) the accessor's byte-equal projection
7623    // against the raw field access across the empty / singleton / cohort
7624    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
7625    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
7626    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
7627    // consumer routing through the accessor on both arms, and (3) the
7628    // per-child validate loop's traversal reading the same slice-view the
7629    // accessor projects. Peer of the sibling M2
7630    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7631    // two-consumer coherence pin on the per-`:supervisor`
7632    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
7633    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
7634
7635    #[test]
7636    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
7637        // The canonical per-`:supervisor` static-child-list scalar-shape
7638        // pin: [`SupervisorSpec::children`] must return the `:supervisor
7639        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
7640        // slice-view over the same backing buffer the raw
7641        // `self.children.as_slice()` field access borrows from, byte-
7642        // equal across every representative fixture in the accept-set —
7643        // the empty slice (the `SimpleOneForOne`-arm sentinel),
7644        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
7645        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
7646        // with the peer three restart-policy variants in play).
7647        //
7648        // Pins against a future silent detour that returned
7649        // `&Vec<ChildSpec>` (which would type-check but leak the
7650        // storage-side `Vec`'s grow/push/reserve surface no consumer of
7651        // the typed view reaches for), a fresh-allocated
7652        // `Vec<ChildSpec>` copy (which would type-check via a coercion
7653        // but silently break every downstream caller that relied on the
7654        // slice sharing the backing buffer's identity), or an
7655        // out-of-order or length-drifted projection (which would silently
7656        // split the per-child validate loop's traversal input from the
7657        // paired partition-dispatch `.is_empty()` probe's input).
7658        //
7659        // Peer of the sibling
7660        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7661        // (eafb619) `Copy`-composite-enum byte-equal pin on the
7662        // per-`:supervisor` sibling-restart-strategy axis, extended onto
7663        // the per-`:supervisor` static-child-list `Vec`-carry axis.
7664        let fixtures: Vec<Vec<ChildSpec>> = vec![
7665            Vec::new(),
7666            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7667            vec![
7668                child("worker", "^0.1", RestartPolicy::Permanent),
7669                child("cache-server", "^0.1", RestartPolicy::Transient),
7670            ],
7671            vec![
7672                child("worker", "^0.1", RestartPolicy::Permanent),
7673                child("cache-server", "^0.1", RestartPolicy::Transient),
7674                child("scratch-job", "^0.1", RestartPolicy::Temporary),
7675            ],
7676        ];
7677        for children in fixtures {
7678            let s = SupervisorSpec {
7679                children: children.clone(),
7680                ..SupervisorSpec::default()
7681            };
7682            assert_eq!(
7683                s.children(),
7684                children.as_slice(),
7685                "SupervisorSpec::children must return :supervisor \
7686                 :children verbatim (got {:?}, expected {:?})",
7687                s.children(),
7688                children.as_slice(),
7689            );
7690            assert_eq!(
7691                s.children(),
7692                s.children.as_slice(),
7693                "SupervisorSpec::children accessor and \
7694                 .children.as_slice() field access must byte-equal — \
7695                 the accessor is the substrate-primitive typed \
7696                 dispatch every downstream static-child-list consumer \
7697                 must route through",
7698            );
7699            assert_eq!(
7700                s.children().len(),
7701                s.children.len(),
7702                "SupervisorSpec::children().len() must byte-equal \
7703                 self.children.len() — a length-drift would silently \
7704                 split the paired partition-dispatch `.is_empty()` \
7705                 probe input from the per-child validate loop's \
7706                 traversal input",
7707            );
7708        }
7709    }
7710
7711    #[test]
7712    fn validate_reads_through_lifted_children_accessor() {
7713        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
7714        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
7715        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
7716        // when the accessor projects a non-empty slice under a
7717        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
7718        // `self.children().is_empty()` refusal probe (which must trip
7719        // [`SupervisorError::NoChildren`] when the accessor projects the
7720        // empty slice under any peer estrategia), and the per-child
7721        // validate loop's `for child in self.children()` traversal
7722        // (which must reach every entry in the same order the accessor
7723        // projects) must all key off the lifted accessor, so any future
7724        // rebrand on the typed slot's reader shape lands at exactly one
7725        // place. Pins the three-site coherence by exercising each
7726        // production consumer end-to-end: (1) the
7727        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
7728        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
7729        // refusal under the empty slice + non-`SimpleOneForOne`
7730        // estrategia across every peer variant, and (3) the per-child
7731        // duplicate-detection surface fires on the second entry of a
7732        // two-child cohort that shares a `:caixa` name (which requires
7733        // the loop to reach both entries — a first-entry-only projection
7734        // would silently pass since the dedup HashSet has room for the
7735        // first insert).
7736        //
7737        // Peer of the sibling M2
7738        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7739        // two-consumer coherence pin on the per-`:supervisor`
7740        // sibling-restart-strategy axis, extended onto the
7741        // per-`:supervisor` static-child-list `Vec`-carry axis.
7742
7743        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
7744        // `SimpleOneForOne` estrategia must trip
7745        // `SimpleOneForOneWithStaticChildren`.
7746        let s = SupervisorSpec {
7747            estrategia: RestartStrategy::SimpleOneForOne,
7748            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7749            ..SupervisorSpec::default()
7750        };
7751        assert_eq!(
7752            s.validate().unwrap_err(),
7753            SupervisorError::SimpleOneForOneWithStaticChildren,
7754            "SimpleOneForOne + non-empty children must trip \
7755             SimpleOneForOneWithStaticChildren — the accessor projects \
7756             a non-empty slice, and the SimpleOneForOne-arm refusal \
7757             probe reads through the lifted accessor",
7758        );
7759        assert!(
7760            !s.children().is_empty(),
7761            "the SimpleOneForOne-arm refusal input must be a non-empty \
7762             slice per the accessor's projection",
7763        );
7764
7765        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
7766        // under any peer estrategia must trip `NoChildren`.
7767        for estrategia in [
7768            RestartStrategy::OneForOne,
7769            RestartStrategy::OneForAll,
7770            RestartStrategy::RestForOne,
7771        ] {
7772            let s = SupervisorSpec {
7773                estrategia,
7774                children: Vec::new(),
7775                ..SupervisorSpec::default()
7776            };
7777            match s.validate().unwrap_err() {
7778                SupervisorError::NoChildren { estrategia: e } => {
7779                    assert_eq!(
7780                        e, estrategia,
7781                        "NoChildren.estrategia must carry the author-\
7782                         declared :supervisor :estrategia variant \
7783                         verbatim (got {e:?}, expected {estrategia:?})",
7784                    );
7785                }
7786                other => panic!(
7787                    "expected NoChildren, got {other:?} for \
7788                     estrategia={estrategia:?}"
7789                ),
7790            }
7791            assert!(
7792                s.children().is_empty(),
7793                "the non-SimpleOneForOne-arm refusal input must be the \
7794                 empty slice per the accessor's projection",
7795            );
7796        }
7797
7798        // (3) Per-child validate loop: a two-child cohort that shares a
7799        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
7800        // reach both entries through the accessor.
7801        let s = SupervisorSpec {
7802            estrategia: RestartStrategy::OneForOne,
7803            children: vec![
7804                child("worker", "^0.1", RestartPolicy::Permanent),
7805                child("worker", "^0.2", RestartPolicy::Transient),
7806            ],
7807            ..SupervisorSpec::default()
7808        };
7809        match s.validate().unwrap_err() {
7810            SupervisorError::DuplicateChildCaixa { caixa } => {
7811                assert_eq!(
7812                    caixa, "worker",
7813                    "DuplicateChildCaixa.caixa must carry the shared \
7814                     child `:caixa` name verbatim",
7815                );
7816            }
7817            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
7818        }
7819        assert_eq!(
7820            s.children().len(),
7821            2,
7822            "the per-child validate loop's traversal input must be a \
7823             two-element slice per the accessor's projection",
7824        );
7825    }
7826
7827    // Shared helper for the M2 per-`:children` per-slot-gate ≡
7828    // `validate` equivalence pins: builds an `OneForOne`-estrategia
7829    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
7830    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
7831    // bracket all pass cleanly so the sole failing surface is the
7832    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
7833    // pins the two-altitude equivalence on the paired probe.
7834    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
7835        let s = SupervisorSpec {
7836            estrategia: RestartStrategy::OneForOne,
7837            children,
7838            ..SupervisorSpec::default()
7839        };
7840        let via_gate = s.validate_children().unwrap_err();
7841        let via_validate = s.validate().unwrap_err();
7842        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
7843        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
7844        assert_eq!(
7845            via_gate, via_validate,
7846            "per-slot gate ≡ validate() must discriminate the same \
7847             refusal shape",
7848        );
7849    }
7850
7851    #[test]
7852    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
7853        // Fail-before-pass-after equivalence pin on the M2
7854        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
7855        // convergence — sibling of the M3 mesh-slot
7856        // `validate_membros_*` / `validate_contratos_*` /
7857        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
7858        // peer per-entry axes. Sweeps four of the five refusal shapes
7859        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
7860        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
7861        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
7862        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
7863        // duplicate-`:caixa` fan-out. Companion pin
7864        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
7865        // covers `ChildVersaoInvalid` (whose parser-owned reason string
7866        // needs pattern-matching, not equality) and the clean-pass
7867        // canonical fixture; together the two pins guarantee the
7868        // per-slot gate and `validate` discriminate the same set on
7869        // every per-child-covered input.
7870        assert_validate_children_matches_gate(
7871            vec![child("", "^0.1", RestartPolicy::Permanent)],
7872            &SupervisorError::EmptyChildName,
7873        );
7874        assert_validate_children_matches_gate(
7875            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
7876            &SupervisorError::ChildCaixaInvalid {
7877                caixa: "Worker".into(),
7878                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
7879            },
7880        );
7881        assert_validate_children_matches_gate(
7882            vec![child("worker", "", RestartPolicy::Permanent)],
7883            &SupervisorError::EmptyChildVersion {
7884                caixa: "worker".into(),
7885            },
7886        );
7887        assert_validate_children_matches_gate(
7888            vec![
7889                child("worker", "^0.1", RestartPolicy::Permanent),
7890                child("worker", "^0.2", RestartPolicy::Transient),
7891            ],
7892            &SupervisorError::DuplicateChildCaixa {
7893                caixa: "worker".into(),
7894            },
7895        );
7896    }
7897
7898    #[test]
7899    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
7900        // Second half of the two-altitude equivalence pin — covers the
7901        // one refusal shape whose reason string is parser-owned
7902        // (`ChildVersaoInvalid`, whose reason comes from the shared
7903        // [`crate::version::parse_requirement`] impl and may drift) and
7904        // the clean-pass canonical fixture. Sibling pin
7905        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
7906        // covers the four equality-comparable refusal shapes.
7907        let s_bad_versao = SupervisorSpec {
7908            estrategia: RestartStrategy::OneForOne,
7909            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
7910            ..SupervisorSpec::default()
7911        };
7912        let via_gate = s_bad_versao.validate_children().unwrap_err();
7913        let via_validate = s_bad_versao.validate().unwrap_err();
7914        match (&via_gate, &via_validate) {
7915            (
7916                SupervisorError::ChildVersaoInvalid {
7917                    caixa: cg,
7918                    versao: vg,
7919                    ..
7920                },
7921                SupervisorError::ChildVersaoInvalid {
7922                    caixa: cv,
7923                    versao: vv,
7924                    ..
7925                },
7926            ) => {
7927                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
7928                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
7929                assert_eq!(cv, "worker", "validate() :caixa carrier");
7930                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
7931            }
7932            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
7933        }
7934        assert_eq!(
7935            via_gate, via_validate,
7936            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
7937        );
7938
7939        let s_ok = SupervisorSpec {
7940            estrategia: RestartStrategy::OneForOne,
7941            children: vec![
7942                child("worker-a", "^0.1", RestartPolicy::Permanent),
7943                child("worker-b", "~0.2.3", RestartPolicy::Transient),
7944                child("collector", "*", RestartPolicy::Temporary),
7945            ],
7946            ..SupervisorSpec::default()
7947        };
7948        s_ok.validate_children()
7949            .expect("per-slot gate must accept the clean-pass fixture");
7950        s_ok.validate()
7951            .expect("validate() must accept the clean-pass fixture");
7952    }
7953
7954    #[test]
7955    fn validate_children_is_self_contained_on_children_slot() {
7956        // Self-containment pin: [`SupervisorSpec::validate_children`]
7957        // resolves the per-child cascade against `&self` alone, without
7958        // depending on the peer `:estrategia`/`:max-restarts`/
7959        // `:restart-window` gates having run first — same posture the M3
7960        // peer per-slot gates carry (`validate_membros`,
7961        // `validate_contratos`, `validate_entrada`, `validate_placement`,
7962        // routing through their own oracles rather than borrowing state
7963        // threaded down from `validate`). A future consumer that reaches
7964        // the per-slot gate directly on a spec whose peer slots would
7965        // fail `validate` still surfaces the per-child refusal, not the
7966        // peer refusal.
7967        //
7968        // Construct a spec whose `:max-restarts` is `0` (which would
7969        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
7970        // the partition-dispatch) and whose `:children` carries a
7971        // `DuplicateChildCaixa` shape: the per-slot gate called directly
7972        // must surface `DuplicateChildCaixa`, proving it does not depend
7973        // on the peer `:max-restarts` gate running first.
7974        let s = SupervisorSpec {
7975            estrategia: RestartStrategy::OneForOne,
7976            max_restarts: 0,
7977            restart_window: Some(Duration::from_secs(60)),
7978            children: vec![
7979                child("worker", "^0.1", RestartPolicy::Permanent),
7980                child("worker", "^0.2", RestartPolicy::Transient),
7981            ],
7982        };
7983        assert_eq!(
7984            s.validate_children().unwrap_err(),
7985            SupervisorError::DuplicateChildCaixa {
7986                caixa: "worker".into(),
7987            },
7988            "per-slot gate must resolve per-child refusal directly against \
7989             `&self` — a dependency on the peer `:max-restarts` gate \
7990             running first would surface ZeroMaxRestarts here instead",
7991        );
7992        // The peer gate is still the surface `validate` reaches — pin
7993        // the ordering to establish that `validate_children` truly runs
7994        // last in `validate`'s dispatch, so a direct call bypasses the
7995        // peer gates on any spec whose per-child cascade would fail.
7996        assert_eq!(
7997            s.validate().unwrap_err(),
7998            SupervisorError::ZeroMaxRestarts,
7999            "validate() must surface the peer `:max-restarts` gate before \
8000             reaching the per-child cascade — this pins the dispatch \
8001             ordering the per-slot gate's self-containment complements",
8002        );
8003    }
8004
8005    #[test]
8006    fn child_spec_restart_accessor_is_const_fn() {
8007        // The [`ChildSpec::restart`] per-`:children` restart-decision-
8008        // policy `Copy`-return scalar accessor is declared
8009        // `#[must_use] pub const fn` — matching the sibling M2
8010        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
8011        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
8012        // both converted in this commit), the sibling M2
8013        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
8014        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
8015        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
8016        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
8017        // `Copy`-return `pub const fn` scalar accessors on the sibling
8018        // M3 surface. Pin the `const`-eval posture here so a future
8019        // accidental downgrade to non-`const` (an added runtime helper
8020        // reachable only from a non-`const` context, an
8021        // `Option<RestartPolicy>`-shape migration on the per-child
8022        // restart-decision axis once heterogeneous per-cluster
8023        // restart-policy overlays land that would silently drop the
8024        // `const` qualifier, a manual hand-rolled shadow) trips at
8025        // caixa-core build time rather than surfacing as a downstream
8026        // `const`-context regression far from the declaration.
8027        //
8028        // Same shape as the sibling M3
8029        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
8030        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
8031        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
8032        // accessor axis — the load-bearing witness lives in the
8033        // module-scope `const fn` wrapper `restart_via_const_fn` below:
8034        // a body that calls [`ChildSpec::restart`] under a `const fn`
8035        // signature is well-formed only when the callee is itself
8036        // `const fn`, so any future accidental downgrade of
8037        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
8038        // build time (const-eval E0015 `cannot call non-const method`),
8039        // strictly stronger than a runtime `assert!(CONST)` and
8040        // side-stepping the destructor-in-const restriction that
8041        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
8042        // items on `ChildSpec`'s `String` carriers.
8043        //
8044        // The runtime body sweeps every closed-set [`RestartPolicy`]
8045        // arm and asserts the wrapped and direct dispatches agree.
8046        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
8047            c.restart()
8048        }
8049        for restart in [
8050            RestartPolicy::Permanent,
8051            RestartPolicy::Transient,
8052            RestartPolicy::Temporary,
8053        ] {
8054            let c = ChildSpec {
8055                caixa: "worker".into(),
8056                versao: "^0.1".into(),
8057                restart,
8058            };
8059            assert_eq!(
8060                restart_via_const_fn(&c),
8061                c.restart(),
8062                "const-fn-wrapped and direct dispatch on \
8063                 ChildSpec::restart must agree for {restart:?}",
8064            );
8065            assert_eq!(
8066                c.restart(),
8067                restart,
8068                "ChildSpec::restart must return the storage-side \
8069                 RestartPolicy verbatim for {restart:?} (a violation \
8070                 means the accessor stopped being a raw field-return \
8071                 copy)",
8072            );
8073        }
8074    }
8075
8076    #[test]
8077    fn supervisor_spec_estrategia_accessor_is_const_fn() {
8078        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
8079        // sibling-restart-strategy `Copy`-return scalar accessor is
8080        // declared `#[must_use] pub const fn` — matching the sibling M2
8081        // per-`:children` [`ChildSpec::restart`] (pinned by
8082        // [`child_spec_restart_accessor_is_const_fn`] above, both
8083        // converted in this commit), the sibling M2 per-`:supervisor`
8084        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
8085        // accessor already `pub const fn`, and mirroring the peer M3
8086        // mesh-slot per-`:placement`
8087        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
8088        // `pub const fn` scalar accessor whose method-name discipline
8089        // the [`SupervisorSpec::estrategia`] method was authored to
8090        // match. Pin the `const`-eval posture here so a future
8091        // accidental downgrade to non-`const` (an added runtime helper
8092        // reachable only from a non-`const` context, an
8093        // `Option<RestartStrategy>`-shape migration once the substrate
8094        // grows per-cluster strategy overlays that would silently drop
8095        // the `const` qualifier, a manual hand-rolled shadow) trips at
8096        // caixa-core build time rather than surfacing as a downstream
8097        // `const`-context regression far from the declaration.
8098        //
8099        // Same shape as the sibling
8100        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
8101        // load-bearing witness lives in the module-scope `const fn`
8102        // wrapper `estrategia_via_const_fn` below: a body that calls
8103        // [`SupervisorSpec::estrategia`] under a `const fn` signature
8104        // is well-formed only when the callee is itself `const fn`,
8105        // side-stepping the destructor-in-const restriction that would
8106        // otherwise block a direct
8107        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
8108        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
8109        // carriers.
8110        //
8111        // The runtime body sweeps every closed-set [`RestartStrategy`]
8112        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
8113        // direct dispatches agree.
8114        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
8115            s.estrategia()
8116        }
8117        for &estrategia in RestartStrategy::ALL {
8118            let s = SupervisorSpec {
8119                estrategia,
8120                max_restarts: 5,
8121                restart_window: Some(Duration::from_secs(60)),
8122                children: Vec::new(),
8123            };
8124            assert_eq!(
8125                estrategia_via_const_fn(&s),
8126                s.estrategia(),
8127                "const-fn-wrapped and direct dispatch on \
8128                 SupervisorSpec::estrategia must agree for {estrategia:?}",
8129            );
8130            assert_eq!(
8131                s.estrategia(),
8132                estrategia,
8133                "SupervisorSpec::estrategia must return the storage-side \
8134                 RestartStrategy verbatim for {estrategia:?} (a violation \
8135                 means the accessor stopped being a raw field-return \
8136                 copy)",
8137            );
8138        }
8139    }
8140
8141    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
8142    // macro definition (see the paired doc-block above the macro
8143    // definition) — every generated `<ctor>(caixa: &str) -> Self`
8144    // constructor folds the uniform `Self::<Variant> { caixa:
8145    // caixa.to_string() }` one-field struct-literal onto one substrate
8146    // primitive. The three per-variant equivalence pins below
8147    // (fail-before-pass-after by construction — a byte-mismatched macro
8148    // arm would trip its equivalence pin first) lock each generated
8149    // constructor to its struct-literal peer under `PartialEq`, so
8150    // every wire-up in [`SupervisorSpec::validate_children`] and
8151    // [`validate_no_self_supervision`] on that variant produces a
8152    // byte-equal `SupervisorError` to the pre-lift open-coded
8153    // struct-literal. The cross-axis pin that follows (non-default
8154    // caixa name) routes the sole constructor input axis through
8155    // `.to_string()`, so the fold does not silently collapse onto a
8156    // fixed name.
8157    //
8158    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
8159    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
8160    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
8161    // `missing_entry_ctor_matches_struct_literal_wrap` /
8162    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
8163    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
8164    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
8165    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
8166    // on the six sibling ctor families the recent trajectory closed
8167    // on the peer `LayoutError` / `AplicacaoError` envelopes.
8168
8169    #[test]
8170    fn empty_child_version_ctor_matches_struct_literal_wrap() {
8171        assert_eq!(
8172            SupervisorError::empty_child_version("worker"),
8173            SupervisorError::EmptyChildVersion {
8174                caixa: "worker".to_string(),
8175            },
8176            "generated empty_child_version ctor must produce byte-equal \
8177             SupervisorError to the open-coded struct-literal wrap on the \
8178             same &str fixture",
8179        );
8180    }
8181
8182    #[test]
8183    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
8184        assert_eq!(
8185            SupervisorError::duplicate_child_caixa("worker"),
8186            SupervisorError::DuplicateChildCaixa {
8187                caixa: "worker".to_string(),
8188            },
8189            "generated duplicate_child_caixa ctor must produce byte-equal \
8190             SupervisorError to the open-coded struct-literal wrap on the \
8191             same &str fixture",
8192        );
8193    }
8194
8195    #[test]
8196    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
8197        assert_eq!(
8198            SupervisorError::child_supervises_self("orquestra"),
8199            SupervisorError::ChildSupervisesSelf {
8200                caixa: "orquestra".to_string(),
8201            },
8202            "generated child_supervises_self ctor must produce byte-equal \
8203             SupervisorError to the open-coded struct-literal wrap on the \
8204             same &str fixture",
8205        );
8206    }
8207
8208    // Per-variant equivalence pins for the two lifted
8209    // [`SupervisorError::child_caixa_invalid`] /
8210    // [`SupervisorError::child_versao_invalid`] inherent constructors
8211    // (fail-before-pass-after by construction — a byte-mismatched ctor body
8212    // would trip its equivalence pin first). Each pins the ctor output to
8213    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
8214    // in [`SupervisorSpec::validate_children`] on the two variants
8215    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
8216    // struct-literal on the same scalar fixtures. Peers of the sibling
8217    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
8218    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
8219    // the peer `AplicacaoError` envelope's
8220    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
8221
8222    #[test]
8223    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
8224        let caixa = "Worker";
8225        let reason = "sample reason text";
8226        assert_eq!(
8227            SupervisorError::child_caixa_invalid(caixa, reason),
8228            SupervisorError::ChildCaixaInvalid {
8229                caixa: caixa.to_string(),
8230                reason: reason.to_string(),
8231            },
8232            "lifted child_caixa_invalid ctor must produce byte-equal \
8233             SupervisorError to the open-coded struct-literal wrap on the \
8234             same (&str, reason) fixture",
8235        );
8236    }
8237
8238    #[test]
8239    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
8240        let caixa = "worker";
8241        let versao = "not-a-req";
8242        let reason = "sample reason text";
8243        assert_eq!(
8244            SupervisorError::child_versao_invalid(caixa, versao, reason),
8245            SupervisorError::ChildVersaoInvalid {
8246                caixa: caixa.to_string(),
8247                versao: versao.to_string(),
8248                reason: reason.to_string(),
8249            },
8250            "lifted child_versao_invalid ctor must produce byte-equal \
8251             SupervisorError to the open-coded struct-literal wrap on the \
8252             same (&str, &str, reason) fixture",
8253        );
8254    }
8255
8256    #[test]
8257    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
8258        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
8259        // against a `&str`-literal vs. `format!(…)` reason input to pin
8260        // both constructors accept the `impl Into<String>` bound
8261        // uniformly, so neither wire-up site drifts under a per-arm
8262        // wrapper transformation on the caller-side `reason` axis. Peer
8263        // of the sibling
8264        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
8265        // sweep on the peer `AplicacaoError` envelope.
8266        let via_literal = "literal reason text";
8267        let via_format = format!("{} reason text", "literal");
8268        assert_eq!(
8269            SupervisorError::child_caixa_invalid("Worker", via_literal),
8270            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
8271        );
8272        assert_eq!(
8273            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
8274            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
8275        );
8276    }
8277
8278    #[test]
8279    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
8280        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
8281        // &str`) through a non-default fixture name against every
8282        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
8283        // so any wrapper-side lowercase / trim / truncate / re-order on
8284        // the `caixa.to_string()` sole-field construction surfaces
8285        // here rather than at a downstream diagnostic-shape mismatch.
8286        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
8287        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
8288        // through_to_string` / `contrato_target_ctors_route_edge_
8289        // triple_through_verbatim` / `contrato_empty_pair_ctors_
8290        // route_edge_pair_through_verbatim` cross-axis routing pins on
8291        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
8292        // here onto the `SupervisorError` `{ caixa: String }` envelope
8293        // so every substrate-primitive ctor family in caixa-core
8294        // guarantees the sole-field construction routes the caller's
8295        // `&str` through `.to_string()` verbatim.
8296        let name = "cache-v2";
8297        assert_eq!(
8298            SupervisorError::empty_child_version(name),
8299            SupervisorError::EmptyChildVersion {
8300                caixa: name.to_string(),
8301            },
8302        );
8303        assert_eq!(
8304            SupervisorError::duplicate_child_caixa(name),
8305            SupervisorError::DuplicateChildCaixa {
8306                caixa: name.to_string(),
8307            },
8308        );
8309        assert_eq!(
8310            SupervisorError::child_supervises_self(name),
8311            SupervisorError::ChildSupervisesSelf {
8312                caixa: name.to_string(),
8313            },
8314        );
8315    }
8316}