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::ChildCaixaInvalid {
2097                    caixa: child.nome().to_string(),
2098                    reason,
2099                },
2100            )?;
2101            // The author surface for `:children :versao` is the same
2102            // Cargo-shaped semver requirement string `:deps :versao` and
2103            // `:membros :versao` carry — and the lacre pipeline resolves
2104            // all three axes through the same
2105            // [`crate::version::parse_requirement`] entry-point. The
2106            // shared [`crate::render::require_valid_versao_requirement`]
2107            // helper brackets the empty-first + parse cascade both peer
2108            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2109            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2110            // :versao`) route through, so drift between the three axes'
2111            // accepted requirement sets is structurally impossible and
2112            // the parse-side no-op the empty-first arm closes (semver's
2113            // empty parse yields an implicit `*`) lives in exactly one
2114            // predicate. Every `ChildSpec::versao` past validate is
2115            // round-trippable through [`crate::parse_requirement`]
2116            // without re-checking at the resolver layer, and the three
2117            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2118            // are now structurally equivalent by construction.
2119            crate::render::require_valid_versao_requirement(
2120                child.versao_requirement(),
2121                || SupervisorError::empty_child_version(child.nome()),
2122                |reason| SupervisorError::ChildVersaoInvalid {
2123                    caixa: child.nome().to_string(),
2124                    versao: child.versao_requirement().to_string(),
2125                    reason,
2126                },
2127            )?;
2128            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2129                SupervisorError::duplicate_child_caixa(child.nome())
2130            })?;
2131        }
2132        Ok(())
2133    }
2134}
2135
2136/// Cross-slot coherence gate on the supervision tree: no
2137/// `:children :caixa` entry may name the supervisor's own `:nome`.
2138///
2139/// A supervisor that lists itself as a child is a degenerate self-parent
2140/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2141/// specs reference *distinct* child processes; a supervisor is never its
2142/// own child), and the wasm-operator's hierarchical reconciliation would
2143/// otherwise be handed a node that is its own parent: a one-node cycle it
2144/// either rejects far from the source `caixa.lisp` or recurses on. Because
2145/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2146/// lacre closure root), a child whose `:caixa` equals the supervisor's
2147/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2148///
2149/// Lives outside [`SupervisorSpec::validate`] because the typed view
2150/// carries the children but not the parent `:nome`; mirrors the
2151/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2152/// (which likewise reads one slot against another at the
2153/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2154/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2155/// node to itself is structurally not a tree/mesh edge" discipline, here
2156/// on the supervision-tree axis.
2157pub fn validate_no_self_supervision(
2158    children: &[ChildSpec],
2159    parent_nome: &str,
2160) -> Result<(), SupervisorError> {
2161    for child in children {
2162        if child.nome() == parent_nome {
2163            return Err(SupervisorError::child_supervises_self(parent_nome));
2164        }
2165    }
2166    Ok(())
2167}
2168
2169#[derive(Debug, Error, PartialEq, Eq)]
2170pub enum SupervisorError {
2171    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2172    NoChildren { estrategia: RestartStrategy },
2173    #[error(
2174        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2175    )]
2176    SimpleOneForOneWithStaticChildren,
2177    #[error(":max-restarts must be > 0")]
2178    ZeroMaxRestarts,
2179    #[error(
2180        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2181         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2182         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2183         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2184         can reach it, so the supervisor never escalates to its parent and a bad child can \
2185         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2186         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2187         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2188         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2189         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2190         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2191         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2192         band) or restructure the supervision tree (split the flaky child into its own \
2193         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2194    )]
2195    MaxRestartsExceedsCap { max_restarts: u32 },
2196    #[error(
2197        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2198         requires Period > 0; a zero window either trips on the first failure or \
2199         never trips depending on operator interpretation. Omit :restart-window to \
2200         express `never reset`; carry a positive duration to express the window."
2201    )]
2202    RestartWindowZero,
2203    #[error(
2204        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2205         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2206         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2207         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2208         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2209    )]
2210    RestartWindowNotCanonical { window: Duration },
2211    #[error(
2212        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2213         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2214         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2215         failure-counting window is structurally so long that transient restarts are never \
2216         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2217         when the child has exceeded its restart budget within the recent window` to `trip the \
2218         parent when the child has exceeded its restart budget over its lifetime`, and the \
2219         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2220         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2221         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2222         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2223         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2224         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2225         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2226         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2227         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2228         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2229         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2230         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2231         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2232         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2233         hiding it behind a rolling-window declaration the cap arm rejects)"
2234    )]
2235    RestartWindowExceedsCap { window: Duration },
2236    #[error("child entry has empty :caixa name")]
2237    EmptyChildName,
2238    #[error(
2239        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2240         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2241         name / label value the child name lands in — the per-child \
2242         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2243         label value, and the future wasm-operator per-child Service `metadata.name` \
2244         — each apiserver-side schema rejects names that don't match; use a \
2245         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2246    )]
2247    ChildCaixaInvalid { caixa: String, reason: String },
2248    #[error("child {caixa:?} has empty :versao constraint")]
2249    EmptyChildVersion { caixa: String },
2250    #[error(
2251        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2252         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2253         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2254         `:membros :versao` carry; the lacre pipeline resolves all three \
2255         through the same parser)"
2256    )]
2257    ChildVersaoInvalid {
2258        caixa: String,
2259        versao: String,
2260        reason: String,
2261    },
2262    #[error(
2263        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2264         child_spec.id per supervisor; duplicate children materialize as duplicate \
2265         ComputeUnits in the rendered chart, one silently overwriting the other)"
2266    )]
2267    DuplicateChildCaixa { caixa: String },
2268    #[error(
2269        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2270         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2271         OTP child specs reference distinct child processes). Since every :nome is a \
2272         globally-unique substrate identity, a child naming the supervisor's own :nome \
2273         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2274         self-referential :children entry or rename it to the actual child caixa."
2275    )]
2276    ChildSupervisesSelf { caixa: String },
2277}
2278
2279// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2280// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2281// and [`validate_no_self_supervision`] onto one substrate primitive per
2282// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2283// `LayoutError`-envelope constructor families the peer
2284// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2285// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2286// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2287// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2288// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2289// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2290// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2291// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2292// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2293// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2294// variants on `{ de, para }`) already at that discipline on the peer
2295// `AplicacaoError` envelopes.
2296//
2297// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2298// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2299// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2300// self-supervision arm) opened the identical
2301// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2302// the exact "same block re-inlined at every consumer" shape the PRIME
2303// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2304// `AplicacaoError` families each closed on their sibling envelopes. The
2305// three variants share one `{ caixa: String }` shape, so the fold routes
2306// each wire-up site through one dispatch per typed variant.
2307//
2308// The macro below generates one static constructor per variant of shape
2309// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2310// collapses onto one dispatch:
2311// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2312// struct-literal on the same `&str` fixture. The uniform one-field
2313// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2314// macro — rather than at every wire-up site. Every constructor is
2315// `#[must_use]` so a caller who mistakenly discards the constructed error
2316// trips a compile warning at the wire-up site.
2317//
2318// Every future consumer that wants to construct one of these three
2319// variants outside `SupervisorSpec::validate_children` /
2320// `validate_no_self_supervision` — a deferred
2321// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2322// webhook re-checking one added/renamed child, a future
2323// `feira validate --supervisor` per-caixa admission verb, a per-child
2324// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2325// once dynamic-children graduate to a typed slot, a per-Supervisor
2326// overlay resolver rejecting a duplicate/self-supervising child against
2327// a cluster-local snapshot — now reaches each variant through one call
2328// rather than re-inlining the three-line struct-literal in lockstep
2329// with the three in-crate wire-up sites.
2330macro_rules! supervisor_caixa_only_ctors {
2331    ($($ctor:ident => $variant:ident),* $(,)?) => {
2332        impl SupervisorError {
2333            $(
2334                #[doc = concat!(
2335                    "Construct a [`SupervisorError::",
2336                    stringify!($variant),
2337                    "`] naming the offending `:children :caixa` (or ",
2338                    "supervisor `:nome`, on the self-supervision arm). ",
2339                    "Folds the uniform `Self::",
2340                    stringify!($variant),
2341                    " { caixa: caixa.to_string() }` one-field ",
2342                    "struct-literal onto one substrate primitive so ",
2343                    "every [`SupervisorSpec::validate_children`] / ",
2344                    "[`validate_no_self_supervision`] wire-up on this ",
2345                    "variant reads through one dispatch rather than the ",
2346                    "pre-lift open-coded struct-literal block."
2347                )]
2348                #[must_use]
2349                pub fn $ctor(caixa: &str) -> Self {
2350                    Self::$variant { caixa: caixa.to_string() }
2351                }
2352            )*
2353        }
2354    };
2355}
2356
2357supervisor_caixa_only_ctors! {
2358    empty_child_version => EmptyChildVersion,
2359    duplicate_child_caixa => DuplicateChildCaixa,
2360    child_supervises_self => ChildSupervisesSelf,
2361}
2362
2363/// Shared duration string codec for the typed slots that take a
2364/// duration (`restart_window`, `MeshPolicy::timeout`,
2365/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2366/// reuse it without duplicating the parser.
2367pub mod duration_codec {
2368    use super::Duration;
2369    use serde::{Deserializer, Serializer};
2370
2371    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2372        // Route through the canonical [`crate::render::serialize_option_via_str`]
2373        // — the substrate-side single-owner primitive for the forward
2374        // arm of the typed-magnitude codec family. See its docstring
2375        // for the full sibling roster.
2376        crate::render::serialize_option_via_str(v, s, render)
2377    }
2378
2379    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2380        // Route through the canonical [`crate::render::deserialize_option_via_str`]
2381        // — the substrate-side single-owner primitive for the reverse
2382        // arm of the typed-magnitude codec family. See its docstring
2383        // for the full sibling roster.
2384        crate::render::deserialize_option_via_str(d, parse)
2385    }
2386
2387    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2388        // Paired whitespace-rejection arm — same canonical-form
2389        // render-determinism discipline as the peer
2390        // `limits::parse_byte_size` / `limits::parse_duration` /
2391        // `limits::parse_millicores` /
2392        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2393        // byte-scan closes the WhatWG-conformant whitespace bytes
2394        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2395        // `char::is_whitespace` scan closes the strictly-complementary
2396        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2397        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2398        // codepoints) that `str::trim` at parse entry silently strips.
2399        // Either drift class would round-trip through `render` to a
2400        // *different* canonical form on next emit — breaking the
2401        // THEORY.md Part V render-determinism contract on three typed-
2402        // duration slots at once (`:supervisor :restart-window`,
2403        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2404        // via the shared codec.
2405        //
2406        // Routed through the lifted [`crate::render::reject_whitespace`]
2407        // primitive — the substrate-side single-owner paired-arm gate
2408        // every typed-magnitude codec in caixa-core shares.
2409        crate::render::reject_whitespace::<String, _, _>(
2410            s,
2411            |b| {
2412                format!(
2413                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2414                 authoring form for the typed duration slots routed through this shared codec \
2415                 (`:supervisor :restart-window`, `:politicas :timeout`, \
2416                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2417                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2418                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2419                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2420                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2421                 Part V render-determinism contract every typed slot carries. Strip every \
2422                 whitespace byte (write `\"30s\"` verbatim)"
2423                )
2424            },
2425            |ch| {
2426                format!(
2427                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2428                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2429                 duration slots routed through this shared codec (`:supervisor \
2430                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2431                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2432                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2433                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2434                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2435                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2436                 `White_Space` property, strictly wider than the ASCII byte set) silently \
2437                 strips it at parse entry, and the value round-trips through `render` to \
2438                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2439                 the THEORY.md Part V render-determinism contract every typed slot \
2440                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2441                 verbatim with only ASCII bytes)",
2442                    cp = ch as u32
2443                )
2444            },
2445        )?;
2446        let s = s.trim();
2447        // Routed through the lifted
2448        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
2449        // the single-owner split every ASCII-alphabetic-unit typed-
2450        // magnitude codec in caixa-core (`limits::parse_byte_size` /
2451        // `limits::parse_duration` / this shared duration codec) shares.
2452        // See its docstring for the full sibling roster on the same
2453        // primitive altitude.
2454        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
2455        let num_trim = num_part.trim();
2456        // The canonical authoring form for every typed slot routed
2457        // through this shared codec — `:supervisor :restart-window`,
2458        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
2459        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
2460        // non-negative integer with no decimal point and no leading
2461        // sign, so the parser's accepted set must match for
2462        // serialize/deserialize to round-trip without canonical-form
2463        // drift. Until this gate landed the parser accepted any
2464        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
2465        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
2466        // tripped the value to a *different* canonical string on the
2467        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
2468        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
2469        // — breaking the THEORY.md Part V render-determinism contract
2470        // on three typed slots at once. Same canonical-form discipline
2471        // `crate::limits::parse_duration` (818dd38, the immediate
2472        // predecessor on the peer `:limits :wall-clock` codec) applies;
2473        // this gate lifts the discipline onto the shared codec that
2474        // backs the remaining three typed-duration slots in caixa-core.
2475        //
2476        // Strict canonical form: every byte of the magnitude is an
2477        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
2478        // inputs the gate distinguishes "non-canonical-but-numeric"
2479        // (parses as f64 or i64 — surfaced with a self-locating
2480        // diagnostic naming the canonical authoring form, the
2481        // round-trip drift each rejected shape would produce on first
2482        // serialize, and the canonical-form remediation) from
2483        // "garbage" (parses as neither — surfaced with the existing
2484        // narrower "bad duration magnitude" wording so its diagnostic
2485        // shape remains stable for the parser-shape footgun case).
2486        // The pre-existing `num < 0.0` arm is now unreachable — the
2487        // digit-only gate strictly precedes magnitude parsing, and a
2488        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
2489        // non-canonical-but-numeric branch with the `-30` named
2490        // verbatim in the diagnostic rather than the prior
2491        // value-laundered "negative duration in \"-30s\"" wording.
2492        //
2493        // Routed through the lifted
2494        // [`crate::render::is_digit_only_magnitude`] predicate — the
2495        // same source of truth the four peer typed-magnitude codec
2496        // sites share.
2497        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
2498        if !digit_only {
2499            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
2500            if numeric {
2501                return Err(format!(
2502                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
2503                     canonical authoring form for the typed duration slots routed through \
2504                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2505                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2506                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
2507                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
2508                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
2509                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
2510                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
2511                     THEORY.md Part V render-determinism contract every typed slot carries. \
2512                     Pick an integer magnitude in the unit that divides cleanly (write \
2513                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
2514                ));
2515            }
2516            return Err(format!("bad duration magnitude in {s:?}"));
2517        }
2518        // Leading-zero arm — peer with the `rate_limit_codec` leading-
2519        // zero arm (4f46830) on the same canonical-form render-
2520        // determinism axis. The digit-only gate accepts `"030s"`,
2521        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
2522        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
2523        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
2524        // *different* canonical string on the next emit, breaking the
2525        // THEORY.md Part V render-determinism contract the same way
2526        // `"+30s"` did before the leading-`+` arm landed. The single-
2527        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
2528        // losslessly through `render` (`render(Duration::ZERO)` emits
2529        // `"0s"`) — the downstream semantic-zero gates (e.g.
2530        // `SupervisorError::ZeroRestartWindow` on
2531        // `:supervisor :restart-window`,
2532        // `AplicacaoError::PolicyTimeoutZero` /
2533        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
2534        // duration slots) refuse zero-magnitude authoring at the typed-
2535        // validate layer above, so the single-byte `"0"` stays in the
2536        // accepted set at this codec layer and the diagnostic
2537        // partitioning between canonical-form drift (this arm) and
2538        // semantic-zero (the downstream gates) remains stable.
2539        // Peer with the future leading-zero arms on the two remaining
2540        // typed-magnitude codecs the trajectory acknowledges:
2541        // `limits::parse_duration` backing `:limits :wall-clock`,
2542        // `limits::parse_byte_size` backing `:limits :memory` — each
2543        // carries the same canonical-form-drift class today; this
2544        // gate lands the discipline on the shared duration codec
2545        // first because the `rate_limit_codec` predecessor on the
2546        // same canonical-form-drift axis is the closest peer on the
2547        // trajectory.
2548        //
2549        // Routed through the lifted
2550        // [`crate::render::is_leading_zero_padded_magnitude`]
2551        // predicate — the same source of truth the four peer
2552        // typed-magnitude codec sites share.
2553        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
2554            return Err(format!(
2555                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
2556                 canonical authoring form for the typed duration slots routed through \
2557                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2558                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2559                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
2560                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
2561                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
2562                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
2563                 serialize — breaking the THEORY.md Part V render-determinism contract \
2564                 every typed slot carries. Strip the leading zeros (write \
2565                 `\"30s\"` instead of `\"030s\"`)"
2566            ));
2567        }
2568        // The digit-only gate guarantees every byte is `[0-9]`, and
2569        // the leading-zero arm above guarantees the magnitude is
2570        // either the single byte `"0"` or starts with `[1-9]`, so
2571        // the only way `u64::from_str` can fail here is overflow (the
2572        // magnitude exceeds `u64::MAX`). Surface that with an
2573        // overflow-shaped wording so the diagnostic names the offending
2574        // magnitude verbatim rather than collapsing onto the
2575        // non-canonical arm. The codec now operates on `u64` end-to-end
2576        // — every accepted magnitude is integer-exact; no f64 mantissa
2577        // drift between author-supplied magnitude and the consumer's
2578        // `Duration` value. Same shape `crate::limits::parse_duration`
2579        // (818dd38) carries on the peer `:limits :wall-clock` axis.
2580        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
2581            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
2582        })?;
2583        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
2584        // unit-arm dispatch through the canonical
2585        // [`crate::render::duration_from_integer_magnitude_and_unit`]
2586        // primitive — the substrate-side single-owner unit-dispatch
2587        // table every typed-duration codec in caixa-core routes
2588        // through (peer: `crate::limits::parse_duration` backing
2589        // `:limits :wall-clock`). Every unit conversion is integer-
2590        // exact for an integer magnitude; overflow surfaces via the
2591        // typed `DurationUnitError::Overflow { multiplier }`
2592        // discriminant so this arm reconstructs the pre-lift
2593        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
2594        // wording verbatim from `num` / `unit_trim` / the returned
2595        // `multiplier`, and the unknown-unit arm reconstructs the
2596        // pre-lift `"unknown duration unit \"<other>\""` wording from
2597        // the caller-scoped `unit_trim`. Load-bearing pinned by
2598        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
2599        let unit_trim = unit.trim();
2600        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
2601            |e| match e {
2602                crate::render::DurationUnitError::Overflow { multiplier } => format!(
2603                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
2604                ),
2605                crate::render::DurationUnitError::UnknownUnit => {
2606                    format!("unknown duration unit {unit_trim:?}")
2607                }
2608            },
2609        )?;
2610        Ok(dur)
2611    }
2612
2613    /// Render a [`Duration`] in the canonical pleme-io duration string
2614    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
2615    /// caixa typed-duration slot serializes to and the same form K8s
2616    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
2617    /// EnvoyConfig per-route timeouts both expect (an integer
2618    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
2619    /// `+`). Lifted to `pub` so caixa-side renderers
2620    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
2621    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
2622    /// emitter, the future caixa-otel collector pipeline emitter) can
2623    /// consume the same canonical formatter without re-inlining the
2624    /// magnitude/unit decision tree (and inheriting the same drift
2625    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
2626    /// downstream apply-time parsing in non-obvious ways).
2627    pub fn render(d: Duration) -> String {
2628        let total_ms = d.as_millis();
2629        if total_ms == 0 {
2630            return "0s".into();
2631        }
2632        if total_ms.is_multiple_of(3600 * 1000) {
2633            return format!("{}h", total_ms / (3600 * 1000));
2634        }
2635        if total_ms.is_multiple_of(60 * 1000) {
2636            return format!("{}m", total_ms / (60 * 1000));
2637        }
2638        if total_ms.is_multiple_of(1000) {
2639            return format!("{}s", total_ms / 1000);
2640        }
2641        format!("{total_ms}ms")
2642    }
2643
2644    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
2645    ///
2646    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
2647    /// largest divisor unit, so any sub-millisecond residue
2648    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
2649    /// §V.2.7 render-determinism contract:
2650    ///
2651    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
2652    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
2653    ///     `1_000_000` ns ≠ original `1_500_000` ns;
2654    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
2655    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
2656    ///     on every typed-`Duration` slot then rejects on re-validate.
2657    ///
2658    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
2659    /// the codec's round-trippable accepted set lives in exactly one place —
2660    /// every typed-`Duration` slot that routes through this shared codec
2661    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
2662    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
2663    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
2664    /// every typed-`Duration` slot whose own codec shares the same
2665    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
2666    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
2667    /// pair) calls this predicate from its `validate()` to bracket the
2668    /// accepted set against the codec's accepted set, structurally. Drift
2669    /// between the codec's granularity and any typed slot's accepted set is
2670    /// then a single-source-of-truth edit at this predicate rather than a
2671    /// silent round-trip break the next consumer discovers at apply time.
2672    ///
2673    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
2674    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
2675    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
2676    /// family — same "typed-slot's valid set matches its codec's accepted
2677    /// set, structurally" discipline carried at the codec layer.
2678    #[must_use]
2679    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
2680        d.subsec_nanos().is_multiple_of(1_000_000)
2681    }
2682}
2683
2684/// Required-Duration variant for fields that aren't Option<Duration>.
2685pub mod duration_codec_required {
2686    use super::Duration;
2687    use serde::{Deserialize, Deserializer, Serializer};
2688
2689    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
2690        s.serialize_str(&super::duration_codec::render(*v))
2691    }
2692
2693    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
2694        let s = String::deserialize(d)?;
2695        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
2696    }
2697}
2698
2699#[cfg(test)]
2700mod tests {
2701    use super::*;
2702
2703    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
2704        ChildSpec {
2705            caixa: name.into(),
2706            versao: ver.into(),
2707            restart,
2708        }
2709    }
2710
2711    #[test]
2712    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
2713        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
2714        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
2715        // posture. Each accessor projects the per-`:children :caixa`
2716        // / per-`:children :versao` [`String`] storage through the
2717        // `pub const fn` [`String::as_str`] (const-stable since Rust
2718        // 1.87, well within the workspace MSRV) — any future
2719        // accidental downgrade to non-`const` fails the corresponding
2720        // `<name>_via_const_fn` wrapper at caixa-core build time with
2721        // E0015 (`cannot call non-const method`), strictly stronger
2722        // than a runtime `assert!`. Sibling of the peer
2723        // per-M2/M3/universal-axis `String → &str` scalar-accessor
2724        // family pins on the sibling `const`-eval-surface passes
2725        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
2726        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
2727        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
2728        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
2729        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
2730        // [`crate::aplicacao::Entrada::destination`] at the M3
2731        // ingress axis,
2732        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
2733        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
2734        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
2735        // axis, and the per-`:contratos`
2736        // [`crate::aplicacao::WitContract::source`] /
2737        // [`crate::aplicacao::WitContract::destination`] /
2738        // [`crate::aplicacao::WitContract::world_ref`] trio the
2739        // sibling pin at 279823b already anchors).
2740        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
2741            c.nome()
2742        }
2743        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
2744            c.versao_requirement()
2745        }
2746        for (caixa, versao) in [
2747            ("worker-a", "^0.1"),
2748            ("worker-b", "~0.2.3"),
2749            ("collector", "*"),
2750        ] {
2751            let c = child(caixa, versao, RestartPolicy::Permanent);
2752            assert_eq!(nome_via_const_fn(&c), c.nome());
2753            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
2754            assert_eq!(c.nome(), caixa);
2755            assert_eq!(c.versao_requirement(), versao);
2756        }
2757    }
2758
2759    #[test]
2760    fn supervisor_children_slice_return_accessor_is_const_fn() {
2761        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
2762        // `const`-eval-surface posture. The accessor destructures the
2763        // per-`:children` `Vec<ChildSpec>` storage through the
2764        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
2765        // 1.66, well within the workspace MSRV) — any future
2766        // accidental downgrade to non-`const` fails
2767        // `children_via_const_fn` at caixa-core build time with E0015
2768        // (`cannot call non-const method`), strictly stronger than a
2769        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
2770        // `Vec → &[T]` slice-return accessor family pin
2771        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
2772        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
2773        // per-`:membros` / per-`:contratos` slice-return axes, and of
2774        // the peer M2 upgrade-appup axis pin
2775        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
2776        // on the per-`:upgrade-from :instructions` slice-return axis.
2777        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
2778            s.children()
2779        }
2780        // Sweep both the empty-children (leaf-supervisor with no
2781        // static children — the `SimpleOneForOne` dynamic-child
2782        // arm's canonical shape) and the populated-children
2783        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
2784        // arm's canonical shape) axes so the accessor carries a
2785        // const-dispatch pin on both arms.
2786        let s_empty = SupervisorSpec {
2787            estrategia: RestartStrategy::SimpleOneForOne,
2788            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2789            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2790            children: vec![],
2791        };
2792        assert!(children_via_const_fn(&s_empty).is_empty());
2793        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
2794        let s_full = SupervisorSpec {
2795            estrategia: RestartStrategy::OneForOne,
2796            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2797            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2798            children: vec![
2799                child("worker-a", "^0.1", RestartPolicy::Permanent),
2800                child("worker-b", "~0.2.3", RestartPolicy::Transient),
2801                child("collector", "*", RestartPolicy::Temporary),
2802            ],
2803        };
2804        assert_eq!(children_via_const_fn(&s_full).len(), 3);
2805        assert_eq!(children_via_const_fn(&s_full), s_full.children());
2806    }
2807
2808    #[test]
2809    fn default_has_one_for_one_and_5_restarts_in_60s() {
2810        let s = SupervisorSpec::default();
2811        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
2812        assert_eq!(s.max_restarts, 5);
2813        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
2814        assert!(s.children.is_empty());
2815    }
2816
2817    #[test]
2818    fn validate_one_for_one_requires_children() {
2819        let mut s = SupervisorSpec::default();
2820        s.children = vec![];
2821        assert!(matches!(
2822            s.validate().unwrap_err(),
2823            SupervisorError::NoChildren { .. }
2824        ));
2825        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
2826        s.validate().unwrap();
2827    }
2828
2829    #[test]
2830    fn validate_simple_one_for_one_forbids_static_children() {
2831        let mut s = SupervisorSpec {
2832            estrategia: RestartStrategy::SimpleOneForOne,
2833            ..SupervisorSpec::default()
2834        };
2835        s.children
2836            .push(child("w", "^0.1", RestartPolicy::Permanent));
2837        assert_eq!(
2838            s.validate().unwrap_err(),
2839            SupervisorError::SimpleOneForOneWithStaticChildren
2840        );
2841        s.children.clear();
2842        s.validate().unwrap();
2843    }
2844
2845    #[test]
2846    fn validate_rejects_zero_max_restarts() {
2847        let s = SupervisorSpec {
2848            max_restarts: 0,
2849            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2850            ..SupervisorSpec::default()
2851        };
2852        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
2853    }
2854
2855    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
2856    //
2857    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
2858    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
2859    // `:supervisor :max-restarts` axis — both fields are "trip the
2860    // next-higher protection layer after N events in a rolling window"
2861    // counters with identical degenerate-at-the-high-end shape, so the
2862    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
2863    // exactly as it lies in `1..=1000` on the breaker side.
2864
2865    #[test]
2866    fn validate_rejects_max_restarts_above_cap() {
2867        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
2868        // 1` is structurally one past the cap and silently passed
2869        // validate on every pre-gate codebase because the typed slot's
2870        // only check was the zero-floor arm. The no-op-supervisor vector
2871        // only surfaced at the runtime substrate (Erlang/OTP
2872        // MaxIntensity/Period ratio, the future wasm-operator's
2873        // per-supervisor restart-intensity counter) far from the source
2874        // caixa.lisp with no field naming the offending supervisor.
2875        let s = SupervisorSpec {
2876            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2877            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2878            ..SupervisorSpec::default()
2879        };
2880        assert_eq!(
2881            s.validate().unwrap_err(),
2882            SupervisorError::MaxRestartsExceedsCap {
2883                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2884            }
2885        );
2886    }
2887
2888    #[test]
2889    fn validate_rejects_max_restarts_far_above_cap() {
2890        // The `u32::MAX` worst case — the four-billion-restart
2891        // threshold a typo (`:max-restarts 4294967295`) or a
2892        // struct-literal copy-paste lands in the slot. Pin the cap
2893        // arm's coverage explicitly across the full `u32` overflow so
2894        // a future relaxation that drops the upper bound surfaces
2895        // here. Same shape every other typed-cap arm on this surface
2896        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
2897        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
2898        let s = SupervisorSpec {
2899            max_restarts: u32::MAX,
2900            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2901            ..SupervisorSpec::default()
2902        };
2903        assert_eq!(
2904            s.validate().unwrap_err(),
2905            SupervisorError::MaxRestartsExceedsCap {
2906                max_restarts: u32::MAX,
2907            }
2908        );
2909    }
2910
2911    #[test]
2912    fn validate_accepts_max_restarts_at_cap() {
2913        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
2914        // must validate. The cap is inclusive on the top edge,
2915        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
2916        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
2917        // discipline on the sibling capped axes. Pin the boundary
2918        // explicitly so a future off-by-one tightening
2919        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
2920        // here as a test failure rather than a silent contract
2921        // narrowing.
2922        let s = SupervisorSpec {
2923            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
2924            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2925            ..SupervisorSpec::default()
2926        };
2927        s.validate()
2928            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
2929    }
2930
2931    #[test]
2932    fn validate_accepts_max_restarts_typical_values() {
2933        // The documented production-playbook band positive-control
2934        // sweep — every value Erlang/OTP / Elixir / Riak Core /
2935        // RabbitMQ recommend (1..=100) must pass, plus a sweep
2936        // through the hyperscale band (200, 500, 1000) the cap
2937        // accepts. Pin the inclusive validated set explicitly so a
2938        // future tightening of the ceiling surfaces here.
2939        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
2940            let s = SupervisorSpec {
2941                max_restarts: n,
2942                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2943                ..SupervisorSpec::default()
2944            };
2945            s.validate()
2946                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
2947        }
2948    }
2949
2950    #[test]
2951    fn zero_max_restarts_takes_precedence_over_cap() {
2952        // The cross-arm ordering pin: `0` is structurally outside
2953        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
2954        // (cap), but the zero-floor diagnostic is the more
2955        // self-locating one (it directly names the counter-axis
2956        // remediation), so the validate gate must fire on zero first.
2957        // Same shape every other zero-then-shape ordering on this
2958        // surface uses (PolicyRetriesZero then
2959        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
2960        // PolicyBreakerMaxFailuresExceedsCap).
2961        let s = SupervisorSpec {
2962            max_restarts: 0,
2963            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2964            ..SupervisorSpec::default()
2965        };
2966        assert_eq!(
2967            s.validate().unwrap_err(),
2968            SupervisorError::ZeroMaxRestarts,
2969            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
2970        );
2971    }
2972
2973    #[test]
2974    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
2975        // The cross-arm ordering pin between the cap and the sibling
2976        // `:restart-window` gates (zero-window, canonical-window). A
2977        // supervisor carrying both an over-cap `max_restarts` AND a
2978        // structurally invalid window (zero, sub-ms) must surface the
2979        // cap diagnostic first — the cap arm is wired immediately
2980        // after the zero-restart arm and strictly before the window
2981        // arms, so the offending value the diagnostic names matches
2982        // the order the author would discover the gates by reading
2983        // top-to-bottom through `SupervisorSpec::validate`. Pin the
2984        // order so a future refactor that reorders the arms surfaces
2985        // here as a test failure rather than a silent diagnostic
2986        // regression. Peer of
2987        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
2988        // on the sibling `:politicas :circuit-breaker` slot.
2989        let s = SupervisorSpec {
2990            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2991            restart_window: Some(Duration::ZERO),
2992            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2993            ..SupervisorSpec::default()
2994        };
2995        assert_eq!(
2996            s.validate().unwrap_err(),
2997            SupervisorError::MaxRestartsExceedsCap {
2998                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2999            },
3000            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3001        );
3002    }
3003
3004    #[test]
3005    fn max_restarts_cap_diagnostic_carries_offending_value() {
3006        // The diagnostic-shape pin: the offending `u32` is carried
3007        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3008        // variant so the surfaced error message names the value the
3009        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3010        // supervisor-policy ceiling …"`), not just the cap. Same
3011        // self-locating diagnostic shape every other typed-cap arm on
3012        // this surface carries
3013        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3014        // the offending failure count verbatim,
3015        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3016        // retries count verbatim).
3017        let s = SupervisorSpec {
3018            max_restarts: 50_000,
3019            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3020            ..SupervisorSpec::default()
3021        };
3022        let err = s.validate().unwrap_err();
3023        assert!(
3024            matches!(
3025                err,
3026                SupervisorError::MaxRestartsExceedsCap {
3027                    max_restarts: 50_000
3028                }
3029            ),
3030            "got {err:?}"
3031        );
3032        let msg = err.to_string();
3033        assert!(
3034            msg.contains("50000"),
3035            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3036        );
3037    }
3038
3039    #[test]
3040    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3041        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3042        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3043        // half of Learn You Some Erlang's worker-supervisor default,
3044        // sibling of the `60s` `Period` half that the paired
3045        // [`Default for SupervisorSpec`] impl already pins on the
3046        // sibling `restart_window` axis. Pinning the literal here
3047        // surfaces a future rebrand (a tightening to Elixir's `3`,
3048        // a widening to a per-cluster overlay the operator pins
3049        // through a future `:max-restarts-overrides` slot) as a
3050        // deliberate test edit, not a silent contract migration.
3051        // Peer of the sibling
3052        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3053        // upper-bracket pin on the same axis.
3054        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3055    }
3056
3057    #[test]
3058    fn default_max_restarts_helper_routes_through_lifted_default() {
3059        // Composition pin: the private `default_max_restarts()`
3060        // serde-`#[serde(default = "…")]` helper on
3061        // [`SupervisorSpec::max_restarts`] must route through the
3062        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3063        // typed `pub const` rather than a raw `5` literal. Prior to
3064        // the lift the helper carried an inline `5` with no compile-
3065        // time link back to the shared default, so the wire-format
3066        // author-omitted arm and the caixa-core
3067        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3068        // arm could silently split on any future default rebrand.
3069        // Byte-parity against the lifted constant closes the split.
3070        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3071    }
3072
3073    #[test]
3074    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3075        // Composition pin: the [`Default for SupervisorSpec`] impl's
3076        // struct-literal `max_restarts` field must route through the
3077        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3078        // typed `pub const` (via the private helper this test's
3079        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3080        // already pins onto the constant). Structurally: every
3081        // `SupervisorSpec::default()` call must yield a
3082        // `max_restarts` field byte-equal to the lifted constant
3083        // (the two paired defaults — the serde-side wire-format arm
3084        // and the struct-literal default arm — cannot silently split
3085        // on any future default rebrand). Peer of the sibling
3086        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3087        // — this pin closes the byte-parity arm on the two paired
3088        // altitude entry points onto the shared substrate constant.
3089        assert_eq!(
3090            SupervisorSpec::default().max_restarts(),
3091            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3092        );
3093    }
3094
3095    #[test]
3096    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3097        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3098        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3099        // Learn You Some Erlang's worker-supervisor default, paired
3100        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3101        // `MaxIntensity` half this constant is the sliding-window
3102        // denominator of on the same `MaxIntensity / Period`
3103        // restart-intensity ratio. Pinning the literal here surfaces a
3104        // future coherent rebrand of the paired default (Elixir's
3105        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3106        // the operator pins through a future
3107        // `:restart-window-overrides` slot) as a deliberate test edit,
3108        // not a silent contract migration. Peer of the sibling
3109        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3110        // paired-half pin on the same OTP-canonical default and the
3111        // [`supervisor_restart_window_cap_pins_canonical_value`]
3112        // upper-bracket pin on the same axis.
3113        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3114    }
3115
3116    #[test]
3117    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3118        // Composition pin: the [`Default for SupervisorSpec`] impl's
3119        // struct-literal `restart_window` field must route through the
3120        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3121        // typed `pub const` rather than a raw
3122        // `Duration::from_secs(60)` literal. Prior to this lift the
3123        // paired `{intensity, 5, 60}` OTP-canonical default was split
3124        // across two altitudes with no compile-time link between the
3125        // halves — the `MaxIntensity` half rode through the lifted
3126        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3127        // `Period` half rode as an open-coded literal at the
3128        // composition site, so a future coherent rebrand of the paired
3129        // canonical would have had to migrate one half through the
3130        // constant and the other through a raw literal in lockstep.
3131        // Byte-parity against the lifted constant on the `Period` half
3132        // closes the split — the paired OTP-canonical default now
3133        // migrates as one unit on any future axis change. Peer of the
3134        // sibling
3135        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3136        // byte-parity pin on the paired `MaxIntensity` half.
3137        assert_eq!(
3138            SupervisorSpec::default().restart_window(),
3139            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3140        );
3141    }
3142
3143    #[test]
3144    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3145        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3146        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3147        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3148        // canonical default, paired with the sibling
3149        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3150        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3151        // this constant is the strategy discriminator of on the same
3152        // OTP-canonical worker-supervisor default. Pinning the arm here
3153        // surfaces a future coherent rebrand of the paired triple (Elixir's
3154        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3155        // intensity/period axes leaving this strategy arm untouched, an OTP
3156        // `rest_for_one` widening once the substrate discovers startup-
3157        // order-coupled child cohorts as the more common worker-supervisor
3158        // shape, a per-cluster overlay the operator pins through a future
3159        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3160        // supervision-canary roadmap acknowledges) as a deliberate test
3161        // edit, not a silent contract migration. Peer of the sibling
3162        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3163        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3164        // paired-half pins on the same OTP-canonical default.
3165        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3166    }
3167
3168    #[test]
3169    fn restart_strategy_default_routes_through_lifted_default() {
3170        // Composition pin: the [`Default for RestartStrategy`] impl's
3171        // return arm must route through the substrate-canonical
3172        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3173        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3174        // an inline `Self::OneForOne` with no compile-time link back to
3175        // the shared OTP-canonical `one_for_one` strategy the paired
3176        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3177        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3178        // `.unwrap_or_default()` (now
3179        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3180        // so a future rebrand of the OTP-canonical strategy default (an
3181        // OTP `rest_for_one` widening once the substrate discovers
3182        // startup-order-coupled child cohorts as the more common worker-
3183        // supervisor shape, a per-cluster overlay the operator pins
3184        // through a future `:estrategia-overrides` slot) would have had to
3185        // be threaded through the `Default` impl and the two peer routes
3186        // in lockstep or the three consumers would silently split. Byte-
3187        // parity against the lifted constant closes the split. Peer of
3188        // the sibling
3189        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3190        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3191        // composition pins on the paired `MaxIntensity` + `Period` halves.
3192        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3193    }
3194
3195    #[test]
3196    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3197        // Composition pin: the [`Default for SupervisorSpec`] impl's
3198        // struct-literal `estrategia` field must route through the
3199        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3200        // `pub const` (either directly, or via the
3201        // [`RestartStrategy::default`] impl that the sibling
3202        // `restart_strategy_default_routes_through_lifted_default` pin
3203        // already routes onto the constant). Structurally: every
3204        // `SupervisorSpec::default()` call must yield an `estrategia`
3205        // field byte-equal to the lifted constant (the three paired
3206        // defaults — the [`Default for RestartStrategy`] impl arm, the
3207        // struct-literal default arm here, and the
3208        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3209        // silently split on any future default rebrand). Peer of the
3210        // sibling
3211        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3212        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3213        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3214        // of the same `SupervisorSpec::default()` composed altitude.
3215        assert_eq!(
3216            SupervisorSpec::default().estrategia(),
3217            SUPERVISOR_ESTRATEGIA_DEFAULT,
3218        );
3219    }
3220
3221    #[test]
3222    fn supervisor_child_restart_default_pins_otp_canonical_value() {
3223        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3224        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3225        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3226        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3227        // half of the same OTP-shape supervisor-tree default set whose
3228        // per-`:supervisor` halves the sibling
3229        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3230        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3231        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3232        // arm here surfaces a future rebrand of the per-child default (an
3233        // OTP-`transient` widening once the substrate discovers clean-
3234        // completion-aware children as the more common child shape, a
3235        // per-cluster overlay the operator pins through a future
3236        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3237        // supervision-canary roadmap acknowledges) as a deliberate test
3238        // edit, not a silent contract migration. Peer of the sibling
3239        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3240        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3241        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3242        // value pins on the per-`:supervisor` halves.
3243        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3244    }
3245
3246    #[test]
3247    fn restart_policy_default_routes_through_lifted_default() {
3248        // Composition pin: the [`Default for RestartPolicy`] impl's return
3249        // arm must route through the substrate-canonical
3250        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3251        // than a raw `Self::Permanent` arm. Prior to the lift the impl
3252        // carried an inline `Self::Permanent` with no compile-time link
3253        // back to the OTP-shape supervisor-tree default set whose three
3254        // per-`:supervisor` halves already rode through lifted constants
3255        // — so a future coherent rebrand of the set would have had to
3256        // migrate three halves through typed constants and this fourth
3257        // through a raw enum arm in lockstep or the supervisor-level and
3258        // child-level defaults would silently drift apart. Byte-parity
3259        // against the lifted constant closes the split. Peer of the
3260        // sibling
3261        // [`restart_strategy_default_routes_through_lifted_default`]
3262        // composition pin on the per-`:supervisor` `:estrategia` axis.
3263        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3264    }
3265
3266    #[test]
3267    fn child_spec_serde_default_restart_routes_through_lifted_default() {
3268        // Composition pin: the serde-side `#[serde(default)]` on
3269        // [`ChildSpec::restart`] — the wire-format author-omitted
3270        // `:children :restart` arm — must resolve onto the substrate-
3271        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3272        // (via the [`Default for RestartPolicy`] impl the sibling
3273        // `restart_policy_default_routes_through_lifted_default` pin
3274        // already routes onto the constant). Structurally: a `ChildSpec`
3275        // deserialized from a payload that omits the `restart` key must
3276        // yield a `restart` field byte-equal to the lifted constant, so
3277        // the wire-format author-omitted arm and the
3278        // [`RestartPolicy::default`] impl arm cannot silently split on any
3279        // future default rebrand. Peer of the sibling
3280        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3281        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3282        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3283        // byte-parity pins on the per-`:supervisor` halves of the same
3284        // author-omitted-slot resolution surface.
3285        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3286            .expect("ChildSpec must deserialize with the restart key omitted");
3287        assert_eq!(
3288            omitted.restart(),
3289            SUPERVISOR_CHILD_RESTART_DEFAULT,
3290            "an author-omitted :children :restart slot must degrade onto \
3291             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3292             {:?}, expected {:?})",
3293            omitted.restart(),
3294            SUPERVISOR_CHILD_RESTART_DEFAULT,
3295        );
3296    }
3297
3298    #[test]
3299    fn supervisor_max_restarts_cap_pins_canonical_value() {
3300        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3301        // 1000 — the same ceiling the peer
3302        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3303        // `:politicas :circuit-breaker :max-failures` axis (both are
3304        // "trip the next-higher protection layer after N events in a
3305        // rolling window" counters with identical
3306        // degenerate-at-the-high-end shape; uniform top edge so the
3307        // M4 CR materializers and the wasm-operator reconciler reach
3308        // for either field knowing the value is in `1..=1000`). Two
3309        // orders of magnitude above every documented Erlang/OTP /
3310        // Elixir / Riak Core / RabbitMQ production-playbook
3311        // recommendation band and below the clearly-pathological
3312        // "effectively no escalation" floor (10_000, 100_000,
3313        // u32::MAX). Pinning the literal value here surfaces a future
3314        // drift (a relaxation to 10_000, a tightening to 100) as a
3315        // deliberate test edit, not a silent contract narrowing.
3316        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3317    }
3318
3319    #[test]
3320    fn validate_rejects_empty_child_name() {
3321        let s = SupervisorSpec {
3322            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3323            ..SupervisorSpec::default()
3324        };
3325        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3326    }
3327
3328    #[test]
3329    fn validate_rejects_empty_child_version() {
3330        let s = SupervisorSpec {
3331            children: vec![child("w", "", RestartPolicy::Permanent)],
3332            ..SupervisorSpec::default()
3333        };
3334        assert!(matches!(
3335            s.validate().unwrap_err(),
3336            SupervisorError::EmptyChildVersion { .. }
3337        ));
3338    }
3339
3340    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3341
3342    #[test]
3343    fn validate_rejects_invalid_child_versao_requirement() {
3344        // The fail-before-pass-after pin: a non-empty but malformed
3345        // semver requirement (`"^bad-version"`) silently passed
3346        // `validate()` on every pre-gate codebase because the prior
3347        // shape only refused the empty string. The parse failure
3348        // surfaced far downstream at lacre-resolve time with a
3349        // `semver::Error` that didn't name which `:children` entry
3350        // carried the typo. The new gate moves the check to caixa-build
3351        // time at the source caixa.lisp — the third `:versao` typed
3352        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3353        // structural parity.
3354        let s = SupervisorSpec {
3355            children: vec![
3356                child("worker", "^0.1", RestartPolicy::Permanent),
3357                child("cache", "^bad-version", RestartPolicy::Transient),
3358            ],
3359            ..SupervisorSpec::default()
3360        };
3361        let err = s.validate().unwrap_err();
3362        assert!(
3363            matches!(
3364                err,
3365                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3366                    if caixa == "cache" && versao == "^bad-version"
3367            ),
3368            "got {err:?}"
3369        );
3370    }
3371
3372    #[test]
3373    fn validate_rejects_child_versao_with_double_caret_typo() {
3374        // `"^^0.1"` is the canonical doubled-caret typo — looks
3375        // Cargo-shaped on first glance but fails the parser because
3376        // semver doesn't accept stacked operators. Pin this
3377        // adjacent-shape footgun explicitly so a future relaxation that
3378        // accepts "looks-canonical-but-isn't" forms surfaces here.
3379        let s = SupervisorSpec {
3380            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
3381            ..SupervisorSpec::default()
3382        };
3383        let err = s.validate().unwrap_err();
3384        assert!(
3385            matches!(
3386                err,
3387                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3388                    if caixa == "worker" && versao == "^^0.1"
3389            ),
3390            "got {err:?}"
3391        );
3392    }
3393
3394    #[test]
3395    fn validate_rejects_child_versao_with_v_prefixed_tag() {
3396        // `"v0.1"` is the canonical "git-tag-shape leaking into the
3397        // semver requirement slot" typo — an author copies the
3398        // publish-side git-tag string verbatim into `:versao`, but
3399        // Cargo's semver parser rejects the leading `v`. Same
3400        // adjacent-shape footgun pinned for `:membros :versao`
3401        // (9888b13).
3402        let s = SupervisorSpec {
3403            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
3404            ..SupervisorSpec::default()
3405        };
3406        let err = s.validate().unwrap_err();
3407        assert!(
3408            matches!(
3409                err,
3410                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3411                    if caixa == "worker" && versao == "v0.1"
3412            ),
3413            "got {err:?}"
3414        );
3415    }
3416
3417    #[test]
3418    fn validate_accepts_canonical_child_versao_forms() {
3419        // The Cargo-shaped requirement forms `:deps :versao` and
3420        // `:membros :versao` already accept via
3421        // `crate::parse_requirement` must pass the children gate
3422        // without re-validating at the resolver layer. Pin every leg so
3423        // a future tightening of the canonical set surfaces here as a
3424        // test failure.
3425        for form in [
3426            "^0.1",      // caret — minor-range pin (the most common shape)
3427            "~0.1.2",    // tilde — patch-range pin
3428            "0.1.0",     // exact — single-version pin
3429            "*",         // wildcard — any version (semver::VersionReq::STAR)
3430            ">=0.1, <2", // multi-range — comma-separated comparators
3431        ] {
3432            let s = SupervisorSpec {
3433                children: vec![child("worker", form, RestartPolicy::Permanent)],
3434                ..SupervisorSpec::default()
3435            };
3436            s.validate()
3437                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3438        }
3439    }
3440
3441    #[test]
3442    fn child_versao_empty_takes_precedence_over_invalid() {
3443        // Order pin: the existing `EmptyChildVersion` diagnostic (which
3444        // doesn't try to parse) fires before the new
3445        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
3446        // `:versao` keeps its narrower error message —
3447        // `parse_requirement` would also reject `""`, but the
3448        // empty-string arm is the more self-locating diagnostic for the
3449        // author. Same ordering discipline as
3450        // `membro_versao_empty_takes_precedence_over_invalid` in
3451        // aplicacao.rs.
3452        let s = SupervisorSpec {
3453            children: vec![child("worker", "", RestartPolicy::Permanent)],
3454            ..SupervisorSpec::default()
3455        };
3456        let err = s.validate().unwrap_err();
3457        assert!(
3458            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
3459            "got {err:?}"
3460        );
3461    }
3462
3463    #[test]
3464    fn child_versao_invalid_fires_before_duplicate_check() {
3465        // Order pin: a malformed requirement on a non-duplicate entry
3466        // surfaces *its own* diagnostic (which names the offending
3467        // `:versao` string), even when a later entry would otherwise
3468        // collapse onto an earlier name. The per-entry shape gate runs
3469        // inline before the duplicate-key insert — parallel to
3470        // `membro_versao_invalid_fires_before_duplicate_check` in
3471        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
3472        let s = SupervisorSpec {
3473            children: vec![
3474                child("worker", "^bad", RestartPolicy::Permanent),
3475                child("cache", "^0.1", RestartPolicy::Transient),
3476                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3477            ],
3478            ..SupervisorSpec::default()
3479        };
3480        let err = s.validate().unwrap_err();
3481        assert!(
3482            matches!(
3483                err,
3484                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
3485            ),
3486            "got {err:?}"
3487        );
3488    }
3489
3490    #[test]
3491    fn child_versao_invalid_diagnostic_carries_offending_versao() {
3492        // The diagnostic-shape pin: the error names the offending
3493        // `:versao` value verbatim so the author can grep their
3494        // caixa.lisp without re-running the build, and carries a
3495        // non-empty `reason` from `semver::VersionReq::parse` so the
3496        // parser's own wording flows through to the diagnostic.
3497        let s = SupervisorSpec {
3498            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
3499            ..SupervisorSpec::default()
3500        };
3501        let err = s.validate().unwrap_err();
3502        let SupervisorError::ChildVersaoInvalid {
3503            caixa,
3504            versao,
3505            reason,
3506        } = err
3507        else {
3508            panic!("expected ChildVersaoInvalid, got other variant");
3509        };
3510        assert_eq!(caixa, "worker");
3511        assert_eq!(versao, "not-a-req");
3512        assert!(
3513            !reason.is_empty(),
3514            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
3515        );
3516    }
3517
3518    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
3519
3520    #[test]
3521    fn validate_rejects_child_caixa_with_uppercase() {
3522        // The canonical "I copied the Servico's display name verbatim"
3523        // typo — child caixa names are lowercase per K8s DNS-1123 label
3524        // rule. The diagnostic names the offending name and suggests the
3525        // lower-cased fix in one edit, mirroring the
3526        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
3527        let s = SupervisorSpec {
3528            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
3529            ..SupervisorSpec::default()
3530        };
3531        let err = s.validate().unwrap_err();
3532        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3533            panic!("expected ChildCaixaInvalid, got other variant");
3534        };
3535        assert_eq!(caixa, "Worker");
3536        assert!(
3537            reason.contains("uppercase"),
3538            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
3539        );
3540        assert!(
3541            reason.contains("\"worker\""),
3542            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
3543        );
3544    }
3545
3546    #[test]
3547    fn validate_rejects_child_caixa_with_underscore() {
3548        // The canonical "I'm thinking of a Python module / Postgres
3549        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
3550        // label schema. K8s rejects `metadata.name: my_worker` at
3551        // admission time with an opaque `field is invalid` (no source-
3552        // citing diagnostic). The gate moves it to caixa-build time.
3553        let s = SupervisorSpec {
3554            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
3555            ..SupervisorSpec::default()
3556        };
3557        let err = s.validate().unwrap_err();
3558        assert!(
3559            matches!(
3560                err,
3561                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3562                    if caixa == "my_worker" && reason.contains('_')
3563            ),
3564            "got {err:?}"
3565        );
3566    }
3567
3568    #[test]
3569    fn validate_rejects_child_caixa_with_dot() {
3570        // A `:children :caixa` entry is a single DNS-1123 label, not a
3571        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
3572        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
3573        // (3f9d7a0) on the peer name axis.
3574        let s = SupervisorSpec {
3575            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
3576            ..SupervisorSpec::default()
3577        };
3578        let err = s.validate().unwrap_err();
3579        assert!(
3580            matches!(
3581                err,
3582                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3583                    if caixa == "team.worker" && reason.contains('.')
3584            ),
3585            "got {err:?}"
3586        );
3587    }
3588
3589    #[test]
3590    fn validate_rejects_child_caixa_with_leading_hyphen() {
3591        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
3592        // with an alphanumeric. The K8s apiserver rejects `-worker`
3593        // outright; the renderer would emit a `metadata.name: "-worker"`
3594        // that fails admission far from the source caixa.lisp.
3595        let s = SupervisorSpec {
3596            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
3597            ..SupervisorSpec::default()
3598        };
3599        let err = s.validate().unwrap_err();
3600        assert!(
3601            matches!(
3602                err,
3603                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3604                    if caixa == "-worker" && reason.contains("start and end")
3605            ),
3606            "got {err:?}"
3607        );
3608    }
3609
3610    #[test]
3611    fn validate_rejects_child_caixa_with_trailing_hyphen() {
3612        // The symmetric arm of the boundary rule. Pin separately so
3613        // both ends of the label are covered against a future relaxation
3614        // that only checks one boundary.
3615        let s = SupervisorSpec {
3616            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
3617            ..SupervisorSpec::default()
3618        };
3619        let err = s.validate().unwrap_err();
3620        assert!(
3621            matches!(
3622                err,
3623                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3624                    if caixa == "worker-"
3625            ),
3626            "got {err:?}"
3627        );
3628    }
3629
3630    #[test]
3631    fn validate_rejects_child_caixa_with_unicode() {
3632        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
3633        // (`xn--…`) by the author before it reaches K8s. The byte-by-
3634        // byte ASCII validity check rejects multi-byte UTF-8 sequences
3635        // by the first byte that fails the `[a-z0-9-]` predicate.
3636        let s = SupervisorSpec {
3637            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
3638            ..SupervisorSpec::default()
3639        };
3640        let err = s.validate().unwrap_err();
3641        assert!(
3642            matches!(
3643                err,
3644                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3645                    if caixa == "café"
3646            ),
3647            "got {err:?}"
3648        );
3649    }
3650
3651    #[test]
3652    fn validate_rejects_child_caixa_with_whitespace() {
3653        // Whitespace is the canonical "I pasted from a sketch / doc"
3654        // footgun. The apiserver rejects every `metadata.name` value
3655        // carrying whitespace; pin the gate fires at the right boundary.
3656        let s = SupervisorSpec {
3657            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
3658            ..SupervisorSpec::default()
3659        };
3660        let err = s.validate().unwrap_err();
3661        assert!(
3662            matches!(
3663                err,
3664                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3665                    if caixa == "my worker"
3666            ),
3667            "got {err:?}"
3668        );
3669    }
3670
3671    #[test]
3672    fn validate_rejects_child_caixa_too_long() {
3673        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
3674        // 63 bytes; the K8s apiserver rejects every `metadata.name`
3675        // axis over the limit at admission time. The diagnostic names
3676        // both the cap and the actual length so the author can shorten
3677        // in one edit, mirroring `rejects_membro_caixa_too_long`
3678        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
3679        let too_long = "a".repeat(64);
3680        let s = SupervisorSpec {
3681            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
3682            ..SupervisorSpec::default()
3683        };
3684        let err = s.validate().unwrap_err();
3685        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3686            panic!("expected ChildCaixaInvalid, got other variant");
3687        };
3688        assert_eq!(caixa, too_long);
3689        assert!(
3690            reason.contains("63"),
3691            "diagnostic must name the 63-byte cap (got: {reason:?})"
3692        );
3693        assert!(
3694            reason.contains("64"),
3695            "diagnostic must name the actual length (got: {reason:?})"
3696        );
3697    }
3698
3699    #[test]
3700    fn child_caixa_max_length_validates() {
3701        // The 63-byte boundary control pin — exactly-at-the-cap is
3702        // accepted, mirroring `membro_caixa_max_length_validates`
3703        // (3f9d7a0) and `placement_cluster_max_length_validates`
3704        // (6cbb900). Pinned separately so a future off-by-one tightening
3705        // surfaces here.
3706        let max_label = "a".repeat(63);
3707        let s = SupervisorSpec {
3708            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
3709            ..SupervisorSpec::default()
3710        };
3711        s.validate().unwrap();
3712    }
3713
3714    #[test]
3715    fn validate_accepts_canonical_child_caixa_forms() {
3716        // The realistic shapes a supervised child's `:caixa` carries —
3717        // single-word `worker`, version-suffixed `cache-v2`, single-char
3718        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
3719        // `payment-retry`, all-digit `0`. Pin every leg so a future
3720        // tightening (e.g. requiring a leading lowercase letter) surfaces
3721        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
3722        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
3723        // (6cbb900).
3724        for form in [
3725            "worker",
3726            "cache-v2",
3727            "a",
3728            "db",
3729            "2-pool",
3730            "payment-retry",
3731            "0",
3732        ] {
3733            let s = SupervisorSpec {
3734                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
3735                ..SupervisorSpec::default()
3736            };
3737            s.validate()
3738                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3739        }
3740    }
3741
3742    #[test]
3743    fn child_caixa_empty_takes_precedence_over_invalid() {
3744        // Order pin: the existing `EmptyChildName` diagnostic (which
3745        // doesn't try to parse the DNS-1123 shape) fires before the new
3746        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
3747        // its narrower error message — `is_dns_1123_label` would reject
3748        // the empty string too (boundary check on the first byte), but
3749        // the empty-string arm is the more self-locating diagnostic for
3750        // the author. Same ordering discipline as
3751        // `membro_caixa_empty_takes_precedence_over_invalid` in
3752        // aplicacao.rs.
3753        let s = SupervisorSpec {
3754            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3755            ..SupervisorSpec::default()
3756        };
3757        let err = s.validate().unwrap_err();
3758        assert_eq!(err, SupervisorError::EmptyChildName);
3759    }
3760
3761    #[test]
3762    fn child_caixa_invalid_fires_before_versao_check() {
3763        // Order pin: the per-axis shape gate runs inline before the
3764        // per-entry versao check, so a malformed `:caixa` on an entry
3765        // whose `:versao` would also fail surfaces the more self-
3766        // locating name-axis diagnostic first. Parallel to
3767        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
3768        // and `placement_cluster_invalid_fires_before_duplicate_check`
3769        // (6cbb900).
3770        let s = SupervisorSpec {
3771            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
3772            ..SupervisorSpec::default()
3773        };
3774        let err = s.validate().unwrap_err();
3775        assert!(
3776            matches!(
3777                err,
3778                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
3779            ),
3780            "got {err:?}"
3781        );
3782    }
3783
3784    #[test]
3785    fn child_caixa_invalid_fires_before_duplicate_check() {
3786        // Order pin: a malformed name on a non-duplicate entry surfaces
3787        // its own diagnostic, even when a later entry would otherwise
3788        // collapse onto an earlier name. The per-entry shape gate runs
3789        // inline before the duplicate-key HashSet insert, mirroring
3790        // `placement_cluster_invalid_fires_before_duplicate_check`
3791        // (6cbb900).
3792        let s = SupervisorSpec {
3793            children: vec![
3794                child("Worker", "^0.1", RestartPolicy::Permanent),
3795                child("cache", "^0.1", RestartPolicy::Transient),
3796                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3797            ],
3798            ..SupervisorSpec::default()
3799        };
3800        let err = s.validate().unwrap_err();
3801        assert!(
3802            matches!(
3803                err,
3804                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
3805            ),
3806            "got {err:?}"
3807        );
3808    }
3809
3810    #[test]
3811    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
3812        // The diagnostic-shape pin: the error names the offending
3813        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
3814        // the author can grep their caixa.lisp without re-running the
3815        // build. Mirrors the diagnostic-shape sweep on every prior
3816        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
3817        let s = SupervisorSpec {
3818            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
3819            ..SupervisorSpec::default()
3820        };
3821        let err = s.validate().unwrap_err();
3822        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3823            panic!("expected ChildCaixaInvalid, got other variant");
3824        };
3825        assert_eq!(caixa, "My_Worker");
3826        assert!(
3827            !reason.is_empty(),
3828            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
3829        );
3830    }
3831
3832    // ── value-shape: zero restart_window + duplicate child names ──────────
3833
3834    #[test]
3835    fn validate_accepts_none_restart_window() {
3836        // Omitted `:restart-window` is the "never reset" sentinel —
3837        // valid by design. Mirrors :limits axes where None = unbounded.
3838        let s = SupervisorSpec {
3839            restart_window: None,
3840            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3841            ..SupervisorSpec::default()
3842        };
3843        s.validate().unwrap();
3844    }
3845
3846    #[test]
3847    fn validate_rejects_zero_restart_window() {
3848        // Same "0 means the opposite of what you think" footgun closed
3849        // for :politicas :timeout (Envoy treats 0s as infinite) and
3850        // :limits :wall-clock (wasmtime traps before the call starts).
3851        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
3852        let s = SupervisorSpec {
3853            restart_window: Some(Duration::ZERO),
3854            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3855            ..SupervisorSpec::default()
3856        };
3857        assert_eq!(
3858            s.validate().unwrap_err(),
3859            SupervisorError::RestartWindowZero
3860        );
3861    }
3862
3863    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
3864    //
3865    // The fourth (and last) typed-`Duration` axis in caixa-core to get
3866    // the integer-millisecond canonical-form gate — peer with
3867    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
3868    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
3869    // path is already gated at the shared codec layer (see
3870    // `restart_window_serde_rejects_fractional_seconds`); this arm
3871    // closes the programmatic-struct-literal path the codec gate can't
3872    // see.
3873
3874    #[test]
3875    fn validate_rejects_sub_millisecond_restart_window() {
3876        // The fail-before-pass-after pin: a programmatic
3877        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
3878        // `validate` on every pre-gate codebase, then truncated to
3879        // `as_millis() == 1` on first serialize — the shared codec
3880        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
3881        // 1_000_000 ns, the typed `restart_window` no longer matches
3882        // its rendered form.
3883        let s = SupervisorSpec {
3884            restart_window: Some(Duration::from_micros(1500)),
3885            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3886            ..SupervisorSpec::default()
3887        };
3888        match s.validate().unwrap_err() {
3889            SupervisorError::RestartWindowNotCanonical { window } => {
3890                assert_eq!(window, Duration::from_micros(1500));
3891            }
3892            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
3893        }
3894    }
3895
3896    #[test]
3897    fn validate_rejects_one_nanosecond_restart_window() {
3898        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
3899        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
3900        // so the shared codec emits the literal `"0s"` — the next
3901        // serde round-trip would parse back to `Duration::ZERO`, which
3902        // the `RestartWindowZero` arm then rejects on re-validate. The
3903        // canonical-form gate at this layer surfaces a self-locating
3904        // diagnostic naming the offending Duration verbatim rather
3905        // than a downstream `RestartWindowZero` whose remediation
3906        // points at omitting the slot.
3907        let s = SupervisorSpec {
3908            restart_window: Some(Duration::from_nanos(1)),
3909            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3910            ..SupervisorSpec::default()
3911        };
3912        match s.validate().unwrap_err() {
3913            SupervisorError::RestartWindowNotCanonical { window } => {
3914                assert_eq!(window, Duration::from_nanos(1));
3915            }
3916            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
3917        }
3918    }
3919
3920    #[test]
3921    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
3922        // The 1-ns-past-1ms boundary case: a `Duration` carrying
3923        // 1_000_001 ns is structurally past the integer-ms granularity
3924        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
3925        // trip would truncate to `1ms` and the consumer would observe
3926        // a 1-ns drift on every emit. Same boundary the peer
3927        // `validate_rejects_nanosecond_past_canonical_boundary` test
3928        // in limits.rs pins for the `:limits :wall-clock` axis.
3929        let w = Duration::from_nanos(1_000_001);
3930        let s = SupervisorSpec {
3931            restart_window: Some(w),
3932            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3933            ..SupervisorSpec::default()
3934        };
3935        assert_eq!(
3936            s.validate().unwrap_err(),
3937            SupervisorError::RestartWindowNotCanonical { window: w }
3938        );
3939    }
3940
3941    #[test]
3942    fn validate_accepts_integer_millisecond_restart_window_values() {
3943        // The positive-control sweep: every `Duration` the shared
3944        // codec can round-trip losslessly — the canonical
3945        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
3946        // pair emits and accepts — passes `validate` without
3947        // surfacing the new canonical-form arm. Mirrors
3948        // `validate_accepts_integer_millisecond_wall_clock_values` on
3949        // the sibling `:limits :wall-clock` axis.
3950        for w in [
3951            Duration::from_millis(1),
3952            Duration::from_millis(500),
3953            Duration::from_millis(1500),
3954            Duration::from_secs(1),
3955            Duration::from_secs(30),
3956            Duration::from_secs(60),
3957            Duration::from_secs(120),
3958            Duration::from_secs(3600),
3959        ] {
3960            let s = SupervisorSpec {
3961                restart_window: Some(w),
3962                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3963                ..SupervisorSpec::default()
3964            };
3965            s.validate()
3966                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
3967        }
3968    }
3969
3970    #[test]
3971    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
3972        // Cross-arm ordering pin: `Duration::ZERO` has
3973        // `subsec_nanos() == 0` and would otherwise pass the
3974        // canonical-form arm — the zero-floor arm must fire first so
3975        // the more self-locating `RestartWindowZero` diagnostic (with
3976        // its omit-axis remediation directly named) leads. Same
3977        // posture every peer zero-then-shape gate uses
3978        // (`WallClockZero` → `WallClockNotCanonical`,
3979        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
3980        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
3981        let s = SupervisorSpec {
3982            restart_window: Some(Duration::ZERO),
3983            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3984            ..SupervisorSpec::default()
3985        };
3986        assert_eq!(
3987            s.validate().unwrap_err(),
3988            SupervisorError::RestartWindowZero
3989        );
3990    }
3991
3992    #[test]
3993    fn restart_window_canonical_diagnostic_carries_offending_duration() {
3994        // Diagnostic-shape pin: the canonical-form arm names the
3995        // offending `Duration` verbatim so the author's grep lands on
3996        // the field's value, not a generic "duration not canonical"
3997        // message. Same shape every other typed-canonical-form arm
3998        // on this surface carries (`WallClockNotCanonical` carries
3999        // the offending `Duration` verbatim,
4000        // `PolicyTimeoutNotCanonical` carries the offending
4001        // `Duration` verbatim).
4002        let w = Duration::from_micros(500);
4003        let s = SupervisorSpec {
4004            restart_window: Some(w),
4005            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4006            ..SupervisorSpec::default()
4007        };
4008        let err = s.validate().unwrap_err();
4009        let msg = err.to_string();
4010        assert!(
4011            msg.contains("500"),
4012            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4013        );
4014        assert!(
4015            msg.contains("sub-millisecond"),
4016            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4017        );
4018    }
4019
4020    #[test]
4021    fn restart_window_validated_value_round_trips_through_codec() {
4022        // The structural property the canonical-ms gate enforces:
4023        // every `SupervisorSpec::restart_window` past
4024        // `SupervisorSpec::validate` round-trips losslessly through
4025        // the shared duration codec (serialize → string →
4026        // deserialize → equal value). Pin this end-to-end so a future
4027        // change to either side (the validate gate's accepted
4028        // granularity, the codec's parse/render unit set) that breaks
4029        // the alignment surfaces here. Peer of
4030        // `wall_clock_validated_value_round_trips_through_codec` on
4031        // the sibling `:limits :wall-clock` axis.
4032        for w in [
4033            Duration::from_millis(1),
4034            Duration::from_millis(1500),
4035            Duration::from_secs(30),
4036            Duration::from_secs(3600),
4037        ] {
4038            let s = SupervisorSpec {
4039                restart_window: Some(w),
4040                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4041                ..SupervisorSpec::default()
4042            };
4043            s.validate().unwrap();
4044            let json = serde_json::to_string(&s).unwrap();
4045            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4046            assert_eq!(back.restart_window, Some(w));
4047        }
4048    }
4049
4050    // ── value-shape: upper cap on :restart-window ─────────────────────────
4051    //
4052    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4053    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4054    // `:politicas :timeout` (2e8ee7e), and `:politicas
4055    // :circuit-breaker :window` (379a814). Brackets the typed
4056    // `:restart-window` axis structurally: every validated value lies
4057    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4058    // granularity, closing the
4059    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4060    // zero-floor-and-canonical-form-only checks left open.
4061
4062    #[test]
4063    fn validate_rejects_restart_window_above_cap() {
4064        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4065        // structurally one canonical-tick past the
4066        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4067        // integer-millisecond magnitude the canonical-form arm above
4068        // accepts cleanly, that the shared duration codec round-trips
4069        // losslessly as `"3601s"`, and that silently passed validate on
4070        // every pre-gate codebase because the typed slot's only checks
4071        // were the zero-floor and canonical-form arms. The runtime
4072        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4073        // Period reconciler, the future wasm-operator's per-supervisor
4074        // restart-intensity counter) reaches for a `Duration` so long
4075        // no realistic restart-recovery pattern resets the counter,
4076        // far from the source caixa.lisp.
4077        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4078        let s = SupervisorSpec {
4079            restart_window: Some(w),
4080            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4081            ..SupervisorSpec::default()
4082        };
4083        assert_eq!(
4084            s.validate().unwrap_err(),
4085            SupervisorError::RestartWindowExceedsCap { window: w }
4086        );
4087    }
4088
4089    #[test]
4090    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4091        // Boundary case: exactly 1ms past the cap (the granularity the
4092        // canonical-form gate enforces). Catches a future "strictly
4093        // less than" half-measure and pins the diagnostic to name the
4094        // offending `Duration` verbatim. Peer of
4095        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4096        // `rejects_policy_timeout_one_millisecond_above_cap` /
4097        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4098        // on the sibling typed-`Duration` axes' top edges.
4099        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4100        let s = SupervisorSpec {
4101            restart_window: Some(w),
4102            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4103            ..SupervisorSpec::default()
4104        };
4105        assert_eq!(
4106            s.validate().unwrap_err(),
4107            SupervisorError::RestartWindowExceedsCap { window: w }
4108        );
4109    }
4110
4111    #[test]
4112    fn validate_rejects_restart_window_far_above_cap() {
4113        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4114        // `(:restart-window "7d")`, or any "I want a lifetime counter
4115        // but wrote a `<integer>h` magnitude anyway" typo — values the
4116        // canonical-form arm accepts as integer-millisecond magnitudes,
4117        // the codec round-trips losslessly through serde, but the
4118        // operator's `MaxIntensity / Period` reconciler cannot honor
4119        // as a meaningful rolling window. Until this gate landed
4120        // validate accepted them. Pin the common above-cap values (24h,
4121        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4122        // surfaces here.
4123        for w in [
4124            Duration::from_secs(86_400),    // 24h
4125            Duration::from_secs(604_800),   // 7d
4126            Duration::from_secs(1_000_000), // ~11.5 days
4127        ] {
4128            let s = SupervisorSpec {
4129                restart_window: Some(w),
4130                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4131                ..SupervisorSpec::default()
4132            };
4133            assert_eq!(
4134                s.validate().unwrap_err(),
4135                SupervisorError::RestartWindowExceedsCap { window: w }
4136            );
4137        }
4138    }
4139
4140    #[test]
4141    fn validate_accepts_restart_window_at_cap() {
4142        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4143        // (1h) — must validate. The cap is inclusive on the top edge,
4144        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4145        // [`crate::POLICY_TIMEOUT_MAX`] /
4146        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4147        // capped axes. Pin the boundary explicitly so a future
4148        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4149        // instead of `>`) surfaces here as a test failure rather than a
4150        // silent contract narrowing.
4151        let s = SupervisorSpec {
4152            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4153            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4154            ..SupervisorSpec::default()
4155        };
4156        s.validate()
4157            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4158    }
4159
4160    #[test]
4161    fn validate_accepts_restart_window_typical_values() {
4162        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4163        // per-supervisor production-playbook band positive-control
4164        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4165        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4166        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4167        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4168        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4169        // default recommend (5s..=300s) must pass, plus a sweep
4170        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4171        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4172        // on the sibling `:limits :wall-clock` axis.
4173        for w in [
4174            Duration::from_millis(1),
4175            Duration::from_millis(500),
4176            Duration::from_secs(1),
4177            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4178            Duration::from_secs(10), // Riak Core lower
4179            Duration::from_secs(30),
4180            Duration::from_secs(60),  // Learn You Some Erlang default
4181            Duration::from_secs(120), // OTP supervisor MaxT typical
4182            Duration::from_secs(300), // Riak Core upper
4183            Duration::from_secs(900), // 15m
4184            Duration::from_secs(1800),
4185            Duration::from_secs(3600), // exactly 1h, the cap
4186        ] {
4187            let s = SupervisorSpec {
4188                restart_window: Some(w),
4189                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4190                ..SupervisorSpec::default()
4191            };
4192            s.validate()
4193                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4194        }
4195    }
4196
4197    #[test]
4198    fn restart_window_zero_takes_precedence_over_cap() {
4199        // The cross-arm ordering pin: `Duration::ZERO` is structurally
4200        // outside both `>= 1ms` (zero-floor) and `<=
4201        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4202        // diagnostic is the more self-locating one (it directly names
4203        // the omit-axis remediation), so the validate gate must fire
4204        // on zero first. Same shape every other zero-then-cap ordering
4205        // on this surface uses (`WallClockZero` then
4206        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4207        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4208        // `PolicyBreakerWindowExceedsCap`).
4209        let s = SupervisorSpec {
4210            restart_window: Some(Duration::ZERO),
4211            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4212            ..SupervisorSpec::default()
4213        };
4214        assert_eq!(
4215            s.validate().unwrap_err(),
4216            SupervisorError::RestartWindowZero,
4217            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4218        );
4219    }
4220
4221    #[test]
4222    fn restart_window_canonical_takes_precedence_over_cap() {
4223        // The cross-arm ordering pin: a `Duration` that is *both*
4224        // sub-millisecond (non-canonical-form) and structurally above
4225        // the cap surfaces the canonical-form diagnostic first,
4226        // because the round-trip-shape break is the more fundamental
4227        // issue (the value can't even round-trip through the codec,
4228        // so the cap diagnostic naming `1ms..=1h` would be misleading
4229        // — there's no integer-ms form of the offending value). Pin
4230        // the order so a future refactor that reorders the arms
4231        // surfaces here as a test failure rather than a silent
4232        // diagnostic regression. Peer of
4233        // `wall_clock_canonical_takes_precedence_over_cap` /
4234        // `policy_timeout_canonical_takes_precedence_over_cap`.
4235        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4236        let s = SupervisorSpec {
4237            restart_window: Some(w),
4238            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4239            ..SupervisorSpec::default()
4240        };
4241        assert_eq!(
4242            s.validate().unwrap_err(),
4243            SupervisorError::RestartWindowNotCanonical { window: w },
4244            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4245        );
4246    }
4247
4248    #[test]
4249    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4250        // The cross-arm ordering pin between the `:max-restarts` cap
4251        // and the sibling `:restart-window` cap. A supervisor carrying
4252        // both an over-cap `max_restarts` AND an over-cap window must
4253        // surface the `MaxRestartsExceedsCap` diagnostic first — the
4254        // cap arm is wired immediately after the zero-restart arm and
4255        // strictly before every window-axis arm (zero / canonical /
4256        // cap), so the offending value the diagnostic names matches
4257        // the order the author would discover the gates by reading
4258        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4259        // order so a future refactor that reorders the arms surfaces
4260        // here as a test failure rather than a silent diagnostic
4261        // regression. Peer of
4262        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4263        // on the sibling zero / canonical window arms.
4264        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4265        let s = SupervisorSpec {
4266            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4267            restart_window: Some(w),
4268            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4269            ..SupervisorSpec::default()
4270        };
4271        assert_eq!(
4272            s.validate().unwrap_err(),
4273            SupervisorError::MaxRestartsExceedsCap {
4274                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4275            },
4276            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4277        );
4278    }
4279
4280    #[test]
4281    fn restart_window_cap_diagnostic_carries_offending_value() {
4282        // The diagnostic-shape pin: the offending `Duration` is
4283        // carried verbatim into the
4284        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4285        // surfaced error message names the value the author wrote,
4286        // not just the cap. Same self-locating diagnostic shape every
4287        // other typed-cap arm on this surface carries
4288        // (`WallClockExceedsCap` carries the offending `Duration`
4289        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4290        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4291        // the offending `Duration` verbatim).
4292        let w = Duration::from_secs(7200); // 2h
4293        let s = SupervisorSpec {
4294            restart_window: Some(w),
4295            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4296            ..SupervisorSpec::default()
4297        };
4298        let err = s.validate().unwrap_err();
4299        assert!(
4300            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4301            "got {err:?}"
4302        );
4303        let msg = err.to_string();
4304        assert!(
4305            msg.contains("7200"),
4306            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4307        );
4308    }
4309
4310    #[test]
4311    fn supervisor_restart_window_cap_pins_canonical_value() {
4312        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4313        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4314        // shared duration codec emits as a clean canonical string
4315        // (`"<n>h"`). Pinning the literal value here surfaces a future
4316        // drift (a relaxation to 24h, a tightening to 5m) as a
4317        // deliberate test edit, not a silent contract narrowing.
4318        //
4319        // The four typed-`Duration` caps on the validation surface
4320        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4321        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4322        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4323        // single uniform top edge at the codec's largest emitted unit
4324        // — a structural-property invariant the equality assertions
4325        // here enshrine, so a future drift on any of the four
4326        // surfaces as a deliberate test edit. Same shape every other
4327        // typed-cap value pin uses
4328        // (`wall_clock_cap_pins_canonical_value`,
4329        // `policy_timeout_cap_pins_canonical_value`,
4330        // `circuit_breaker_window_cap_pins_canonical_value`).
4331        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4332        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4333        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4334        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4335        assert_eq!(
4336            SUPERVISOR_RESTART_WINDOW_MAX,
4337            crate::POLICY_BREAKER_WINDOW_MAX
4338        );
4339    }
4340
4341    #[test]
4342    fn restart_window_cap_value_round_trips_through_codec() {
4343        // The codec round-trip property the cap arm preserves: the
4344        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4345        // through the shared duration codec — every value at the cap
4346        // serializes to the canonical `"1h"` form and parses back
4347        // identically. Pin the round-trip so a future change to the
4348        // codec's unit set or to the cap's magnitude that breaks the
4349        // round-trip property surfaces here. Peer of
4350        // `wall_clock_cap_value_round_trips_through_codec` on the
4351        // sibling `:limits :wall-clock` axis.
4352        let s = SupervisorSpec {
4353            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4354            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4355            ..SupervisorSpec::default()
4356        };
4357        s.validate().unwrap();
4358        let json = serde_json::to_string(&s).unwrap();
4359        assert!(
4360            json.contains("\"1h\""),
4361            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
4362        );
4363        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4364        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
4365    }
4366
4367    #[test]
4368    fn validate_rejects_duplicate_child_caixa() {
4369        // Two children with the same :caixa render to two ComputeUnits
4370        // with the same name in the cluster's HelmRelease values —
4371        // one silently overwrites the other. Erlang/OTP's child_spec.id
4372        // is required-unique per supervisor; same set-not-multiset
4373        // discipline applied here as for :membros / :placement
4374        // :clusters / :entrada :paths.
4375        let s = SupervisorSpec {
4376            children: vec![
4377                child("worker", "^0.1", RestartPolicy::Permanent),
4378                child("cache", "^0.1", RestartPolicy::Transient),
4379                child("worker", "^0.2", RestartPolicy::Permanent),
4380            ],
4381            ..SupervisorSpec::default()
4382        };
4383        let err = s.validate().unwrap_err();
4384        assert!(
4385            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
4386            "got {err:?}"
4387        );
4388    }
4389
4390    #[test]
4391    fn validate_duplicate_child_diagnostic_names_first_collision() {
4392        // Iteration walks the :children list in declaration order —
4393        // the diagnostic names the first repeat, deterministically,
4394        // even when multiple names duplicate.
4395        let s = SupervisorSpec {
4396            children: vec![
4397                child("a", "^0.1", RestartPolicy::Permanent),
4398                child("b", "^0.1", RestartPolicy::Permanent),
4399                child("a", "^0.1", RestartPolicy::Permanent),
4400                child("b", "^0.1", RestartPolicy::Permanent),
4401            ],
4402            ..SupervisorSpec::default()
4403        };
4404        let err = s.validate().unwrap_err();
4405        assert!(
4406            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
4407            "got {err:?}"
4408        );
4409    }
4410
4411    // ── self-supervision cross-slot gate ──────────────────────────
4412
4413    #[test]
4414    fn validate_no_self_supervision_rejects_self_referential_child() {
4415        // A supervisor whose `:children` lists its own `:nome` is a
4416        // one-node reconciliation cycle — rejected, naming the parent.
4417        let children = vec![
4418            child("worker", "^0.1", RestartPolicy::Permanent),
4419            child("orquestra", "^0.1", RestartPolicy::Permanent),
4420        ];
4421        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
4422        assert!(
4423            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
4424            "got {err:?}"
4425        );
4426    }
4427
4428    #[test]
4429    fn validate_no_self_supervision_accepts_distinct_children() {
4430        // Positive control: distinct child names (including a child that
4431        // is itself a supervisor — nested trees are valid OTP) pass.
4432        let children = vec![
4433            child("worker", "^0.1", RestartPolicy::Permanent),
4434            child("sub-tree", "^0.1", RestartPolicy::Permanent),
4435        ];
4436        validate_no_self_supervision(&children, "orquestra").unwrap();
4437    }
4438
4439    #[test]
4440    fn validate_no_self_supervision_empty_children_is_ok() {
4441        // SimpleOneForOne / no-static-children supervisors have nothing
4442        // to self-reference — the gate is vacuously satisfied.
4443        validate_no_self_supervision(&[], "orquestra").unwrap();
4444    }
4445
4446    #[test]
4447    fn validate_simple_one_for_one_skips_uniqueness_check() {
4448        // SimpleOneForOne supervisors carry no static children — the
4449        // duplicate-child loop never runs. A zero-window declaration
4450        // on a SimpleOneForOne supervisor still trips the window check
4451        // (window applies to dynamic children too).
4452        let s = SupervisorSpec {
4453            estrategia: RestartStrategy::SimpleOneForOne,
4454            restart_window: None,
4455            children: vec![],
4456            ..SupervisorSpec::default()
4457        };
4458        s.validate().unwrap();
4459        let s_zero = SupervisorSpec {
4460            estrategia: RestartStrategy::SimpleOneForOne,
4461            restart_window: Some(Duration::ZERO),
4462            children: vec![],
4463            ..SupervisorSpec::default()
4464        };
4465        assert_eq!(
4466            s_zero.validate().unwrap_err(),
4467            SupervisorError::RestartWindowZero
4468        );
4469    }
4470
4471    #[test]
4472    fn validate_zero_window_runs_after_max_restarts_check() {
4473        // Pin the order: max_restarts == 0 fires before
4474        // restart_window == 0s, so an author with both wrong sees the
4475        // counter-axis diagnostic first (matches the order in the
4476        // struct and in the doc comment).
4477        let s = SupervisorSpec {
4478            max_restarts: 0,
4479            restart_window: Some(Duration::ZERO),
4480            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4481            ..SupervisorSpec::default()
4482        };
4483        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4484    }
4485
4486    #[test]
4487    fn round_trip_all_strategies() {
4488        for &strat in RestartStrategy::ALL {
4489            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
4490            // shape partition through the [`gen_platform::IsVariant`]
4491            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
4492            // predicate rather than the raw
4493            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
4494            // open-coded pattern-match — same closed-set-typed-enum
4495            // arm-discriminator dispatch discipline the sibling
4496            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
4497            // (915a934) extended onto its two paired positive / negated
4498            // `matches!` filter sites, and the sibling
4499            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
4500            // predicate convergence (766ec63) extended onto the M3 mesh-
4501            // slot per-`:placement` distribution-strategy `matches!`
4502            // discriminator axis. See the sibling
4503            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
4504            // fixture and the peer `manifest::tests::
4505            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
4506            // fixture — all three sites (the last unlifted
4507            // `matches!`-based arm-discriminator axis on the OTP-shape
4508            // supervisor sibling-restart-strategy closed-set typed enum,
4509            // acknowledged in 915a934's Prior-commits footnote as the
4510            // outstanding follow-up) now consult one typed dispatch on
4511            // the substrate primitive.
4512            let s = SupervisorSpec {
4513                estrategia: strat,
4514                children: if strat.is_simple_one_for_one() {
4515                    vec![]
4516                } else {
4517                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
4518                },
4519                ..SupervisorSpec::default()
4520            };
4521            let json = serde_json::to_string(&s).unwrap();
4522            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4523            assert_eq!(s, back);
4524        }
4525    }
4526
4527    #[test]
4528    fn round_trip_all_restart_policies() {
4529        for policy in [
4530            RestartPolicy::Permanent,
4531            RestartPolicy::Temporary,
4532            RestartPolicy::Transient,
4533        ] {
4534            let c = child("w", "^0.1", policy);
4535            let json = serde_json::to_string(&c).unwrap();
4536            let back: ChildSpec = serde_json::from_str(&json).unwrap();
4537            assert_eq!(c, back);
4538        }
4539    }
4540
4541    #[test]
4542    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
4543        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
4544        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
4545        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
4546        // is the only variant that satisfies `.is_simple_one_for_one()`;
4547        // every static-children-bearing arm (`OneForOne` / `OneForAll`
4548        // / `RestForOne`) returns `false`. This pin makes the partition
4549        // invariant load-bearing at caixa-core test time so a future
4550        // derive regression (a hole that returns `false` for
4551        // `SimpleOneForOne` too, or a byte-collision that flips a second
4552        // variant to `true`) trips here rather than laundering the arm
4553        // at the three test-fixture builder sites (a hole flips the
4554        // `SimpleOneForOne` fixture to carry a non-empty children list
4555        // and the subsequent `SupervisorSpec::validate` would refuse the
4556        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
4557        // a collision flips a peer strategy's fixture to carry an empty
4558        // children list and the subsequent `validate` would refuse with
4559        // [`SupervisorError::NoChildren`] — either way, the pin fires
4560        // here, at the derive site, rather than at the fixture-refusal
4561        // site far away). Peer of the sibling
4562        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
4563        // (915a934) pin on the M2 OTP-appup axis and the sibling
4564        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
4565        // pin on the M0 `:kind` axis.
4566        let cases: &[(RestartStrategy, bool)] = &[
4567            (RestartStrategy::OneForOne, false),
4568            (RestartStrategy::OneForAll, false),
4569            (RestartStrategy::RestForOne, false),
4570            (RestartStrategy::SimpleOneForOne, true),
4571        ];
4572        for (variant, expected) in cases {
4573            assert_eq!(
4574                variant.is_simple_one_for_one(),
4575                *expected,
4576                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
4577                 return {expected} (partition invariant on the \
4578                 IsVariant-derived arm-discriminator predicate — every \
4579                 test-fixture site that partitions the `:children` slot \
4580                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
4581                 off this typed dispatch, so a derive regression must \
4582                 surface here rather than at the fixture-refusal site)"
4583            );
4584        }
4585    }
4586
4587    #[test]
4588    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
4589        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
4590        // fixture-shape partition against the pre-lift
4591        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
4592        // pattern-match every test-fixture builder site previously
4593        // coupled to inline. Asserts the two projections agree byte-for-
4594        // byte on every arm of the enum, so a future derive regression
4595        // that flipped either predicate's arm-set would surface here at
4596        // caixa-core test time rather than at the three fixture-builder
4597        // sites (`supervisor::tests::round_trip_all_strategies`,
4598        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
4599        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
4600        // far from the derive site. Same peer-shape byte-identity pin
4601        // every sibling `IsVariant`-derive-routed convergence carries on
4602        // the substrate's closed-set typed-enum surface (peer of
4603        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
4604        // on the M2 OTP-appup axis).
4605        for &strat in RestartStrategy::ALL {
4606            let via_predicate = strat.is_simple_one_for_one();
4607            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
4608            assert_eq!(
4609                via_predicate, via_matches,
4610                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
4611                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
4612                 the pre-lift open-coded pattern and the \
4613                 IsVariant-derived predicate are the same axis, \
4614                 one typed dispatch"
4615            );
4616        }
4617    }
4618
4619    #[test]
4620    fn duration_codec_round_trip_canonical_units() {
4621        // Note the canonical-form rule: durations serialize to the
4622        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
4623        // "60s" — but the round-trip preserves the underlying Duration.
4624        let cases = [
4625            ("30s", Duration::from_secs(30)),
4626            ("5m", Duration::from_secs(300)),
4627            ("1h", Duration::from_secs(3600)),
4628            ("500ms", Duration::from_millis(500)),
4629        ];
4630        for (lit, dur) in cases {
4631            let s = SupervisorSpec {
4632                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4633                restart_window: Some(dur),
4634                ..SupervisorSpec::default()
4635            };
4636            let json = serde_json::to_string(&s).unwrap();
4637            assert!(
4638                json.contains(&format!("\"{lit}\"")),
4639                "expected \"{lit}\" in {json}"
4640            );
4641            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4642            assert_eq!(back.restart_window, Some(dur));
4643        }
4644    }
4645
4646    #[test]
4647    fn duration_canonicalizes_to_largest_unit() {
4648        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
4649        // typed Duration still equals 60s on the way back.
4650        let s = SupervisorSpec {
4651            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4652            restart_window: Some(Duration::from_secs(60)),
4653            ..SupervisorSpec::default()
4654        };
4655        let json = serde_json::to_string(&s).unwrap();
4656        assert!(json.contains("\"1m\""), "{json}");
4657        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4658        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
4659    }
4660
4661    #[test]
4662    fn three_child_one_for_one_validates() {
4663        let s = SupervisorSpec {
4664            estrategia: RestartStrategy::OneForOne,
4665            max_restarts: 5,
4666            restart_window: Some(Duration::from_secs(60)),
4667            children: vec![
4668                child("worker", "^0.1", RestartPolicy::Permanent),
4669                child("cache", "^0.1", RestartPolicy::Transient),
4670                child("scratch", "^0.1", RestartPolicy::Temporary),
4671            ],
4672        };
4673        s.validate().unwrap();
4674    }
4675
4676    #[test]
4677    fn json_uses_pascal_case_for_strategy_and_policy() {
4678        // Variant names are PascalCase by default in serde, matching
4679        // tatara-lisp's enum convention (`:estrategia OneForOne`).
4680        let c = child("w", "^0.1", RestartPolicy::Permanent);
4681        let json = serde_json::to_string(&c).unwrap();
4682        assert!(json.contains("\"Permanent\""));
4683        assert!(!json.contains("\"permanent\""));
4684
4685        let s = SupervisorSpec {
4686            estrategia: RestartStrategy::OneForOne,
4687            children: vec![c],
4688            ..SupervisorSpec::default()
4689        };
4690        let json = serde_json::to_string(&s).unwrap();
4691        assert!(json.contains("\"estrategia\":\"OneForOne\""));
4692    }
4693
4694    // ── shared duration codec: integer-magnitude canonical-form gate ──
4695    //
4696    // The gate lifts the discipline `crate::limits::parse_duration`
4697    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
4698    // the shared codec backing the remaining three typed-duration
4699    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
4700    // `:politicas :circuit-breaker :window`. Every magnitude `render`
4701    // emits is a non-negative integer with no decimal point and no
4702    // leading sign, so the codec's accepted set must match for
4703    // serialize/deserialize to round-trip without canonical-form
4704    // drift.
4705
4706    #[test]
4707    fn parse_accepts_integer_canonical_units() {
4708        // Pin the happy-path: every canonical author shape `render`
4709        // ever emits parses to the same `Duration` value, so the
4710        // codec's accepted set is at least a superset of its emitted
4711        // set on the canonical-unit axis.
4712        for (lit, dur) in [
4713            ("30s", Duration::from_secs(30)),
4714            ("500ms", Duration::from_millis(500)),
4715            ("2m", Duration::from_secs(120)),
4716            ("1h", Duration::from_secs(3600)),
4717            ("0s", Duration::ZERO),
4718        ] {
4719            assert_eq!(
4720                duration_codec::parse(lit).unwrap(),
4721                dur,
4722                "parse({lit:?}) should be {dur:?}"
4723            );
4724        }
4725    }
4726
4727    #[test]
4728    fn parse_accepts_bare_integer_as_seconds() {
4729        // The `"s" | ""` arm: a bare integer with no unit is read as
4730        // seconds. Pin this so the unit-empty form keeps parsing (it
4731        // renders to `"<n>s"` on serialize — that's a unit-choice
4732        // drift the integer-magnitude gate does NOT close, matching
4733        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
4734        // the peer `:limits :memory` codec).
4735        assert_eq!(
4736            duration_codec::parse("30").unwrap(),
4737            Duration::from_secs(30)
4738        );
4739    }
4740
4741    #[test]
4742    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
4743        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
4744        // on first serialize — DRIFT. The integer-magnitude gate names
4745        // the offending `"1.5"` verbatim and points at the canonical
4746        // remediation `"1500ms"`.
4747        let err = duration_codec::parse("1.5s").unwrap_err();
4748        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
4749        assert!(
4750            err.contains("not a non-negative integer"),
4751            "missing canonical-form reason in {err:?}"
4752        );
4753        assert!(
4754            err.contains("\"1500ms\""),
4755            "missing canonical-form remediation in {err:?}"
4756        );
4757    }
4758
4759    #[test]
4760    fn parse_rejects_decimal_shaped_integer_seconds() {
4761        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
4762        // `1s` exactly, so the round-trip looks correct — but the
4763        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
4764        // decimal-shape-with-integer-value form so author intent is
4765        // never silently rewritten.
4766        let err = duration_codec::parse("1.0s").unwrap_err();
4767        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
4768        assert!(
4769            err.contains("not a non-negative integer"),
4770            "missing canonical-form reason in {err:?}"
4771        );
4772    }
4773
4774    #[test]
4775    fn parse_rejects_half_unit_minute() {
4776        // `"0.5m"` is the unit-fraction footgun — author writes a
4777        // human-readable half-minute, serde silently rewrites to
4778        // `"30s"` on next emit. The gate names the offending
4779        // magnitude `"0.5"` and points at the integer-in-smaller-unit
4780        // form.
4781        let err = duration_codec::parse("0.5m").unwrap_err();
4782        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
4783        assert!(
4784            err.contains("\"30s\""),
4785            "missing canonical-form remediation in {err:?}"
4786        );
4787    }
4788
4789    #[test]
4790    fn parse_rejects_leading_plus_sign() {
4791        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
4792        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
4793        // cleanly to 30s and round-tripped to `"30s"` on next emit
4794        // (DRIFT). The digit-only gate closes the leading-sign class
4795        // first; the diagnostic names `"+30"` verbatim.
4796        let err = duration_codec::parse("+30s").unwrap_err();
4797        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
4798        assert!(
4799            err.contains("not a non-negative integer"),
4800            "missing canonical-form reason in {err:?}"
4801        );
4802    }
4803
4804    #[test]
4805    fn parse_rejects_leading_minus_sign() {
4806        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
4807        // rejected with `"negative duration in \"-30s\""`. Under the
4808        // integer-magnitude gate the diagnostic is unified — `-30` is
4809        // non-digit-only, f64-numeric, and surfaces with the canonical-
4810        // form reason (no leading `+` / `-` sign) naming the offending
4811        // `"-30"` verbatim. Same diagnostic shape as every other
4812        // rejected non-integer magnitude.
4813        let err = duration_codec::parse("-30s").unwrap_err();
4814        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
4815        assert!(
4816            err.contains("not a non-negative integer"),
4817            "missing canonical-form reason in {err:?}"
4818        );
4819    }
4820
4821    #[test]
4822    fn parse_garbage_still_falls_through_to_bad_magnitude() {
4823        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
4824        // through to the narrower "bad duration magnitude" arm — the
4825        // canonical-form diagnostic is reserved for the parser-shape
4826        // footgun case, not the "not a number at all" case. Same
4827        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
4828        // the peer `:limits :memory` codec.
4829        let err = duration_codec::parse("--1s").unwrap_err();
4830        assert!(
4831            err.contains("bad duration magnitude"),
4832            "expected bad-magnitude wording in {err:?}"
4833        );
4834    }
4835
4836    #[test]
4837    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
4838        // The accepted set is now closed under `u64`-exact integer
4839        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
4840        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
4841        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
4842        // possible. Pin the integer-exact arms across the four unit
4843        // suffixes so a future refactor that reaches back for f64
4844        // (`from_secs_f64`, `mul_f64`) surfaces here.
4845        assert_eq!(
4846            duration_codec::parse("3600s").unwrap(),
4847            Duration::from_secs(3600)
4848        );
4849        assert_eq!(
4850            duration_codec::parse("60m").unwrap(),
4851            Duration::from_secs(3600)
4852        );
4853        assert_eq!(
4854            duration_codec::parse("1h").unwrap(),
4855            Duration::from_secs(3600)
4856        );
4857        assert_eq!(
4858            duration_codec::parse("999ms").unwrap(),
4859            Duration::from_millis(999)
4860        );
4861    }
4862
4863    #[test]
4864    fn restart_window_serde_rejects_fractional_seconds() {
4865        // The shared codec backs `SupervisorSpec::restart_window`
4866        // (`with = "duration_codec"`) — so the gate applies on serde
4867        // deserialize for the typed Supervisor slot. A
4868        // `{"restartWindow":"1.5s"}` payload that previously round-
4869        // tripped to a different canonical string on next serialize
4870        // is now refused at deserialize with the integer-magnitude
4871        // diagnostic.
4872        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4873            "restartWindow":"1.5s",
4874            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4875        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4876        let msg = err.to_string();
4877        assert!(
4878            msg.contains("not a non-negative integer"),
4879            "expected integer-magnitude diagnostic in {msg:?}"
4880        );
4881        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
4882    }
4883
4884    #[test]
4885    fn restart_window_serde_rejects_leading_plus() {
4886        // The `u64::from_str` leading-`+` permissiveness gap that
4887        // motivated the digit-only gate (the `f64`-side accepted
4888        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
4889        // is now closed on the shared codec — surfaces as a structured
4890        // diagnostic at the serde layer for every typed-duration slot.
4891        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4892            "restartWindow":"+30s",
4893            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4894        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4895        let msg = err.to_string();
4896        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
4897        assert!(
4898            msg.contains("not a non-negative integer"),
4899            "missing canonical-form reason in {msg:?}"
4900        );
4901    }
4902
4903    #[test]
4904    fn parse_rejects_leading_zero_magnitude() {
4905        // `"030s"` is digit-only, so the existing non-digit-only / sign
4906        // / fractional arm doesn't catch it — `u64::from_str("030")`
4907        // returns `Ok(30)`, so before this gate `"030s"` parsed to
4908        // `Duration::from_secs(30)` and round-tripped through `render`
4909        // to `"30s"` — a *different* canonical string on the next emit,
4910        // breaking the THEORY.md Part V render-determinism contract
4911        // exactly the way `"+30s"` did before the leading-`+` arm
4912        // landed. Peer with the `rate_limit_codec` leading-zero arm
4913        // (4f46830) on the same canonical-form-drift axis.
4914        let err = duration_codec::parse("030s").unwrap_err();
4915        assert!(
4916            err.contains("non-canonical leading zero"),
4917            "expected leading-zero diagnostic in {err:?}"
4918        );
4919        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
4920        assert!(
4921            err.contains("\"30s\""),
4922            "missing canonical-form remediation in {err:?}"
4923        );
4924        assert!(
4925            err.contains("THEORY.md"),
4926            "missing render-determinism citation in {err:?}"
4927        );
4928    }
4929
4930    #[test]
4931    fn parse_rejects_multi_digit_zero_magnitude() {
4932        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
4933        // digit-only, parse losslessly to `Duration::ZERO`, but render
4934        // back to `"0s"` (the single-byte canonical form) on the next
4935        // emit. The leading-zero arm refuses the drift class at the
4936        // codec layer; the semantic-zero gate downstream
4937        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
4938        // the single-byte canonical form `"0s"` separately on the
4939        // typed-validate layer.
4940        let err = duration_codec::parse("00s").unwrap_err();
4941        assert!(
4942            err.contains("non-canonical leading zero"),
4943            "expected leading-zero diagnostic in {err:?}"
4944        );
4945        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
4946    }
4947
4948    #[test]
4949    fn parse_rejects_leading_zero_per_hour_window() {
4950        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
4951        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
4952        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
4953        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
4954        // `h` / bare-integer-as-seconds) inherits the same gate.
4955        let err = duration_codec::parse("01h").unwrap_err();
4956        assert!(
4957            err.contains("non-canonical leading zero"),
4958            "expected leading-zero diagnostic in {err:?}"
4959        );
4960        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
4961    }
4962
4963    #[test]
4964    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
4965        // The `parse_accepts_bare_integer_as_seconds` happy-path
4966        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
4967        // multi-byte starts-with-`0`, parses losslessly to
4968        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
4969        // bare-integer surface accepts permissive unit-empty
4970        // shorthand but still must reject leading-zero padding.
4971        let err = duration_codec::parse("030").unwrap_err();
4972        assert!(
4973            err.contains("non-canonical leading zero"),
4974            "expected leading-zero diagnostic in {err:?}"
4975        );
4976        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
4977    }
4978
4979    #[test]
4980    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
4981        // The codec-layer / typed-validate-layer boundary: `"0s"` /
4982        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
4983        // each round-trips losslessly through `render`
4984        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
4985        // accepts them. The downstream semantic-zero gates
4986        // (`SupervisorError::ZeroRestartWindow`,
4987        // `AplicacaoError::PolicyTimeoutZero`,
4988        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
4989        // zero-magnitude authoring at the typed-validate layer above,
4990        // peer with the `rate_limit_codec` codec-layer / typed-
4991        // validate-layer partition for `"0/s"`.
4992        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
4993        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
4994        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
4995    }
4996
4997    #[test]
4998    fn parse_accepts_canonical_magnitude_with_leading_one() {
4999        // The complementary boundary: a future tightening cannot
5000        // drift into rejecting valid canonical magnitudes that
5001        // happen to start with `1` (or any digit `[1-9]`). Pin
5002        // every canonical-unit suffix so the leading-zero arm
5003        // remains strictly narrower than the digit-only arm.
5004        assert_eq!(
5005            duration_codec::parse("100ms").unwrap(),
5006            Duration::from_millis(100)
5007        );
5008        assert_eq!(
5009            duration_codec::parse("100s").unwrap(),
5010            Duration::from_secs(100)
5011        );
5012        assert_eq!(
5013            duration_codec::parse("10m").unwrap(),
5014            Duration::from_secs(600)
5015        );
5016        assert_eq!(
5017            duration_codec::parse("10h").unwrap(),
5018            Duration::from_secs(36_000)
5019        );
5020    }
5021
5022    #[test]
5023    fn restart_window_serde_rejects_leading_zero() {
5024        // The shared codec backs `SupervisorSpec::restart_window`
5025        // (`with = "duration_codec"`) — so the leading-zero arm
5026        // applies on serde deserialize for the typed Supervisor slot.
5027        // A `{"restartWindow":"030s"}` payload that previously round-
5028        // tripped to a different canonical string on next serialize
5029        // is now refused at deserialize with the leading-zero
5030        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5031        // / `restart_window_serde_rejects_fractional_seconds` on the
5032        // same canonical-form-drift axis.
5033        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5034            "restartWindow":"030s",
5035            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5036        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5037        let msg = err.to_string();
5038        assert!(
5039            msg.contains("non-canonical leading zero"),
5040            "expected leading-zero diagnostic in {msg:?}"
5041        );
5042        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5043    }
5044
5045    #[test]
5046    fn parse_rejects_leading_whitespace() {
5047        // `" 30s"` — the canonical paste-from-aligned-doc /
5048        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5049        // gate the top-level `s.trim()` at parse entry silently ate
5050        // the leading space and parsed the value to
5051        // `Duration::from_secs(30)`, which then round-tripped through
5052        // `render` to `"30s"` (a *different* canonical string on the
5053        // next emit) — the exact canonical-form-drift class the
5054        // leading-`+` / leading-zero arms already close, extended
5055        // to the whitespace-byte class. Peer with the sibling
5056        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5057        // the M3 `:politicas` axis.
5058        let err = duration_codec::parse(" 30s").unwrap_err();
5059        assert!(
5060            err.contains("contains whitespace byte"),
5061            "expected whitespace diagnostic in {err:?}"
5062        );
5063        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5064        assert!(
5065            err.contains("THEORY.md"),
5066            "missing render-determinism contract citation in {err:?}"
5067        );
5068    }
5069
5070    #[test]
5071    fn parse_rejects_trailing_whitespace() {
5072        // `"30s "` — the canonical shell-history / trailing-space
5073        // paste footgun. Before this gate the top-level `s.trim()`
5074        // silently ate the trailing space and parsed to
5075        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5076        // next emit — same canonical-form drift as the leading-space
5077        // sibling, closed on the same whitespace-byte arm.
5078        let err = duration_codec::parse("30s ").unwrap_err();
5079        assert!(
5080            err.contains("contains whitespace byte"),
5081            "expected whitespace diagnostic in {err:?}"
5082        );
5083        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5084    }
5085
5086    #[test]
5087    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5088        // `"30 s"` — the canonical typographically-spaced author
5089        // shape (the same idiom every prose reference to a duration
5090        // renders as, mistakenly retained when the value is pasted
5091        // into a codec-shaped slot). Before this gate the per-part
5092        // `num_part.trim()` / `unit.trim()` calls silently ate the
5093        // whitespace between the magnitude and the unit and parsed
5094        // the value to `Duration::from_secs(30)`, round-tripping to
5095        // `"30s"` — the codec's *internal* whitespace-tolerance
5096        // vector, orthogonal to the leading / trailing surface but
5097        // the same canonical-form-drift class. Pins the arm as
5098        // strictly stronger than the pre-existing top-level
5099        // `s.trim()` behavior: it fires on whitespace anywhere in
5100        // the value, not just at the string boundary.
5101        let err = duration_codec::parse("30 s").unwrap_err();
5102        assert!(
5103            err.contains("contains whitespace byte"),
5104            "expected whitespace diagnostic in {err:?}"
5105        );
5106        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5107    }
5108
5109    #[test]
5110    fn parse_rejects_tab_byte() {
5111        // `"\t30s"` — the canonical paste-from-indented-doc /
5112        // paste-from-YAML-block-scalar footgun where a tab byte leads
5113        // the magnitude. Pins that the gate covers tab (`0x09`) as
5114        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5115        // members and both would be silently swallowed by `s.trim()`
5116        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5117        // space alone to the full ASCII-whitespace set (space `0x20`,
5118        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5119        // the tab arm as a representative of the non-space members.
5120        let err = duration_codec::parse("\t30s").unwrap_err();
5121        assert!(
5122            err.contains("contains whitespace byte"),
5123            "expected whitespace diagnostic in {err:?}"
5124        );
5125        assert!(
5126            err.contains("0x09"),
5127            "missing offending tab byte in {err:?}"
5128        );
5129    }
5130
5131    #[test]
5132    fn restart_window_serde_rejects_whitespace() {
5133        // The shared codec backs `SupervisorSpec::restart_window`
5134        // (`with = "duration_codec"`) — so the whitespace arm
5135        // applies on serde deserialize for the typed Supervisor slot.
5136        // A `{"restartWindow":" 30s"}` payload that previously round-
5137        // tripped to a different canonical string on next serialize
5138        // is now refused at deserialize with the whitespace-byte
5139        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5140        // / `restart_window_serde_rejects_leading_plus` /
5141        // `restart_window_serde_rejects_fractional_seconds` on the
5142        // same canonical-form-drift axis.
5143        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5144            "restartWindow":" 30s",
5145            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5146        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5147        let msg = err.to_string();
5148        assert!(
5149            msg.contains("contains whitespace byte"),
5150            "expected whitespace diagnostic in {msg:?}"
5151        );
5152        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5153    }
5154
5155    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5156    //
5157    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5158    // duration codec — closes the strictly-complementary class the
5159    // byte-scan cannot see, through the lifted
5160    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5161    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5162    // and `:politicas :circuit-breaker :window` simultaneously via
5163    // this shared codec.
5164
5165    #[test]
5166    fn duration_codec_parse_rejects_leading_nbsp() {
5167        // NBSP prefix — the strictly-complementary drift class the
5168        // ASCII byte-scan cannot see. `str::trim` strips it silently
5169        // and the value drifts to `"30s"` on next serialize.
5170        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5171        assert!(
5172            err.contains("non-ASCII Unicode whitespace character"),
5173            "expected non-ASCII whitespace diagnostic in {err:?}"
5174        );
5175        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5176    }
5177
5178    #[test]
5179    fn duration_codec_parse_rejects_trailing_line_separator() {
5180        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5181        // footgun.
5182        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5183        assert!(
5184            err.contains("non-ASCII Unicode whitespace character"),
5185            "expected non-ASCII whitespace diagnostic in {err:?}"
5186        );
5187        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5188    }
5189
5190    #[test]
5191    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5192        // Positive-control pin: every ASCII-only canonical form the
5193        // renderer emits stays accepted through the new arm.
5194        assert_eq!(
5195            duration_codec::parse("30s").unwrap(),
5196            Duration::from_secs(30)
5197        );
5198        assert_eq!(
5199            duration_codec::parse("500ms").unwrap(),
5200            Duration::from_millis(500)
5201        );
5202        assert_eq!(
5203            duration_codec::parse("1h").unwrap(),
5204            Duration::from_secs(3600)
5205        );
5206    }
5207
5208    #[test]
5209    fn restart_window_serde_rejects_non_ascii_whitespace() {
5210        // The shared codec backs `SupervisorSpec::restart_window` — so
5211        // the new non-ASCII Unicode whitespace arm applies on serde
5212        // deserialize for the typed Supervisor slot. A
5213        // `{"restartWindow":" 30s"}` payload that previously
5214        // survived the ASCII byte-scan (only ASCII whitespace was
5215        // refused) is now refused at deserialize with the
5216        // non-ASCII-whitespace-and-codepoint diagnostic.
5217        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5218            \"restartWindow\":\"\u{00A0}30s\",\
5219            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5220        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5221        let msg = err.to_string();
5222        assert!(
5223            msg.contains("non-ASCII Unicode whitespace character"),
5224            "expected non-ASCII whitespace diagnostic in {msg:?}"
5225        );
5226        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5227    }
5228
5229    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5230
5231    #[test]
5232    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5233        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5234        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5235        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5236        // name the exact camelCase JSON keys the
5237        // `#[serde(rename_all = "camelCase")]` attribute on
5238        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5239        // field carries `Some(_)` / non-empty) and pin that each canonical
5240        // byte-sequence appears verbatim in the JSON — a future accidental
5241        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5242        // name flip at the derive attribute (any of which would silently
5243        // break every downstream JSON consumer that reaches for one of the
5244        // four consts via `Value::get(...)`) surfaces here as a build-time
5245        // test failure at `supervisor.rs`, not as an apply-time
5246        // `.get(<stale-canonical-const>)` returning `None` far from the
5247        // derive-attr drift's commit. Peer with the sibling
5248        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5249        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5250        // M2 typed-slot family established, extended here to close the
5251        // top-level Supervisor axis.
5252        let spec = SupervisorSpec {
5253            estrategia: RestartStrategy::OneForOne,
5254            max_restarts: 5,
5255            restart_window: Some(Duration::from_secs(60)),
5256            children: vec![ChildSpec {
5257                caixa: "w".into(),
5258                versao: "^0.1".into(),
5259                restart: RestartPolicy::Permanent,
5260            }],
5261        };
5262        let json = serde_json::to_string(&spec).unwrap();
5263        for key in [
5264            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5265            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5266            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5267            crate::render::SUPERVISOR_KEY_CHILDREN,
5268        ] {
5269            let quoted = format!("\"{key}\"");
5270            assert!(
5271                json.contains(&quoted),
5272                "serialized SupervisorSpec must carry the lifted \
5273                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5274                 the JSON emission (got: {json})",
5275            );
5276        }
5277    }
5278
5279    #[test]
5280    fn supervisor_key_consts_are_pairwise_distinct() {
5281        // Cross-axis drift-detection pin: a future collapse of two
5282        // canonical top-level byte-strings onto the same value (e.g. an
5283        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5284        // also read `"estrategia"`) would silently reroute every
5285        // downstream probe on one axis onto the sibling axis's overlay
5286        // entry and pass every propagation-probe test that expected only
5287        // the stale axis's value. Peer of the sibling four-way distinct
5288        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5289        let all = [
5290            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5291            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5292            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5293            crate::render::SUPERVISOR_KEY_CHILDREN,
5294        ];
5295        for (i, a) in all.iter().enumerate() {
5296            for b in all.iter().skip(i + 1) {
5297                assert_ne!(
5298                    a, b,
5299                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5300                     canonical byte-sequences — got `{a}` == `{b}`",
5301                );
5302            }
5303        }
5304    }
5305
5306    #[test]
5307    fn supervisor_key_consts_are_lower_camel_case_shape() {
5308        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5309        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5310        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5311        // capital, no whitespace / dots) — the canonical shape the
5312        // `#[serde(rename_all = "camelCase")]` derive produces on
5313        // `SupervisorSpec`. A future flip to a non-camelCase attribute
5314        // at the derive surfaces both here (this test fails on the
5315        // stale-constant shape) and at
5316        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5317        // (that test fails on the mismatch between const and derive).
5318        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5319        // (d8b8b4f) on the sibling M2 `:limits` axis.
5320        for key in [
5321            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5322            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5323            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5324            crate::render::SUPERVISOR_KEY_CHILDREN,
5325        ] {
5326            assert!(
5327                !key.is_empty(),
5328                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5329            );
5330            let first = key.chars().next().unwrap();
5331            assert!(
5332                first.is_ascii_lowercase(),
5333                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5334                 (got {key:?}, leads with {first:?})",
5335            );
5336            assert!(
5337                key.chars().all(|c| c.is_ascii_alphanumeric()),
5338                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5339                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5340            );
5341        }
5342    }
5343
5344    #[test]
5345    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5346        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5347        // (camelCase JSON keys, no leading colon) must never collide
5348        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5349        // consts (kebab-case author-facing labels with leading colon)
5350        // that sit next to them at `caixa_core::render`. Both families
5351        // cover the same four typed Supervisor slots on two distinct
5352        // axes (author-side kebab vs renderer-side camelCase);
5353        // collapsing either family onto the other's byte-shape would
5354        // silently reroute the render-side probe onto the author-facing
5355        // surface, or vice versa. Peer of the byte-distinctness
5356        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5357        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5358        let pairs = [
5359            (
5360                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5361                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
5362            ),
5363            (
5364                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5365                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
5366            ),
5367            (
5368                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5369                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
5370            ),
5371            (
5372                crate::render::SUPERVISOR_KEY_CHILDREN,
5373                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
5374            ),
5375        ];
5376        for (json_key, author_key) in pairs {
5377            assert_ne!(
5378                json_key, author_key,
5379                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
5380                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
5381                 got JSON `{json_key}` == author `{author_key}`",
5382            );
5383        }
5384    }
5385
5386    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
5387
5388    #[test]
5389    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
5390        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
5391        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
5392        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
5393        // keys the `#[serde(rename_all = "camelCase")]` attribute on
5394        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
5395        // pin that each canonical byte-sequence appears verbatim in the
5396        // JSON — a future accidental `rename_all = "snake_case"` /
5397        // `"kebab-case"` / verbatim-field-name flip at the derive
5398        // attribute (any of which would silently break every downstream
5399        // JSON consumer that reaches for one of the three consts via
5400        // `Value::get(...)`) surfaces here as a build-time test failure at
5401        // `supervisor.rs`, not as an apply-time
5402        // `.get(<stale-canonical-const>)` returning `None` far from the
5403        // derive-attr drift's commit. Peer with the enclosing
5404        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5405        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
5406        // discipline the SupervisorSpec top-level lift established,
5407        // extended here to the sibling per-`:children` entry `ChildSpec`
5408        // derive so the last M2 typed-struct sub-block
5409        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
5410        // surface without a lifted serde-key peer joins the substrate's
5411        // "one canonical byte-string per typed serialized-key axis"
5412        // discipline.
5413        let c = ChildSpec {
5414            caixa: "worker".into(),
5415            versao: "^0.1".into(),
5416            restart: RestartPolicy::Permanent,
5417        };
5418        let json = serde_json::to_string(&c).unwrap();
5419        for key in [
5420            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5421            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5422            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5423        ] {
5424            let quoted = format!("\"{key}\"");
5425            assert!(
5426                json.contains(&quoted),
5427                "serialized ChildSpec must carry the lifted \
5428                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
5429                 in the JSON emission (got: {json})",
5430            );
5431        }
5432    }
5433
5434    #[test]
5435    fn supervisor_child_key_consts_are_pairwise_distinct() {
5436        // Cross-axis drift-detection pin: a future collapse of two
5437        // canonical `ChildSpec` per-entry byte-strings onto the same
5438        // value (e.g. an accidental copy-paste flip of
5439        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
5440        // silently reroute every downstream probe on one axis onto the
5441        // sibling axis's overlay entry and pass every propagation-probe
5442        // test that expected only the stale axis's value. Peer of the
5443        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
5444        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
5445        // pair (ce80ca0).
5446        let all = [
5447            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5448            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5449            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5450        ];
5451        for (i, a) in all.iter().enumerate() {
5452            for b in all.iter().skip(i + 1) {
5453                assert_ne!(
5454                    a, b,
5455                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
5456                     distinct canonical byte-sequences — got `{a}` == `{b}`",
5457                );
5458            }
5459        }
5460    }
5461
5462    #[test]
5463    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
5464        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
5465        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5466        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5467        // capital, no whitespace / dots) — the canonical shape the
5468        // `#[serde(rename_all = "camelCase")]` derive produces on
5469        // `ChildSpec`. A future flip to a non-camelCase attribute at the
5470        // derive surfaces both here (this test fails on the
5471        // stale-constant shape) and at
5472        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
5473        // (that test fails on the mismatch between const and derive).
5474        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
5475        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
5476        for key in [
5477            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5478            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5479            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5480        ] {
5481            assert!(
5482                !key.is_empty(),
5483                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
5484            );
5485            let first = key.chars().next().unwrap();
5486            assert!(
5487                first.is_ascii_lowercase(),
5488                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
5489                 byte (got {key:?}, leads with {first:?})",
5490            );
5491            assert!(
5492                key.chars().all(|c| c.is_ascii_alphanumeric()),
5493                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
5494                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5495            );
5496        }
5497    }
5498
5499    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
5500
5501    #[test]
5502    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
5503        // The fail-before-pass-after pin: pre-lift there was no
5504        // single-source binding between the [`RestartStrategy`] variant
5505        // name the un-`rename`d `Serialize` derive emits under
5506        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
5507        // every downstream cluster-side dispatcher (the future
5508        // wasm-operator's per-supervisor sibling-restart branch, the
5509        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5510        // admission-time enum-arm bind, the `caixa-operator`'s
5511        // hierarchical reconciliation scheduler's per-strategy fan-out)
5512        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
5513        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
5514        // override, or a variant rename in the source — would silently
5515        // rebrand the emitted scalar under one spelling while every
5516        // downstream dispatcher still probed the other, with the failure
5517        // surfacing at the operator's reconcile posture (subtrees coming
5518        // up under the `default()` `OneForOne` arm rather than the typed
5519        // slot's declared strategy — a bad child would then only take
5520        // itself down instead of the sibling set the author intended, so
5521        // shared-state children fall out of sync) far from the source
5522        // rebrand commit and with no field naming the drift. Pinning the
5523        // two paths (the `Serialize` derive's serialized string AND the
5524        // [`RestartStrategy::as_str`] helper) to the same four lifted
5525        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
5526        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
5527        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
5528        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
5529        // byte-strings makes any future drift on either endpoint fail
5530        // here at caixa-core build time. Peer of the M3
5531        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
5532        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
5533        // three-path-convergence discipline, extended to close the
5534        // OTP-shaped per-supervisor sibling-restart axis.
5535        for (variant, expected) in [
5536            (
5537                RestartStrategy::OneForOne,
5538                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5539            ),
5540            (
5541                RestartStrategy::OneForAll,
5542                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5543            ),
5544            (
5545                RestartStrategy::RestForOne,
5546                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5547            ),
5548            (
5549                RestartStrategy::SimpleOneForOne,
5550                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5551            ),
5552        ] {
5553            let json = serde_json::to_string(&variant).unwrap();
5554            assert_eq!(
5555                json,
5556                format!("\"{expected}\""),
5557                "RestartStrategy::{variant:?} must serialize to {expected:?}"
5558            );
5559            assert_eq!(
5560                variant.as_str(),
5561                expected,
5562                "RestartStrategy::{variant:?}.as_str() must return the lifted \
5563                 SUPERVISOR_ESTRATEGIA_* constant"
5564            );
5565        }
5566    }
5567
5568    #[test]
5569    fn supervisor_estrategia_consts_are_pairwise_distinct() {
5570        // Cross-arm drift-detection pin: a future collapse of two
5571        // canonical variant byte-strings onto the same value (e.g. an
5572        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
5573        // to also read `"OneForOne"`) would silently reroute every
5574        // downstream operator's per-strategy dispatch onto the sibling
5575        // arm's reconcile branch and pass every propagation-probe test
5576        // that expected only the stale arm's value — the mis-strategied
5577        // subtree would come up with the wrong sibling-restart posture
5578        // on every subsequent failure. Peer of the sibling four-way
5579        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
5580        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
5581        let all = [
5582            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5583            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5584            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5585            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5586        ];
5587        for (i, a) in all.iter().enumerate() {
5588            for (j, b) in all.iter().enumerate() {
5589                if i != j {
5590                    assert_ne!(
5591                        a, b,
5592                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
5593                         — got duplicate {a:?} at indices {i} and {j}",
5594                    );
5595                }
5596            }
5597        }
5598    }
5599
5600    #[test]
5601    fn restart_strategy_display_routes_through_as_str_helper() {
5602        // The fail-before-pass-after pin on the first half of the
5603        // three-path convergence: pre-convergence the sibling
5604        // OTP-shape typed enum [`RestartStrategy`] carried a
5605        // [`std::fmt::Display`] surface via its
5606        // `#[discriminant(also_display)]` gen-platform derive route,
5607        // which arrived kebab-case as `"one-for-one"` /
5608        // `"one-for-all"` / `"rest-for-one"` /
5609        // `"simple-one-for-one"` while the wire format ran as
5610        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
5611        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
5612        // Every consumer reaching for a strategy byte-string past the
5613        // wire format had to pick between three paths
5614        // ([`RestartStrategy::as_str`], the `Serialize` derive's
5615        // serialized string, or `format!("{v}")` on the
5616        // discriminant-Display route), any two of which a future
5617        // variant rename or `#[serde(rename_all = "kebab-case")]`
5618        // attribute would silently desynchronize. Wiring
5619        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
5620        // closes the third path: every `format!("{v}")` call reaches
5621        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5622        // const the wire format and the [`RestartStrategy::as_str`]
5623        // helper already route through, so a future variant rename
5624        // lands at exactly one place. Pin the routing here so a future
5625        // `impl std::fmt::Display for RestartStrategy`
5626        // reimplementation that hand-rolls the arms instead of
5627        // delegating to [`RestartStrategy::as_str`] fails at
5628        // caixa-core build time. Peer of the M3
5629        // `placement_strategy_display_routes_through_as_str_helper`
5630        // (cc8f749) which the M3 axis converged first.
5631        for &variant in RestartStrategy::ALL {
5632            assert_eq!(
5633                variant.to_string(),
5634                variant.as_str(),
5635                "RestartStrategy::{variant:?} Display must route through \
5636                 RestartStrategy::as_str (single source of truth: the lifted \
5637                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
5638            );
5639        }
5640    }
5641
5642    #[test]
5643    fn restart_strategy_display_matches_serialized_wire_byte_string() {
5644        // The fail-before-pass-after pin on the second half of the
5645        // three-path convergence: `Display` (user-facing text) agrees
5646        // byte-for-byte with the `Serialize` derive's wire format
5647        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
5648        // scalar) on every variant. Pre-convergence the two paths
5649        // were structurally independent — a future
5650        // `#[serde(rename_all = "kebab-case")]` attribute on the
5651        // enum would silently rebrand the emitted wire scalar
5652        // (`one-for-one`, `one-for-all`, `rest-for-one`,
5653        // `simple-one-for-one`) while every consumer that
5654        // pretty-prints the strategy (the future wasm-operator's
5655        // per-supervisor sibling-restart-strategy diagnostic line,
5656        // the future `feira app graph` per-supervisor strategy line,
5657        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5658        // materializer's admission-webhook rejection body) would
5659        // still emit the PascalCase form the `as_str` / `Display`
5660        // route returns, with the mismatch surfacing at consumer
5661        // parse time / operator dispatch time far from the source
5662        // rebrand commit. Pin the two paths byte-for-byte here so any
5663        // future serde-attribute or variant-rename drift is a
5664        // caixa-core-build-time test failure at this call, not a
5665        // silent per-consumer dispatch miss. Peer of the M3
5666        // `placement_strategy_display_matches_serialized_wire_byte_string`
5667        // (cc8f749) which the M3 axis converged first.
5668        for &variant in RestartStrategy::ALL {
5669            let wire = serde_json::to_string(&variant).unwrap();
5670            let unquoted = wire
5671                .strip_prefix('"')
5672                .and_then(|s| s.strip_suffix('"'))
5673                .expect("serialized RestartStrategy is a JSON string");
5674            assert_eq!(
5675                variant.to_string(),
5676                unquoted,
5677                "RestartStrategy::{variant:?} Display byte-string must match the \
5678                 Serialize derive's wire byte-string (three-path convergence: \
5679                 Display + as_str + Serialize all resolve to the same \
5680                 SUPERVISOR_ESTRATEGIA_* const)"
5681            );
5682        }
5683    }
5684
5685    #[test]
5686    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
5687        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
5688        // exhaustive-iteration surface: every variant appears exactly
5689        // once, and the slice length matches the arm count of the
5690        // closed set. Every consumer that walks the accepted-strategy
5691        // set (a future `feira supervisor --estrategia …` CLI-side
5692        // arg-parse's "did you mean" hint, a future M4 admission-
5693        // webhook's rejection body naming the accepted-`:estrategia`
5694        // list, the [`RestartStrategy::from_wire`] reverse-projection
5695        // consumers that iterate the accept-set for diagnostic
5696        // rendering) reads through this slice, so a future arm addition
5697        // that grows the enum but forgets to grow [`Self::ALL`]
5698        // silently truncates every downstream consumer's accept-set at
5699        // the same pre-addition boundary — this pin fails at caixa-core
5700        // build time on the pairwise-distinct + arm-count invariants.
5701        //
5702        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
5703        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
5704        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
5705        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5706        // pins on the peer closed-set typed-enum axes.
5707        let all: &[RestartStrategy] = RestartStrategy::ALL;
5708        assert_eq!(
5709            all.len(),
5710            4,
5711            "RestartStrategy::ALL must enumerate every variant of the \
5712             four-arm closed set (OneForOne, OneForAll, RestForOne, \
5713             SimpleOneForOne); got {all:?}"
5714        );
5715        for (i, a) in all.iter().enumerate() {
5716            for (j, b) in all.iter().enumerate() {
5717                if i != j {
5718                    assert_ne!(
5719                        a, b,
5720                        "RestartStrategy::ALL must carry every variant exactly \
5721                         once — got duplicate {a:?} at indices {i} and {j}"
5722                    );
5723                }
5724            }
5725        }
5726        for variant in [
5727            RestartStrategy::OneForOne,
5728            RestartStrategy::OneForAll,
5729            RestartStrategy::RestForOne,
5730            RestartStrategy::SimpleOneForOne,
5731        ] {
5732            assert!(
5733                all.contains(&variant),
5734                "RestartStrategy::ALL must contain {variant:?} — a future arm \
5735                 addition that grows the enum but forgets to grow the ALL slice \
5736                 silently truncates every downstream consumer's accept-set at \
5737                 the pre-addition boundary"
5738            );
5739        }
5740    }
5741
5742    #[test]
5743    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
5744        // Fail-before-pass-after pin on the forward accept-set of the
5745        // [`RestartStrategy::from_wire`] reverse projection: every
5746        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5747        // constant the [`RestartStrategy::as_str`] emitter walks parses
5748        // back to its paired variant. Any future arm addition that
5749        // grows the emitter's `as_str` match but forgets to grow the
5750        // parser's `from_wire` match silently splits the two halves of
5751        // the round-trip — the wire byte-string one non-serde consumer
5752        // parses from the one the emitter wrote — with the failure
5753        // surfacing at parse time far from the rebrand commit. Pinning
5754        // the four-arm accept-set here catches the drift at caixa-core
5755        // build time.
5756        //
5757        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
5758        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
5759        // accept-set pins on the peer closed-set typed-enum `str → Self`
5760        // axes.
5761        for (wire, expected) in [
5762            (
5763                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5764                RestartStrategy::OneForOne,
5765            ),
5766            (
5767                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5768                RestartStrategy::OneForAll,
5769            ),
5770            (
5771                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5772                RestartStrategy::RestForOne,
5773            ),
5774            (
5775                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5776                RestartStrategy::SimpleOneForOne,
5777            ),
5778        ] {
5779            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
5780                panic!(
5781                    "RestartStrategy::from_wire({wire:?}) must accept every \
5782                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
5783                     lifted canonical byte-string that RestartStrategy::{expected:?} \
5784                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
5785                )
5786            });
5787            assert_eq!(
5788                parsed, expected,
5789                "RestartStrategy::from_wire({wire:?}) must return \
5790                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
5791            );
5792        }
5793    }
5794
5795    #[test]
5796    fn restart_strategy_from_wire_round_trips_through_as_str() {
5797        // Fail-before-pass-after pin on the closed round-trip between
5798        // the forward [`RestartStrategy::as_str`] emitter and the
5799        // reverse [`RestartStrategy::from_wire`] parser: for every
5800        // variant in [`RestartStrategy::ALL`], parsing the emitter's
5801        // output must return exactly the same variant. Any per-arm
5802        // divergence — a future arm added to `as_str` but not
5803        // `from_wire`, an accidental copy-paste flip in one but not
5804        // the other — silently splits the emit and parse halves and
5805        // the failure surfaces at consumer parse time far from the
5806        // drift site. The `ALL`-iterating shape means a future arm
5807        // addition picks up the coverage by construction.
5808        //
5809        // Peer of the sibling
5810        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
5811        // (18c7342) round-trip pin on
5812        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
5813        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
5814        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
5815        for &variant in RestartStrategy::ALL {
5816            let wire = variant.as_str();
5817            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
5818                panic!(
5819                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
5820                     must be Some({variant:?}) — the two halves of the round-trip \
5821                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
5822                     got None on wire byte-string {wire:?}"
5823                )
5824            });
5825            assert_eq!(
5826                parsed, variant,
5827                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
5828                 must round-trip to the same variant; got {parsed:?}"
5829            );
5830        }
5831    }
5832
5833    #[test]
5834    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
5835        // Fail-before-pass-after pin on the closed-set refusal
5836        // discipline of [`RestartStrategy::from_wire`]: every
5837        // byte-string outside the four-arm accept-set returns `None`
5838        // rather than silently collapsing onto the [`Default`]
5839        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
5840        // exercised here sweeps the load-bearing drift shapes: the
5841        // empty string (a stripped serde-attribute drift), all-
5842        // whitespace strings (the canonical text-editor accidental
5843        // padding shape), the kebab-case dispatcher-catalog identities
5844        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
5845        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
5846        // derived [`std::str::FromStr`] accept-set, which parses the
5847        // *other* axis of this enum's two-axis split and must not leak
5848        // into the `from_wire` PascalCase-wire accept-set), the
5849        // lowercased single-word forms (`"oneforone"`), the padded
5850        // canonical scalar (`" OneForOne "`), the trailing-newline
5851        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
5852        // (`"AllForOne"` — the canonical typo direction).
5853        //
5854        // Peer of the sibling
5855        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
5856        // (2aa6d23) +
5857        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
5858        // (18c7342) refusal pins on the peer closed-set typed-enum
5859        // axes.
5860        for bad in [
5861            "",
5862            " ",
5863            "\n",
5864            "\t",
5865            "one-for-one",
5866            "one-for-all",
5867            "rest-for-one",
5868            "simple-one-for-one",
5869            "oneforone",
5870            "OneForOnes",
5871            "one_for_one",
5872            "one for one",
5873            "ONEFORONE",
5874            "OneForOne ",
5875            " OneForOne",
5876            " SimpleOneForOne ",
5877            "OneForOne\n",
5878            "restforone",
5879            "REST_FOR_ONE",
5880            "AllForOne",
5881            "Simple",
5882            "?",
5883        ] {
5884            assert!(
5885                RestartStrategy::from_wire(bad).is_none(),
5886                "RestartStrategy::from_wire({bad:?}) must return None — the \
5887                 parser's accept-set is exactly the four RestartStrategy::as_str \
5888                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
5889                 and this byte-string is outside that closed set"
5890            );
5891        }
5892    }
5893
5894    #[test]
5895    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
5896        // Fail-before-pass-after pin on the fourth path of the four-path
5897        // convergence: `from_wire` (the reverse projection) inverts the
5898        // `Serialize` derive's wire byte-string on every variant.
5899        // Together with the pre-existing three-path convergence
5900        // (`Display` + `as_str` + `Serialize` all resolve to the same
5901        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
5902        // pinned by
5903        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
5904        // this closes the round-trip: the wire byte-string the
5905        // `Serialize` derive emits parses back to the same variant
5906        // through `from_wire`, so any future serde-attribute or variant-
5907        // rename drift on the emit half now surfaces as a matched drift
5908        // on the parse half at caixa-core build time — the two halves
5909        // migrate as a unit through the lifted consts on any future
5910        // rename, and the round-trip cannot silently split.
5911        //
5912        // Peer of the sibling
5913        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
5914        // (18c7342) wire-format pin on
5915        // [`crate::aplicacao::PlacementStrategy::from_wire`].
5916        for &variant in RestartStrategy::ALL {
5917            let wire = serde_json::to_string(&variant).unwrap();
5918            let unquoted = wire
5919                .strip_prefix('"')
5920                .and_then(|s| s.strip_suffix('"'))
5921                .expect("serialized RestartStrategy is a JSON string");
5922            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
5923                panic!(
5924                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
5925                     Serialize derive's wire byte-string for \
5926                     RestartStrategy::{variant:?} — the four-path convergence \
5927                     (Display + as_str + Serialize + from_wire) resolves through \
5928                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
5929                )
5930            });
5931            assert_eq!(
5932                parsed, variant,
5933                "RestartStrategy::from_wire of the Serialize derive's wire \
5934                 byte-string for RestartStrategy::{variant:?} must round-trip \
5935                 to the same variant; got {parsed:?}"
5936            );
5937        }
5938    }
5939
5940    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
5941
5942    #[test]
5943    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
5944        // The fail-before-pass-after pin: pre-lift there was no
5945        // single-source binding between the [`RestartPolicy`] variant
5946        // name the un-`rename`d `Serialize` derive emits under
5947        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
5948        // byte-string every downstream cluster-side dispatcher (the
5949        // future wasm-operator's per-child post-exit restart-decision
5950        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5951        // materializer's admission-time enum-arm bind, the
5952        // `caixa-operator`'s hierarchical reconciliation scheduler's
5953        // per-child-policy fan-out) probes verbatim. A future
5954        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
5955        // or a per-variant `#[serde(rename = "…")]` override, or a
5956        // variant rename in the source — would silently rebrand the
5957        // emitted scalar under one spelling while every downstream
5958        // dispatcher still probed the other, with the failure surfacing
5959        // at the operator's reconcile posture (children coming up under
5960        // the `default()` `Permanent` arm rather than the typed slot's
5961        // declared policy — a `:temporary` `oneShot` child would be
5962        // restarted on clean exit, treating the successful-completion
5963        // signal as failure and re-running the completion-terminal
5964        // one-shot indefinitely; a `:transient` child that clean-exited
5965        // would be restarted, masking the clean-completion contract)
5966        // far from the source rebrand commit and with no field naming
5967        // the drift. Pinning the two paths (the `Serialize` derive's
5968        // serialized string AND the [`RestartPolicy::as_str`] helper)
5969        // to the same three lifted
5970        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
5971        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
5972        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
5973        // byte-strings makes any future drift on either endpoint fail
5974        // here at caixa-core build time. Peer of the sibling
5975        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
5976        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
5977        // and the M3
5978        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
5979        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
5980        // same three-path-convergence discipline, extended to close the
5981        // third OTP-shaped closed-enum discriminator axis on the caixa
5982        // typed surface (per-child restart-decision policy).
5983        for (variant, expected) in [
5984            (
5985                RestartPolicy::Permanent,
5986                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
5987            ),
5988            (
5989                RestartPolicy::Temporary,
5990                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
5991            ),
5992            (
5993                RestartPolicy::Transient,
5994                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
5995            ),
5996        ] {
5997            let json = serde_json::to_string(&variant).unwrap();
5998            assert_eq!(
5999                json,
6000                format!("\"{expected}\""),
6001                "RestartPolicy::{variant:?} must serialize to {expected:?}"
6002            );
6003            assert_eq!(
6004                variant.as_str(),
6005                expected,
6006                "RestartPolicy::{variant:?}.as_str() must return the lifted \
6007                 SUPERVISOR_CHILD_RESTART_* constant"
6008            );
6009        }
6010    }
6011
6012    #[test]
6013    fn supervisor_child_restart_consts_are_pairwise_distinct() {
6014        // Cross-arm drift-detection pin: a future collapse of two
6015        // canonical variant byte-strings onto the same value (e.g. an
6016        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
6017        // to also read `"Permanent"`) would silently reroute every
6018        // downstream operator's per-child-policy dispatch onto the
6019        // sibling arm's reconcile branch and pass every propagation-probe
6020        // test that expected only the stale arm's value — a `:transient`
6021        // child would come up under the `:permanent` restart-decision
6022        // posture on every subsequent clean exit, so a completion-terminal
6023        // child would be restarted indefinitely against its declared
6024        // policy. Peer of the sibling
6025        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
6026        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6027        // and the four-way distinct pin
6028        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
6029        // top-level `SUPERVISOR_KEY_*` axis.
6030        let all = [
6031            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6032            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6033            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6034        ];
6035        for (i, a) in all.iter().enumerate() {
6036            for (j, b) in all.iter().enumerate() {
6037                if i != j {
6038                    assert_ne!(
6039                        a, b,
6040                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
6041                         — got duplicate {a:?} at indices {i} and {j}",
6042                    );
6043                }
6044            }
6045        }
6046    }
6047
6048    #[test]
6049    fn restart_policy_display_routes_through_as_str_helper() {
6050        // The fail-before-pass-after pin on the first half of the
6051        // three-path convergence: pre-convergence [`RestartPolicy`]
6052        // carried a [`std::fmt::Display`] surface via its
6053        // `#[discriminant(also_display)]` gen-platform derive route,
6054        // which arrived kebab-case as `"permanent"` / `"temporary"`
6055        // / `"transient"` on this three-arm enum (whose variant
6056        // names each collapse to their own lowercase form under the
6057        // kebab-case transform) while the wire format ran as
6058        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
6059        // through the un-`rename`d serde derive. Every consumer
6060        // reaching for a policy byte-string past the wire format had
6061        // to pick between three paths ([`RestartPolicy::as_str`],
6062        // the `Serialize` derive's serialized string, or
6063        // `format!("{v}")` on the discriminant-Display route), any
6064        // two of which a future variant rename or
6065        // `#[serde(rename_all = "kebab-case")]` attribute would
6066        // silently desynchronize. Wiring [`std::fmt::Display`]
6067        // through [`RestartPolicy::as_str`] closes the third path:
6068        // every `format!("{v}")` call reaches the same lifted
6069        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
6070        // wire format and the [`RestartPolicy::as_str`] helper
6071        // already route through, so a future variant rename lands at
6072        // exactly one place. Pin the routing here so a future
6073        // `impl std::fmt::Display for RestartPolicy`
6074        // reimplementation that hand-rolls the arms instead of
6075        // delegating to [`RestartPolicy::as_str`] fails at
6076        // caixa-core build time. Peer of the sibling
6077        // [`restart_strategy_display_routes_through_as_str_helper`]
6078        // on the per-supervisor sibling-restart-strategy axis and
6079        // the M3
6080        // `placement_strategy_display_routes_through_as_str_helper`
6081        // (cc8f749) — the third of three OTP-shape closed-enum
6082        // discriminator axes on the caixa typed surface now
6083        // converged onto the same three-path
6084        // (Display → as_str → lifted const) discipline.
6085        for variant in [
6086            RestartPolicy::Permanent,
6087            RestartPolicy::Temporary,
6088            RestartPolicy::Transient,
6089        ] {
6090            assert_eq!(
6091                variant.to_string(),
6092                variant.as_str(),
6093                "RestartPolicy::{variant:?} Display must route through \
6094                 RestartPolicy::as_str (single source of truth: the lifted \
6095                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
6096            );
6097        }
6098    }
6099
6100    #[test]
6101    fn restart_policy_display_matches_serialized_wire_byte_string() {
6102        // The fail-before-pass-after pin on the second half of the
6103        // three-path convergence: `Display` (user-facing text) agrees
6104        // byte-for-byte with the `Serialize` derive's wire format
6105        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
6106        // scalar) on every variant. Pre-convergence the two paths
6107        // were structurally independent — a future
6108        // `#[serde(rename_all = "kebab-case")]` attribute on the
6109        // enum would silently rebrand the emitted wire scalar
6110        // (`permanent`, `temporary`, `transient`) while every
6111        // consumer that pretty-prints the policy (the future
6112        // wasm-operator's per-child post-exit restart-decision
6113        // diagnostic line, the future `feira app graph` per-child
6114        // restart column, the future M4
6115        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6116        // per-child admission-webhook rejection body) would still
6117        // emit the PascalCase form the `as_str` / `Display` route
6118        // returns, with the mismatch surfacing at consumer parse
6119        // time / operator dispatch time far from the source rebrand
6120        // commit. Pin the two paths byte-for-byte here so any future
6121        // serde-attribute or variant-rename drift is a
6122        // caixa-core-build-time test failure at this call, not a
6123        // silent per-consumer dispatch miss. Peer of the sibling
6124        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
6125        // on the per-supervisor sibling-restart-strategy axis and
6126        // the M3
6127        // `placement_strategy_display_matches_serialized_wire_byte_string`
6128        // (cc8f749).
6129        for variant in [
6130            RestartPolicy::Permanent,
6131            RestartPolicy::Temporary,
6132            RestartPolicy::Transient,
6133        ] {
6134            let wire = serde_json::to_string(&variant).unwrap();
6135            let unquoted = wire
6136                .strip_prefix('"')
6137                .and_then(|s| s.strip_suffix('"'))
6138                .expect("serialized RestartPolicy is a JSON string");
6139            assert_eq!(
6140                variant.to_string(),
6141                unquoted,
6142                "RestartPolicy::{variant:?} Display byte-string must match the \
6143                 Serialize derive's wire byte-string (three-path convergence: \
6144                 Display + as_str + Serialize all resolve to the same \
6145                 SUPERVISOR_CHILD_RESTART_* const)"
6146            );
6147        }
6148    }
6149
6150    #[test]
6151    fn restart_policy_all_enumerates_every_variant_exactly_once() {
6152        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
6153        // exhaustive-iteration surface: every variant appears exactly
6154        // once, and the slice length matches the arm count of the
6155        // closed set. Every consumer that walks the accepted-policy
6156        // set (a future `feira supervisor --restart …` CLI-side
6157        // arg-parse's "did you mean" hint, a future M4 admission-
6158        // webhook's per-child rejection body naming the accepted-
6159        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
6160        // projection consumers that iterate the accept-set for
6161        // diagnostic rendering) reads through this slice, so a future
6162        // arm addition that grows the enum but forgets to grow
6163        // [`Self::ALL`] silently truncates every downstream consumer's
6164        // accept-set at the same pre-addition boundary — this pin
6165        // fails at caixa-core build time on the pairwise-distinct +
6166        // arm-count invariants.
6167        //
6168        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
6169        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
6170        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6171        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6172        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6173        // pins on the peer closed-set typed-enum axes.
6174        let all: &[RestartPolicy] = RestartPolicy::ALL;
6175        assert_eq!(
6176            all.len(),
6177            3,
6178            "RestartPolicy::ALL must enumerate every variant of the \
6179             three-arm closed set (Permanent, Temporary, Transient); \
6180             got {all:?}"
6181        );
6182        for (i, a) in all.iter().enumerate() {
6183            for (j, b) in all.iter().enumerate() {
6184                if i != j {
6185                    assert_ne!(
6186                        a, b,
6187                        "RestartPolicy::ALL must carry every variant exactly \
6188                         once — got duplicate {a:?} at indices {i} and {j}"
6189                    );
6190                }
6191            }
6192        }
6193        for variant in [
6194            RestartPolicy::Permanent,
6195            RestartPolicy::Temporary,
6196            RestartPolicy::Transient,
6197        ] {
6198            assert!(
6199                all.contains(&variant),
6200                "RestartPolicy::ALL must contain {variant:?} — a future arm \
6201                 addition that grows the enum but forgets to grow the ALL slice \
6202                 silently truncates every downstream consumer's accept-set at \
6203                 the pre-addition boundary"
6204            );
6205        }
6206    }
6207
6208    #[test]
6209    fn restart_policy_from_wire_accepts_every_lifted_constant() {
6210        // Fail-before-pass-after pin on the forward accept-set of the
6211        // [`RestartPolicy::from_wire`] reverse projection: every
6212        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
6213        // constant the [`RestartPolicy::as_str`] emitter walks parses
6214        // back to its paired variant. Any future arm addition that
6215        // grows the emitter's `as_str` match but forgets to grow the
6216        // parser's `from_wire` match silently splits the two halves of
6217        // the round-trip — the wire byte-string one non-serde consumer
6218        // parses from the one the emitter wrote — with the failure
6219        // surfacing at the operator's reconcile posture (a `:temporary`
6220        // `oneShot` child restarted on clean exit, a `:transient` child
6221        // restarted after clean completion) far from the rebrand
6222        // commit. Pinning the three-arm accept-set here catches the
6223        // drift at caixa-core build time.
6224        //
6225        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
6226        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
6227        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6228        // accept-set pins on the peer closed-set typed-enum `str → Self`
6229        // axes.
6230        for (wire, expected) in [
6231            (
6232                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6233                RestartPolicy::Permanent,
6234            ),
6235            (
6236                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6237                RestartPolicy::Temporary,
6238            ),
6239            (
6240                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6241                RestartPolicy::Transient,
6242            ),
6243        ] {
6244            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6245                panic!(
6246                    "RestartPolicy::from_wire({wire:?}) must accept every \
6247                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
6248                     lifted canonical byte-string that RestartPolicy::{expected:?} \
6249                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
6250                )
6251            });
6252            assert_eq!(
6253                parsed, expected,
6254                "RestartPolicy::from_wire({wire:?}) must return \
6255                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
6256            );
6257        }
6258    }
6259
6260    #[test]
6261    fn restart_policy_from_wire_round_trips_through_as_str() {
6262        // Fail-before-pass-after pin on the closed round-trip between
6263        // the forward [`RestartPolicy::as_str`] emitter and the
6264        // reverse [`RestartPolicy::from_wire`] parser: for every
6265        // variant in [`RestartPolicy::ALL`], parsing the emitter's
6266        // output must return exactly the same variant. Any per-arm
6267        // divergence — a future arm added to `as_str` but not
6268        // `from_wire`, an accidental copy-paste flip in one but not
6269        // the other — silently splits the emit and parse halves and
6270        // the failure surfaces at consumer parse time far from the
6271        // drift site. The `ALL`-iterating shape means a future arm
6272        // addition picks up the coverage by construction.
6273        //
6274        // Peer of the sibling
6275        // [`restart_strategy_from_wire_round_trips_through_as_str`]
6276        // (4eec29c) round-trip pin on
6277        // [`RestartStrategy::from_wire`] and the M3
6278        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6279        // (18c7342) round-trip pin on
6280        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6281        for &variant in RestartPolicy::ALL {
6282            let wire = variant.as_str();
6283            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6284                panic!(
6285                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6286                     must be Some({variant:?}) — the two halves of the round-trip \
6287                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
6288                     got None on wire byte-string {wire:?}"
6289                )
6290            });
6291            assert_eq!(
6292                parsed, variant,
6293                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6294                 must round-trip to the same variant; got {parsed:?}"
6295            );
6296        }
6297    }
6298
6299    #[test]
6300    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
6301        // Fail-before-pass-after pin on the closed-set refusal
6302        // discipline of [`RestartPolicy::from_wire`]: every
6303        // byte-string outside the three-arm accept-set returns `None`
6304        // rather than silently collapsing onto the [`Default`]
6305        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
6306        // exercised here sweeps the load-bearing drift shapes: the
6307        // empty string (a stripped serde-attribute drift), all-
6308        // whitespace strings (the canonical text-editor accidental
6309        // padding shape), the kebab-case dispatcher-catalog identities
6310        // (`"permanent"` / `"temporary"` / `"transient"` — the
6311        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
6312        // accept-set, which parses the *other* axis of this enum's
6313        // two-axis split and must not leak into the `from_wire`
6314        // PascalCase-wire accept-set — a lowercase leak here would
6315        // silently accept the operator's kebab-case
6316        // dispatcher-catalog probe under the wire-axis parser and mis-
6317        // route a `:permanent` intent), the padded canonical scalar
6318        // (`" Permanent "`), the trailing-newline shapes
6319        // (`"Permanent\n"`), the uppercase-single-word forms
6320        // (`"PERMANENT"`), and neighboring-but-unknown arms
6321        // (`"Restart"` — the canonical typo direction toward the
6322        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
6323        //
6324        // Peer of the sibling
6325        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
6326        // (4eec29c) +
6327        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6328        // (2aa6d23) +
6329        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6330        // (18c7342) refusal pins on the peer closed-set typed-enum
6331        // axes.
6332        for bad in [
6333            "",
6334            " ",
6335            "\n",
6336            "\t",
6337            "permanent",
6338            "temporary",
6339            "transient",
6340            "PERMANENT",
6341            "TEMPORARY",
6342            "TRANSIENT",
6343            "Permanents",
6344            "Permanent ",
6345            " Permanent",
6346            " Transient ",
6347            "Permanent\n",
6348            "perma",
6349            "Trans",
6350            "OneForOne",
6351            "Restart",
6352            "?",
6353        ] {
6354            assert!(
6355                RestartPolicy::from_wire(bad).is_none(),
6356                "RestartPolicy::from_wire({bad:?}) must return None — the \
6357                 parser's accept-set is exactly the three RestartPolicy::as_str \
6358                 outputs (Permanent, Temporary, Transient), and this \
6359                 byte-string is outside that closed set"
6360            );
6361        }
6362    }
6363
6364    #[test]
6365    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
6366        // Fail-before-pass-after pin on the fourth path of the four-path
6367        // convergence: `from_wire` (the reverse projection) inverts the
6368        // `Serialize` derive's wire byte-string on every variant.
6369        // Together with the pre-existing three-path convergence
6370        // (`Display` + `as_str` + `Serialize` all resolve to the same
6371        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
6372        // pinned by
6373        // [`restart_policy_display_matches_serialized_wire_byte_string`])
6374        // this closes the round-trip: the wire byte-string the
6375        // `Serialize` derive emits parses back to the same variant
6376        // through `from_wire`, so any future serde-attribute or variant-
6377        // rename drift on the emit half now surfaces as a matched drift
6378        // on the parse half at caixa-core build time — the two halves
6379        // migrate as a unit through the lifted consts on any future
6380        // rename, and the round-trip cannot silently split.
6381        //
6382        // Peer of the sibling
6383        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6384        // (4eec29c) wire-format pin on
6385        // [`RestartStrategy::from_wire`] and the M3
6386        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6387        // (18c7342) wire-format pin on
6388        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6389        for &variant in RestartPolicy::ALL {
6390            let wire = serde_json::to_string(&variant).unwrap();
6391            let unquoted = wire
6392                .strip_prefix('"')
6393                .and_then(|s| s.strip_suffix('"'))
6394                .expect("serialized RestartPolicy is a JSON string");
6395            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
6396                panic!(
6397                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
6398                     Serialize derive's wire byte-string for \
6399                     RestartPolicy::{variant:?} — the four-path convergence \
6400                     (Display + as_str + Serialize + from_wire) resolves through \
6401                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
6402                )
6403            });
6404            assert_eq!(
6405                parsed, variant,
6406                "RestartPolicy::from_wire of the Serialize derive's wire \
6407                 byte-string for RestartPolicy::{variant:?} must round-trip \
6408                 to the same variant; got {parsed:?}"
6409            );
6410        }
6411    }
6412
6413    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
6414    //
6415    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
6416    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
6417    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
6418    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
6419    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
6420    // the peer per-`:upgrade-from :from` axis. The three pins jointly
6421    // brace the accessor against every future silent detour that would
6422    // desynchronize it from the raw `.caixa` field access every consumer
6423    // previously open-coded.
6424
6425    #[test]
6426    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
6427        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
6428        // [`ChildSpec::nome`] must return the `:children :caixa` field
6429        // byte-for-byte across every DNS-1123-label value the upstream
6430        // [`crate::render::require_valid_dns_1123_label`] gate at
6431        // `SupervisorSpec::validate` admits. Peer of the sibling
6432        // `membro_nome_returns_caixa_byte_equal_across_permutations`
6433        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
6434        // substrate-primitive accessor must byte-equal the raw field
6435        // access verbatim across every author-declared value" discipline
6436        // extended to the M2 supervisor-tree per-`:children` arm. Pins
6437        // against a future silent detour that re-normalized the child
6438        // identity (an accidental `.to_lowercase()` — every `:children
6439        // :caixa` is validated as a DNS-1123 label upstream, so any
6440        // re-normalization is redundant + a drift surface between the
6441        // validator and the accessor), a namespace-prefix rewrite (an
6442        // accidental `format!("{namespace}/{caixa}")` per-CR
6443        // fully-qualified rewrite that didn't land on the peer axes), or
6444        // a per-cluster alias stamp the future wasm-operator's
6445        // hierarchical reconciliation scheduler authors on one consumer
6446        // without the others. Five values sweep the accept-set the
6447        // DNS-1123 gate upstream admits (short single-word / dashed /
6448        // v-suffixed / mixed-digit child names).
6449        for name in [
6450            "worker",
6451            "cache-server",
6452            "scratch-job",
6453            "orders-v2",
6454            "session-8080",
6455        ] {
6456            let c = ChildSpec {
6457                caixa: name.into(),
6458                versao: "^0.1".into(),
6459                restart: RestartPolicy::Permanent,
6460            };
6461            assert_eq!(
6462                c.nome(),
6463                name,
6464                "ChildSpec::nome must return :children :caixa verbatim \
6465                 (got {:?}, expected {name:?})",
6466                c.nome(),
6467            );
6468            assert_eq!(
6469                c.nome(),
6470                c.caixa.as_str(),
6471                "ChildSpec::nome must byte-equal the .caixa field access",
6472            );
6473        }
6474    }
6475
6476    #[test]
6477    fn child_spec_nome_borrows_from_caixa_storage() {
6478        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
6479        // `&str` slice that borrows from the typed slot's own [`String`]
6480        // storage — same-address invariant with `c.caixa.as_str()`. Pins
6481        // against a future silent detour that allocated a fresh `String`
6482        // (`self.caixa.clone()` in the body would type-check but silently
6483        // drop the borrow, and every downstream consumer that assumed
6484        // the returned slice outlives `&self` would break on a stale-
6485        // reference use-after-free — the [`crate::render::insert_first_seen`]
6486        // dedup key at [`SupervisorSpec::validate`], the
6487        // [`validate_no_self_supervision`] equality check against the
6488        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
6489        // borrow — each would silently misbehave if this accessor
6490        // produced a detached copy). Peer of the sibling
6491        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
6492        // M3 per-`:membros` axis and the
6493        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
6494        // first M2 slot scalar accessor.
6495        let c = ChildSpec {
6496            caixa: "worker".into(),
6497            versao: "^0.1".into(),
6498            restart: RestartPolicy::Permanent,
6499        };
6500        let name = c.nome();
6501        let caixa_slice = c.caixa.as_str();
6502        assert_eq!(
6503            name.as_ptr(),
6504            caixa_slice.as_ptr(),
6505            "ChildSpec::nome must borrow from the .caixa String's backing \
6506             storage — a fresh allocation here means the accessor no \
6507             longer names the substrate-primitive typed dispatch and \
6508             every downstream consumer would silently carry a detached \
6509             copy",
6510        );
6511        assert_eq!(
6512            name.len(),
6513            caixa_slice.len(),
6514            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
6515             as well as in address",
6516        );
6517    }
6518
6519    #[test]
6520    fn validate_gates_child_nome_through_lifted_accessor() {
6521        // Bilateral coherence pin: every `:children :caixa` that
6522        // [`SupervisorSpec::validate`] accepts is one
6523        // [`crate::render::require_valid_dns_1123_label`] accepts on the
6524        // accessor-projected value, and vice versa on the reject side.
6525        // This closes the "the validator reads through the accessor"
6526        // contract structurally — a future silent detour that made the
6527        // accessor return a different byte-string than the validator
6528        // gates against would surface here as a coverage mismatch, not
6529        // as an apply-time DNS-1123 rejection at
6530        // `metadata.name: Invalid value` far from the caixa.lisp source.
6531        // Peer of the M2 sibling
6532        // `validate_parses_prior_versao_through_lifted_accessor`
6533        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
6534        // `validate_membros` peer discipline.
6535        //
6536        // Accept-set sweep: five DNS-1123-label values the upstream gate
6537        // admits.
6538        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
6539            let s = SupervisorSpec {
6540                children: vec![ChildSpec {
6541                    caixa: ok_name.into(),
6542                    versao: "^0.1".into(),
6543                    restart: RestartPolicy::Permanent,
6544                }],
6545                ..SupervisorSpec::default()
6546            };
6547            s.validate().unwrap_or_else(|e| {
6548                panic!(
6549                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
6550                     (upstream DNS-1123 gate accepts it): got {e:?}",
6551                );
6552            });
6553            let c = ChildSpec {
6554                caixa: ok_name.into(),
6555                versao: "^0.1".into(),
6556                restart: RestartPolicy::Permanent,
6557            };
6558            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
6559                .unwrap_or_else(|()| {
6560                    panic!(
6561                        "require_valid_dns_1123_label must accept the accessor-projected \
6562                     :children :caixa {ok_name:?}",
6563                    );
6564                });
6565        }
6566        // Reject-set sweep: five DNS-1123-label-violating shapes the
6567        // upstream gate refuses (empty / uppercase / underscore / dot /
6568        // leading-hyphen). Every rejection at the validator must
6569        // correspond to a rejection when the accessor's projected value
6570        // is fed back through the shared gate.
6571        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
6572            let s = SupervisorSpec {
6573                children: vec![ChildSpec {
6574                    caixa: bad_name.into(),
6575                    versao: "^0.1".into(),
6576                    restart: RestartPolicy::Permanent,
6577                }],
6578                ..SupervisorSpec::default()
6579            };
6580            let err = s.validate().unwrap_err();
6581            assert!(
6582                matches!(
6583                    err,
6584                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
6585                ),
6586                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
6587                 via the DNS-1123 gate: got {err:?}",
6588            );
6589            let c = ChildSpec {
6590                caixa: bad_name.into(),
6591                versao: "^0.1".into(),
6592                restart: RestartPolicy::Permanent,
6593            };
6594            assert!(
6595                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
6596                    .is_err(),
6597                "require_valid_dns_1123_label must reject the accessor-projected \
6598                 :children :caixa {bad_name:?}",
6599            );
6600        }
6601    }
6602
6603    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
6604    //
6605    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
6606    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
6607    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
6608    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
6609    // trio on the peer per-`:children` `String`-carry axis. The three pins
6610    // jointly brace the accessor against every future silent detour that
6611    // would desynchronize it from the raw `.versao` field access the
6612    // requirement gate + error carrier previously open-coded.
6613    //
6614    // Closes the last unlifted per-`:children` `String`-carry axis: the
6615    // pair (`nome`, `versao_requirement`) now jointly projects the
6616    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
6617    // consumer that fans on per-child identity + version pin reads,
6618    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
6619    // pair discipline verbatim.
6620    #[test]
6621    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
6622        // The canonical per-`:children` child-`:versao`-scalar pin:
6623        // [`ChildSpec::versao_requirement`] must return the `:children
6624        // :versao` field byte-for-byte across every Cargo-shaped semver
6625        // requirement value the upstream
6626        // [`crate::render::require_valid_versao_requirement`] gate admits.
6627        // Peer of the sibling
6628        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
6629        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
6630        // substrate-primitive accessor must byte-equal the raw field
6631        // access verbatim across every author-declared value" discipline
6632        // extended to the M2 supervisor-tree per-`:children` arm. Pins
6633        // against a future silent detour that re-canonicalized the
6634        // requirement (an accidental `.to_string()` via
6635        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
6636        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
6637        // silently drifted the error carrier's quoted requirement away
6638        // from the source `caixa.lisp`, an accidental whitespace trim on
6639        // `"^ 0.1"` that no consumer ever produced from the field-access
6640        // side, an accidental per-cluster lacre-projected concrete-version
6641        // rewrite that didn't land on the peer requirement-gate call).
6642        // Five values sweep the accept-set the shared
6643        // [`crate::render::require_valid_versao_requirement`] gate admits
6644        // (caret / tilde / exact / wildcard / bare-major).
6645        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6646            let c = ChildSpec {
6647                caixa: "worker".into(),
6648                versao: req.into(),
6649                restart: RestartPolicy::Permanent,
6650            };
6651            assert_eq!(
6652                c.versao_requirement(),
6653                req,
6654                "ChildSpec::versao_requirement must return :children :versao \
6655                 verbatim (got {:?}, expected {req:?})",
6656                c.versao_requirement(),
6657            );
6658            assert_eq!(
6659                c.versao_requirement(),
6660                c.versao.as_str(),
6661                "ChildSpec::versao_requirement must byte-equal the .versao \
6662                 field access",
6663            );
6664        }
6665    }
6666
6667    #[test]
6668    fn child_spec_versao_requirement_borrows_from_versao_storage() {
6669        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
6670        // return a `&str` slice that borrows from the typed slot's own
6671        // [`String`] storage — same-address invariant with
6672        // `c.versao.as_str()`. Pins against a future silent detour that
6673        // allocated a fresh `String` (`self.versao.clone()` in the body
6674        // would type-check but silently drop the borrow, and every
6675        // downstream consumer that assumed the returned slice outlives
6676        // `&self` — the [`crate::render::require_valid_versao_requirement`]
6677        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
6678        // `.to_string()` carrier's byte-length assumption — would silently
6679        // misbehave if this accessor produced a detached copy). Peer of
6680        // the sibling `child_spec_nome_borrows_from_caixa_storage`
6681        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
6682        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
6683        // pin on the peer per-`:membros` `:versao` axis.
6684        let c = ChildSpec {
6685            caixa: "worker".into(),
6686            versao: "^0.1".into(),
6687            restart: RestartPolicy::Permanent,
6688        };
6689        let req = c.versao_requirement();
6690        let versao_slice = c.versao.as_str();
6691        assert_eq!(
6692            req.as_ptr(),
6693            versao_slice.as_ptr(),
6694            "ChildSpec::versao_requirement must borrow from the .versao \
6695             String's backing storage — a fresh allocation here means the \
6696             accessor no longer names the substrate-primitive typed \
6697             dispatch and every downstream consumer would silently carry \
6698             a detached copy",
6699        );
6700        assert_eq!(
6701            req.len(),
6702            versao_slice.len(),
6703            "ChildSpec::versao_requirement and .versao.as_str() must \
6704             byte-equal in length as well as in address",
6705        );
6706    }
6707
6708    #[test]
6709    fn validate_gates_child_versao_through_lifted_accessor() {
6710        // Bilateral coherence pin: every `:children :versao` that
6711        // [`SupervisorSpec::validate`] accepts is one
6712        // [`crate::render::require_valid_versao_requirement`] accepts on
6713        // the accessor-projected value, and vice versa on the reject side.
6714        // This closes the "the validator reads through the accessor"
6715        // contract structurally — a future silent detour that made the
6716        // accessor return a different byte-string than the validator gates
6717        // against would surface here as a coverage mismatch, not as a
6718        // resolver-time semver-parse rejection at lacre-closure time far
6719        // from the caixa.lisp source. Peer of the sibling
6720        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
6721        // the per-`:children :caixa` axis and the M2
6722        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
6723        // on the peer per-`:upgrade-from :from` axis.
6724        //
6725        // Accept-set sweep: five Cargo-shaped semver requirement values
6726        // the upstream gate admits (caret / tilde / exact / wildcard /
6727        // bare-major).
6728        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6729            let s = SupervisorSpec {
6730                children: vec![ChildSpec {
6731                    caixa: "worker".into(),
6732                    versao: ok_req.into(),
6733                    restart: RestartPolicy::Permanent,
6734                }],
6735                ..SupervisorSpec::default()
6736            };
6737            s.validate().unwrap_or_else(|e| {
6738                panic!(
6739                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
6740                     (upstream versao-requirement gate accepts it): got {e:?}",
6741                );
6742            });
6743            let c = ChildSpec {
6744                caixa: "worker".into(),
6745                versao: ok_req.into(),
6746                restart: RestartPolicy::Permanent,
6747            };
6748            crate::render::require_valid_versao_requirement(
6749                c.versao_requirement(),
6750                || (),
6751                |_reason| (),
6752            )
6753            .unwrap_or_else(|()| {
6754                panic!(
6755                    "require_valid_versao_requirement must accept the accessor-projected \
6756                     :children :versao {ok_req:?}",
6757                );
6758            });
6759        }
6760        // Reject-set sweep: five requirement-violating shapes the upstream
6761        // gate refuses. The empty string closes the empty-first arm of the
6762        // shared [`crate::render::require_valid_versao_requirement`]
6763        // cascade; the four non-empty arms exercise distinct semver-parse
6764        // failure modes the M3 peer per-`:membros` reject-set already pins
6765        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
6766        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
6767        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
6768        // shared parser routing means the same reject-set must fail
6769        // identically at the M2 supervisor-tree per-`:children` accessor
6770        // arm here. Every rejection at the validator must correspond to a
6771        // rejection when the accessor's projected value is fed back
6772        // through the shared gate.
6773        //
6774        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
6775        // `"not-a-semver"` are intentionally *not* in the reject-set: the
6776        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
6777        // and the identifier-tail arm's grammar admits some non-canonical
6778        // shapes — matching what the M3 peer test suite already documents
6779        // as the shared parser's accept-set edges.)
6780        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
6781            let s = SupervisorSpec {
6782                children: vec![ChildSpec {
6783                    caixa: "worker".into(),
6784                    versao: bad_req.into(),
6785                    restart: RestartPolicy::Permanent,
6786                }],
6787                ..SupervisorSpec::default()
6788            };
6789            let err = s.validate().unwrap_err();
6790            assert!(
6791                matches!(
6792                    err,
6793                    SupervisorError::EmptyChildVersion { .. }
6794                        | SupervisorError::ChildVersaoInvalid { .. }
6795                ),
6796                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
6797                 via the versao-requirement gate: got {err:?}",
6798            );
6799            let c = ChildSpec {
6800                caixa: "worker".into(),
6801                versao: bad_req.into(),
6802                restart: RestartPolicy::Permanent,
6803            };
6804            assert!(
6805                crate::render::require_valid_versao_requirement(
6806                    c.versao_requirement(),
6807                    || (),
6808                    |_reason| (),
6809                )
6810                .is_err(),
6811                "require_valid_versao_requirement must reject the accessor-projected \
6812                 :children :versao {bad_req:?}",
6813            );
6814        }
6815    }
6816
6817    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
6818    //
6819    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
6820    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
6821    // already project the `String`-carry `(caixa, versao)` fields; the
6822    // `Copy`-composite-enum `restart` field is the third and final axis).
6823    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
6824    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
6825    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
6826    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
6827    // strategy scalar accessor — same "one typed dispatch on the substrate
6828    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
6829    // extended onto the M2 supervisor-slot per-`:children` restart-decision
6830    // axis. The pin below covers the accessor's byte-equal projection
6831    // against the raw field access across every variant in the closed
6832    // accept-set (`Permanent`, `Transient`, `Temporary`).
6833
6834    #[test]
6835    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
6836        // The canonical per-`:children` restart-decision-policy-scalar
6837        // pin: [`ChildSpec::restart`] must return the `:children :restart`
6838        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
6839        // typed slot's own [`RestartPolicy`] storage across every variant
6840        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
6841        // Pins against a future silent detour that re-derived the policy
6842        // from a peer axis (an accidental fallback to
6843        // `if is_supervisor_child { Permanent } else { Temporary }` that
6844        // collapsed the child's kind axis into the restart discriminator),
6845        // a variant remap the operator authors on one consumer without the
6846        // other, or a stale-derive detour that substituted
6847        // [`RestartPolicy::default`] when the field held any explicit
6848        // variant (which would silently collapse the distinction between
6849        // "author explicitly declared `:restart Permanent`" and "author
6850        // omitted the slot and inherited the default" the future
6851        // per-cluster restart-decision override slot depends on).
6852        //
6853        // Peer of the sibling per-`:supervisor`
6854        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6855        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
6856        // axis and the M3
6857        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
6858        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
6859        // — same "the substrate-primitive accessor must byte-equal the raw
6860        // field access verbatim across every author-declared value"
6861        // discipline extended onto the M2 supervisor-slot per-`:children`
6862        // restart-decision-policy axis, closing the last unlifted axis on
6863        // the per-`:children` [`ChildSpec`] type.
6864        for restart in [
6865            RestartPolicy::Permanent,
6866            RestartPolicy::Transient,
6867            RestartPolicy::Temporary,
6868        ] {
6869            let c = ChildSpec {
6870                caixa: "worker".into(),
6871                versao: "^0.1".into(),
6872                restart,
6873            };
6874            assert_eq!(
6875                c.restart(),
6876                restart,
6877                "ChildSpec::restart must return :children :restart \
6878                 verbatim (got {:?}, expected {restart:?})",
6879                c.restart(),
6880            );
6881            assert_eq!(
6882                c.restart(),
6883                c.restart,
6884                "ChildSpec::restart accessor and .restart field access \
6885                 must byte-equal — the accessor is the substrate-primitive \
6886                 typed dispatch every downstream per-child restart-\
6887                 decision consumer must route through",
6888            );
6889        }
6890    }
6891
6892    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
6893    //
6894    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
6895    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
6896    // distribution-strategy accessor discipline onto the M2 supervisor-slot
6897    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
6898    // scalar axis. The two pins below cover (1) the accessor's byte-equal
6899    // projection against the raw field access across every variant in the
6900    // closed accept-set, and (2) the two-consumer coherence between the
6901    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
6902    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
6903    // carrier's `estrategia:` field — peer of the sibling M3
6904    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
6905    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
6906    // pair on the per-`:placement` distribution-strategy axis.
6907
6908    #[test]
6909    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
6910        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
6911        // pin: [`SupervisorSpec::estrategia`] must return the
6912        // `:supervisor :estrategia` field verbatim as a
6913        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
6914        // [`RestartStrategy`] storage across every variant in the closed
6915        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
6916        // `SimpleOneForOne`). Pins against a future silent detour that
6917        // re-derived the strategy from a peer axis (an accidental
6918        // fallback to `if children.is_empty() { SimpleOneForOne } else {
6919        // OneForOne }` collapse that read the children-count axis into
6920        // the strategy discriminator), a variant remap the operator
6921        // authors on one consumer without the other, or a stale-derive
6922        // detour that substituted [`RestartStrategy::default`] when the
6923        // field held any explicit variant (which would silently collapse
6924        // the distinction between "author explicitly declared
6925        // `:estrategia OneForOne`" and "author omitted the slot and
6926        // inherited the default" the future per-cluster strategy override
6927        // slot depends on). Peer of the sibling M3
6928        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
6929        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
6930        // axis — same "the substrate-primitive accessor must byte-equal
6931        // the raw field access verbatim across every author-declared
6932        // value" discipline extended onto the M2 supervisor-slot
6933        // per-`:supervisor` sibling-restart-strategy axis.
6934        for &estrategia in RestartStrategy::ALL {
6935            // `SimpleOneForOne` requires `children.is_empty()`; the peer
6936            // three strategies require a non-empty static children list.
6937            // Build each shape coherently so the pin's fixture would
6938            // itself pass [`SupervisorSpec::validate`] once fed through
6939            // the sibling coherence pin below — the byte-equal projection
6940            // asserted here is a strictly weaker property (a `Copy` field
6941            // read) that does not depend on `validate` running, but
6942            // keeping the fixture validate-clean means a future extension
6943            // of the pin to exercise `validate` end-to-end does not have
6944            // to re-author the children shape.
6945            //
6946            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6947            // shape partition through the [`gen_platform::IsVariant`]
6948            // derive-generated
6949            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
6950            // than the raw `matches!(estrategia, RestartStrategy::
6951            // SimpleOneForOne)` open-coded pattern-match — same closed-
6952            // set-typed-enum arm-discriminator dispatch discipline the
6953            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
6954            // convergence (915a934) extended onto its two paired positive
6955            // / negated `matches!` sites and the peer
6956            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6957            // predicate convergence (766ec63) extended onto the M3 mesh-
6958            // slot per-`:placement` distribution-strategy discriminator
6959            // axis. See the sibling `round_trip_all_strategies` and the
6960            // peer `manifest::tests::
6961            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6962            // fixture for the two peer sites the same lift closes on.
6963            let children = if estrategia.is_simple_one_for_one() {
6964                Vec::new()
6965            } else {
6966                vec![ChildSpec {
6967                    caixa: "worker".into(),
6968                    versao: "^0.1".into(),
6969                    restart: RestartPolicy::Permanent,
6970                }]
6971            };
6972            let s = SupervisorSpec {
6973                estrategia,
6974                children,
6975                ..SupervisorSpec::default()
6976            };
6977            assert_eq!(
6978                s.estrategia(),
6979                estrategia,
6980                "SupervisorSpec::estrategia must return :supervisor :estrategia \
6981                 verbatim (got {:?}, expected {estrategia:?})",
6982                s.estrategia(),
6983            );
6984            assert_eq!(
6985                s.estrategia(),
6986                s.estrategia,
6987                "SupervisorSpec::estrategia accessor and .estrategia field \
6988                 access must byte-equal — the accessor is the substrate-\
6989                 primitive typed dispatch every downstream sibling-restart-\
6990                 strategy consumer must route through",
6991            );
6992        }
6993    }
6994
6995    #[test]
6996    fn validate_reads_through_lifted_estrategia_accessor() {
6997        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
6998        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
6999        // dispatch (which reads through [`SupervisorSpec::estrategia`]
7000        // to fan across the strategy-arm shape-gate cascades) and the
7001        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
7002        // error carrier's `estrategia:` field (which reads through
7003        // [`SupervisorSpec::estrategia`] to name the strategy the empty
7004        // `:children` list was declared against) must both key off the
7005        // lifted accessor, so any future rebrand on the typed slot's
7006        // reader shape lands at exactly one place. Pins the two-site
7007        // coherence by exercising the `NoChildren` error surface end-to-
7008        // end across every non-`SimpleOneForOne` variant and asserting
7009        // the surfaced `estrategia:` field byte-equals the accessor's
7010        // return. Peer of the sibling M3
7011        // `validate_placement_reads_through_lifted_estrategia_accessor`
7012        // (921fe1b) three-consumer coherence pin on the per-`:placement`
7013        // distribution-strategy axis.
7014        for estrategia in [
7015            RestartStrategy::OneForOne,
7016            RestartStrategy::OneForAll,
7017            RestartStrategy::RestForOne,
7018        ] {
7019            let s = SupervisorSpec {
7020                estrategia,
7021                children: Vec::new(),
7022                ..SupervisorSpec::default()
7023            };
7024            let err = s.validate().unwrap_err();
7025            match err {
7026                SupervisorError::NoChildren { estrategia: e } => {
7027                    assert_eq!(
7028                        e,
7029                        s.estrategia(),
7030                        "NoChildren.estrategia must byte-equal \
7031                         SupervisorSpec::estrategia() — the empty-`:children` \
7032                         refusal reads through the lifted accessor",
7033                    );
7034                    assert_eq!(
7035                        e, estrategia,
7036                        "NoChildren.estrategia must carry the author-declared \
7037                         :supervisor :estrategia variant verbatim (got {e:?}, \
7038                         expected {estrategia:?})",
7039                    );
7040                }
7041                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
7042            }
7043        }
7044    }
7045
7046    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
7047    //
7048    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
7049    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
7050    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
7051    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
7052    // The two pins below cover (1) the accessor's byte-equal projection
7053    // against the raw field access across every representative value in
7054    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
7055    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
7056    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
7057    // zero-floor / cap composition — the validate gate and the accessor
7058    // must route through the same substrate-primitive typed dispatch, so
7059    // any future silent detour that had the accessor perform a
7060    // bounds-collapsing clamp would fail here at caixa-core build time.
7061    // Peer of the sibling M3
7062    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7063    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
7064
7065    #[test]
7066    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
7067        // The canonical per-`:supervisor` restart-budget-count scalar pin:
7068        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
7069        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
7070        // typed slot's own `u32` storage, byte-equal to the raw field
7071        // access across every representative value in the accept-set —
7072        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
7073        // accept-set the surrounding [`SupervisorSpec::validate`] gate
7074        // carves out on the sibling `ZeroMaxRestarts` refusal),
7075        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
7076        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
7077        // (a past-the-guard sentinel that pins the accessor doesn't
7078        // perform a silent bounds-collapse into `1` on the zero arm —
7079        // validate rejects zero but the accessor must ship the raw slot
7080        // verbatim so a validate-time gate regression surfaces at the
7081        // emit boundary rather than being silently absorbed), `u32::MAX`
7082        // (a past-the-guard sentinel that pins the accessor doesn't
7083        // perform a silent bounds-collapse through
7084        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
7085        //
7086        // Peer of the sibling M3
7087        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7088        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
7089        // required-scalar axis — same "the substrate-primitive accessor
7090        // must byte-equal the raw field access verbatim across every
7091        // value in the `u32` accept-set" discipline extended onto the M2
7092        // supervisor-slot per-`:supervisor` restart-budget-count axis.
7093        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
7094            let s = SupervisorSpec {
7095                max_restarts,
7096                ..SupervisorSpec::default()
7097            };
7098            assert_eq!(
7099                s.max_restarts(),
7100                max_restarts,
7101                "SupervisorSpec::max_restarts must return :supervisor \
7102                 :max-restarts verbatim (got {}, expected {max_restarts})",
7103                s.max_restarts(),
7104            );
7105            assert_eq!(
7106                s.max_restarts(),
7107                s.max_restarts,
7108                "SupervisorSpec::max_restarts accessor and .max_restarts \
7109                 field access must byte-equal — the accessor is the \
7110                 substrate-primitive typed dispatch every downstream \
7111                 restart-budget-count consumer must route through",
7112            );
7113        }
7114    }
7115
7116    #[test]
7117    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
7118        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
7119        // zero-floor + upper-cap bracket must key off
7120        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
7121        // field access. Structurally: a `SupervisorSpec { max_restarts:
7122        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
7123        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7124        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
7125        // (with the offending count carried verbatim from the accessor
7126        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
7127        // lower boundary of the accept-set) plus a `SupervisorSpec {
7128        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
7129        // boundary) must pass validate. The four together jointly pin the
7130        // accessor + validate-gate composition: any future silent detour
7131        // that had the accessor return a fresh `1` on the zero arm (a
7132        // `.max_restarts().max(1)` collapse) would silently absorb the
7133        // `ZeroMaxRestarts` refusal at the accessor boundary and the
7134        // validate gate would accept a struct-literal `SupervisorSpec {
7135        // max_restarts: 0, .. }` — the composition pin catches that at
7136        // caixa-core build time.
7137        //
7138        // Peer of the sibling M3
7139        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
7140        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
7141        // composition axis — same "the validate / shape-gate predicate
7142        // must route through the substrate-primitive typed dispatch"
7143        // discipline extended onto the peer M2 supervisor-slot
7144        // required-`u32` composition axis.
7145        let child = ChildSpec {
7146            caixa: "worker".into(),
7147            versao: "^0.1".into(),
7148            restart: RestartPolicy::Permanent,
7149        };
7150        // Zero-floor arm.
7151        let s = SupervisorSpec {
7152            max_restarts: 0,
7153            children: vec![child.clone()],
7154            ..SupervisorSpec::default()
7155        };
7156        assert_eq!(
7157            s.validate().unwrap_err(),
7158            SupervisorError::ZeroMaxRestarts,
7159            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
7160             — the accessor and the validate gate must route through the \
7161             same substrate-primitive typed dispatch on the zero-floor arm",
7162        );
7163        // Cap arm — the surfaced `max_restarts:` field must byte-equal
7164        // the accessor's return so a future rebrand on the accessor
7165        // lands in the diagnostic without a coordinated rewrite.
7166        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
7167        let s = SupervisorSpec {
7168            max_restarts: over_cap,
7169            children: vec![child.clone()],
7170            ..SupervisorSpec::default()
7171        };
7172        match s.validate().unwrap_err() {
7173            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
7174                assert_eq!(
7175                    max_restarts,
7176                    s.max_restarts(),
7177                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
7178                     SupervisorSpec::max_restarts() — the cap-arm refusal \
7179                     reads through the lifted accessor",
7180                );
7181                assert_eq!(
7182                    max_restarts, over_cap,
7183                    "MaxRestartsExceedsCap.max_restarts must carry the \
7184                     author-declared :supervisor :max-restarts value \
7185                     verbatim (got {max_restarts}, expected {over_cap})",
7186                );
7187            }
7188            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
7189        }
7190        // Lower + upper accept-set boundaries.
7191        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
7192            let s = SupervisorSpec {
7193                max_restarts,
7194                children: vec![child.clone()],
7195                ..SupervisorSpec::default()
7196            };
7197            assert!(
7198                s.validate().is_ok(),
7199                "validate must accept max_restarts == {max_restarts} \
7200                 (an accept-set boundary of \
7201                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
7202            );
7203        }
7204    }
7205
7206    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
7207    //
7208    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
7209    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
7210    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
7211    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
7212    // supervisor-slot per-`:supervisor` restart-intensity-denominator
7213    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
7214    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
7215    // per-`:supervisor` scalar-value axis. The three pins below cover
7216    // (1) the accessor's byte-equal projection against the raw field
7217    // access across every representative value in the `Option<Duration>`
7218    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
7219    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
7220    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
7221    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
7222    // `if let Some(w) = self.restart_window() { … }` bracket-arm
7223    // composition — the validate gate and the accessor must route through
7224    // the same substrate-primitive typed dispatch, so any future silent
7225    // detour that had the accessor perform a bounds-collapsing clamp
7226    // would fail here at caixa-core build time, and (3) the accessor's
7227    // by-copy idempotence pin — the returned `Option<Duration>` must
7228    // outlive `&self` and two successive calls must return byte-equal
7229    // values. Peer of the sibling M2
7230    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7231    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
7232    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7233    // (7073d0f) pin on the per-`:politicas :timeout` axis.
7234
7235    #[test]
7236    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
7237        // The canonical per-`:supervisor` restart-intensity-denominator
7238        // scalar pin: [`SupervisorSpec::restart_window`] must return the
7239        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
7240        // `Option<Duration>`, `Copy`-projected from the typed slot's own
7241        // `Option<Duration>` storage, byte-equal to the raw field access
7242        // across every representative value in the accept-set — `None`
7243        // (the "never reset — every restart across the supervisor's
7244        // lifetime counts against the sibling `:max-restarts` budget"
7245        // sentinel the field's own docstring names and the peer
7246        // `validate_accepts_none_restart_window` pin locks in on the
7247        // [`SupervisorSpec::validate`] entry-side),
7248        // `Some(Duration::from_millis(1))` (the structural minimum a
7249        // validated `:restart-window` may carry, the integer-millisecond
7250        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
7251        // everything sub-ms; `Duration::ZERO` is separately rejected by
7252        // [`SupervisorError::RestartWindowZero`]),
7253        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
7254        // surrounding [`SupervisorSpec::validate`] gate carves out on the
7255        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
7256        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
7257        // accessor doesn't perform a silent bounds-collapse into `None` on
7258        // the zero-Duration arm — validate rejects zero but the accessor
7259        // must ship the raw slot verbatim so a validate-time gate
7260        // regression surfaces at the emit boundary rather than being
7261        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
7262        // sentinel that pins the accessor doesn't perform a silent
7263        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
7264        // return path).
7265        //
7266        // Peer of the sibling M2
7267        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7268        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
7269        // sibling M3
7270        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7271        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
7272        // substrate-primitive accessor must byte-equal the raw field
7273        // access verbatim across every value in the `Option<Duration>`
7274        // accept-set" discipline extended onto the M2 supervisor-slot
7275        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
7276        // silent detour that re-derived the restart-window from a peer
7277        // axis (an accidental `.max_restarts.into()` collapse that read
7278        // the restart-budget-count as a duration — the two axes serve
7279        // different halves of the `MaxIntensity / Period` restart-
7280        // intensity ratio, and confusing them silently inverts the
7281        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
7282        // "zero means never reset" collapse (the canonical
7283        // `Option<Duration>` → `Duration` collapse footgun the
7284        // [`SupervisorError::RestartWindowZero`] validate arm guards on
7285        // the peer zero-floor axis; a zero period either trips on the
7286        // first failure or never trips depending on operator
7287        // interpretation, neither of which is the author's "never reset"
7288        // intent that `None` expresses structurally), or a per-arm
7289        // variant swap that landed on one consumer without the other.
7290        for restart_window in [
7291            None,
7292            Some(Duration::from_millis(1)),
7293            Some(SUPERVISOR_RESTART_WINDOW_MAX),
7294            Some(Duration::ZERO),
7295            Some(Duration::MAX),
7296        ] {
7297            let s = SupervisorSpec {
7298                restart_window,
7299                ..SupervisorSpec::default()
7300            };
7301            assert_eq!(
7302                s.restart_window(),
7303                restart_window,
7304                "SupervisorSpec::restart_window must return :supervisor \
7305                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
7306                s.restart_window(),
7307            );
7308            assert_eq!(
7309                s.restart_window(),
7310                s.restart_window,
7311                "SupervisorSpec::restart_window accessor and \
7312                 .restart_window field access must byte-equal — the \
7313                 accessor is the substrate-primitive typed dispatch every \
7314                 downstream restart-intensity-denominator consumer must \
7315                 route through",
7316            );
7317        }
7318    }
7319
7320    #[test]
7321    fn validate_restart_window_bracket_arm_routes_through_accessor() {
7322        // Composition pin: [`SupervisorSpec::validate`]'s
7323        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
7324        // zero-floor + integer-millisecond canonical-form + upper-cap
7325        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
7326        // the raw `.restart_window` field access. Structurally: a
7327        // `SupervisorSpec { restart_window: None, .. }` must pass the
7328        // arm gate structurally (the `if let Some(_)` shape returns
7329        // early on the `None` arm — the accessor and the validate gate
7330        // must agree on `None → skip the bracket cascade` so an authored
7331        // `:restart-window ()` structurally routes through the "never
7332        // reset" sentinel path), a `SupervisorSpec { restart_window:
7333        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
7334        // refusal exactly, a `SupervisorSpec { restart_window:
7335        // Some(Duration::from_micros(1500)), .. }` must surface the
7336        // `RestartWindowNotCanonical` refusal exactly (with the offending
7337        // duration carried verbatim from the accessor return), a
7338        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
7339        // + Duration::from_millis(1)), .. }` must surface the
7340        // `RestartWindowExceedsCap` refusal exactly (with the offending
7341        // duration carried verbatim from the accessor return), and a
7342        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
7343        // .. }` (the lower boundary of the accept-set) plus a
7344        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7345        // .. }` (the upper boundary) must pass validate. The six together
7346        // jointly pin the accessor + validate-gate composition: any future
7347        // silent detour that had the accessor return a fresh `None` on any
7348        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
7349        // collapse) would silently absorb the `RestartWindowZero` refusal
7350        // at the accessor boundary and the validate gate would accept a
7351        // struct-literal `SupervisorSpec { restart_window:
7352        // Some(Duration::ZERO), .. }` — the composition pin catches that
7353        // at caixa-core build time.
7354        //
7355        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
7356        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
7357        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
7358        // accessor-composition pin on the per-`:politicas :timeout` axis —
7359        // same "the validate / shape-gate predicate must route through
7360        // the substrate-primitive typed dispatch" discipline extended
7361        // onto the peer M2 supervisor-slot optional-`Duration` axis.
7362        let child = ChildSpec {
7363            caixa: "worker".into(),
7364            versao: "^0.1".into(),
7365            restart: RestartPolicy::Permanent,
7366        };
7367        // None arm — must not surface any :restart-window-shaped refusal;
7368        // the `if let Some(_)` bracket returns early on `None` structurally.
7369        let s = SupervisorSpec {
7370            restart_window: None,
7371            children: vec![child.clone()],
7372            ..SupervisorSpec::default()
7373        };
7374        assert!(
7375            s.validate().is_ok(),
7376            "validate must accept restart_window: None (the never-reset \
7377             sentinel) — the `if let Some(_)` bracket returns early on \
7378             the None arm and the accessor must agree",
7379        );
7380        // Zero-floor arm.
7381        let s = SupervisorSpec {
7382            restart_window: Some(Duration::ZERO),
7383            children: vec![child.clone()],
7384            ..SupervisorSpec::default()
7385        };
7386        assert_eq!(
7387            s.validate().unwrap_err(),
7388            SupervisorError::RestartWindowZero,
7389            "validate must reject restart_window == Some(Duration::ZERO) \
7390             with RestartWindowZero — the accessor and the validate gate \
7391             must route through the same substrate-primitive typed \
7392             dispatch on the zero-floor arm",
7393        );
7394        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
7395        // byte-equal the accessor's return so a future rebrand on the
7396        // accessor lands in the diagnostic without a coordinated rewrite.
7397        let sub_ms = Duration::from_micros(1500);
7398        let s = SupervisorSpec {
7399            restart_window: Some(sub_ms),
7400            children: vec![child.clone()],
7401            ..SupervisorSpec::default()
7402        };
7403        match s.validate().unwrap_err() {
7404            SupervisorError::RestartWindowNotCanonical { window } => {
7405                assert_eq!(
7406                    Some(window),
7407                    s.restart_window(),
7408                    "RestartWindowNotCanonical.window must byte-equal \
7409                     SupervisorSpec::restart_window().unwrap() — the \
7410                     non-canonical-arm refusal reads through the lifted \
7411                     accessor",
7412                );
7413                assert_eq!(
7414                    window, sub_ms,
7415                    "RestartWindowNotCanonical.window must carry the \
7416                     author-declared :supervisor :restart-window value \
7417                     verbatim (got {window:?}, expected {sub_ms:?})",
7418                );
7419            }
7420            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7421        }
7422        // Cap arm — the surfaced `window:` field must byte-equal the
7423        // accessor's return.
7424        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
7425        let s = SupervisorSpec {
7426            restart_window: Some(over_cap),
7427            children: vec![child.clone()],
7428            ..SupervisorSpec::default()
7429        };
7430        match s.validate().unwrap_err() {
7431            SupervisorError::RestartWindowExceedsCap { window } => {
7432                assert_eq!(
7433                    Some(window),
7434                    s.restart_window(),
7435                    "RestartWindowExceedsCap.window must byte-equal \
7436                     SupervisorSpec::restart_window().unwrap() — the \
7437                     cap-arm refusal reads through the lifted accessor",
7438                );
7439                assert_eq!(
7440                    window, over_cap,
7441                    "RestartWindowExceedsCap.window must carry the \
7442                     author-declared :supervisor :restart-window value \
7443                     verbatim (got {window:?}, expected {over_cap:?})",
7444                );
7445            }
7446            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
7447        }
7448        // Lower + upper accept-set boundaries.
7449        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
7450            let s = SupervisorSpec {
7451                restart_window: Some(restart_window),
7452                children: vec![child.clone()],
7453                ..SupervisorSpec::default()
7454            };
7455            assert!(
7456                s.validate().is_ok(),
7457                "validate must accept restart_window == Some({restart_window:?}) \
7458                 (an accept-set boundary of \
7459                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
7460            );
7461        }
7462    }
7463
7464    #[test]
7465    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
7466        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
7467        // `Option<Duration>` by copy — `Duration` is `Copy` (so
7468        // `Option<Duration>` is `Copy`) and the accessor must return by
7469        // value, not by reference. Peer of the sibling M2
7470        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
7471        // per-`:limits :wall-clock` axis and the sibling M3
7472        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
7473        // per-`:politicas :timeout` axis, extended onto the peer M2
7474        // supervisor-slot `Option<Duration>` copy-invariant shape — the
7475        // accessor's returned `Option<Duration>` must outlive `&self`
7476        // (multiple calls must return equal values from a dropped-`&self`
7477        // copy, since the returned Option carries no borrow), and calling
7478        // the accessor twice on the same SupervisorSpec must yield the
7479        // same `Option<Duration>` verbatim (idempotent, no side effects
7480        // on `&self`).
7481        //
7482        // Pins against a future silent detour that returned
7483        // `Option<&Duration>` (which would type-check but silently break
7484        // every downstream caller — the future wasm-operator's
7485        // per-supervisor restart-intensity counter consumes `Duration` by
7486        // value and `&Duration` would fold to a detached copy at the call
7487        // site), an accidental `Option::as_ref()` projection
7488        // (`self.restart_window.as_ref()` would also type-check but
7489        // return `Option<&Duration>`), or a one-arm-only accessor that
7490        // reads `Some(*w)` in the Some arm but reads a fresh
7491        // `Default::default()` (which would collapse to `Duration::ZERO`,
7492        // not `None`) in the None arm — a footgun the
7493        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
7494        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
7495        // requires `Period > 0` and `None` structurally expresses "never
7496        // reset" instead.
7497        for restart_window in [
7498            None,
7499            Some(Duration::from_millis(1)),
7500            Some(Duration::from_secs(60)),
7501            Some(SUPERVISOR_RESTART_WINDOW_MAX),
7502        ] {
7503            let s = SupervisorSpec {
7504                restart_window,
7505                ..SupervisorSpec::default()
7506            };
7507            let first = s.restart_window();
7508            let second = s.restart_window();
7509            assert_eq!(
7510                first, second,
7511                "SupervisorSpec::restart_window must be idempotent — two \
7512                 successive calls on the same &self must return the \
7513                 same Option<Duration>",
7514            );
7515            assert_eq!(
7516                first, restart_window,
7517                "SupervisorSpec::restart_window must return :supervisor \
7518                 :restart-window verbatim by copy — got {first:?}, \
7519                 expected {restart_window:?}",
7520            );
7521        }
7522    }
7523
7524    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
7525    //
7526    // The [`SupervisorSpec::children`] accessor lift is the seed of the
7527    // slice-return (`&[T]`) accessor discipline on the substrate — the four
7528    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
7529    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
7530    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
7531    // access at the time of this seed, and inherit this pin family's
7532    // discipline as future compounding runs migrate their consumers. The
7533    // three pins below cover (1) the accessor's byte-equal projection
7534    // against the raw field access across the empty / singleton / cohort
7535    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
7536    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
7537    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
7538    // consumer routing through the accessor on both arms, and (3) the
7539    // per-child validate loop's traversal reading the same slice-view the
7540    // accessor projects. Peer of the sibling M2
7541    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7542    // two-consumer coherence pin on the per-`:supervisor`
7543    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
7544    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
7545
7546    #[test]
7547    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
7548        // The canonical per-`:supervisor` static-child-list scalar-shape
7549        // pin: [`SupervisorSpec::children`] must return the `:supervisor
7550        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
7551        // slice-view over the same backing buffer the raw
7552        // `self.children.as_slice()` field access borrows from, byte-
7553        // equal across every representative fixture in the accept-set —
7554        // the empty slice (the `SimpleOneForOne`-arm sentinel),
7555        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
7556        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
7557        // with the peer three restart-policy variants in play).
7558        //
7559        // Pins against a future silent detour that returned
7560        // `&Vec<ChildSpec>` (which would type-check but leak the
7561        // storage-side `Vec`'s grow/push/reserve surface no consumer of
7562        // the typed view reaches for), a fresh-allocated
7563        // `Vec<ChildSpec>` copy (which would type-check via a coercion
7564        // but silently break every downstream caller that relied on the
7565        // slice sharing the backing buffer's identity), or an
7566        // out-of-order or length-drifted projection (which would silently
7567        // split the per-child validate loop's traversal input from the
7568        // paired partition-dispatch `.is_empty()` probe's input).
7569        //
7570        // Peer of the sibling
7571        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7572        // (eafb619) `Copy`-composite-enum byte-equal pin on the
7573        // per-`:supervisor` sibling-restart-strategy axis, extended onto
7574        // the per-`:supervisor` static-child-list `Vec`-carry axis.
7575        let fixtures: Vec<Vec<ChildSpec>> = vec![
7576            Vec::new(),
7577            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7578            vec![
7579                child("worker", "^0.1", RestartPolicy::Permanent),
7580                child("cache-server", "^0.1", RestartPolicy::Transient),
7581            ],
7582            vec![
7583                child("worker", "^0.1", RestartPolicy::Permanent),
7584                child("cache-server", "^0.1", RestartPolicy::Transient),
7585                child("scratch-job", "^0.1", RestartPolicy::Temporary),
7586            ],
7587        ];
7588        for children in fixtures {
7589            let s = SupervisorSpec {
7590                children: children.clone(),
7591                ..SupervisorSpec::default()
7592            };
7593            assert_eq!(
7594                s.children(),
7595                children.as_slice(),
7596                "SupervisorSpec::children must return :supervisor \
7597                 :children verbatim (got {:?}, expected {:?})",
7598                s.children(),
7599                children.as_slice(),
7600            );
7601            assert_eq!(
7602                s.children(),
7603                s.children.as_slice(),
7604                "SupervisorSpec::children accessor and \
7605                 .children.as_slice() field access must byte-equal — \
7606                 the accessor is the substrate-primitive typed \
7607                 dispatch every downstream static-child-list consumer \
7608                 must route through",
7609            );
7610            assert_eq!(
7611                s.children().len(),
7612                s.children.len(),
7613                "SupervisorSpec::children().len() must byte-equal \
7614                 self.children.len() — a length-drift would silently \
7615                 split the paired partition-dispatch `.is_empty()` \
7616                 probe input from the per-child validate loop's \
7617                 traversal input",
7618            );
7619        }
7620    }
7621
7622    #[test]
7623    fn validate_reads_through_lifted_children_accessor() {
7624        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
7625        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
7626        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
7627        // when the accessor projects a non-empty slice under a
7628        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
7629        // `self.children().is_empty()` refusal probe (which must trip
7630        // [`SupervisorError::NoChildren`] when the accessor projects the
7631        // empty slice under any peer estrategia), and the per-child
7632        // validate loop's `for child in self.children()` traversal
7633        // (which must reach every entry in the same order the accessor
7634        // projects) must all key off the lifted accessor, so any future
7635        // rebrand on the typed slot's reader shape lands at exactly one
7636        // place. Pins the three-site coherence by exercising each
7637        // production consumer end-to-end: (1) the
7638        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
7639        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
7640        // refusal under the empty slice + non-`SimpleOneForOne`
7641        // estrategia across every peer variant, and (3) the per-child
7642        // duplicate-detection surface fires on the second entry of a
7643        // two-child cohort that shares a `:caixa` name (which requires
7644        // the loop to reach both entries — a first-entry-only projection
7645        // would silently pass since the dedup HashSet has room for the
7646        // first insert).
7647        //
7648        // Peer of the sibling M2
7649        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7650        // two-consumer coherence pin on the per-`:supervisor`
7651        // sibling-restart-strategy axis, extended onto the
7652        // per-`:supervisor` static-child-list `Vec`-carry axis.
7653
7654        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
7655        // `SimpleOneForOne` estrategia must trip
7656        // `SimpleOneForOneWithStaticChildren`.
7657        let s = SupervisorSpec {
7658            estrategia: RestartStrategy::SimpleOneForOne,
7659            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7660            ..SupervisorSpec::default()
7661        };
7662        assert_eq!(
7663            s.validate().unwrap_err(),
7664            SupervisorError::SimpleOneForOneWithStaticChildren,
7665            "SimpleOneForOne + non-empty children must trip \
7666             SimpleOneForOneWithStaticChildren — the accessor projects \
7667             a non-empty slice, and the SimpleOneForOne-arm refusal \
7668             probe reads through the lifted accessor",
7669        );
7670        assert!(
7671            !s.children().is_empty(),
7672            "the SimpleOneForOne-arm refusal input must be a non-empty \
7673             slice per the accessor's projection",
7674        );
7675
7676        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
7677        // under any peer estrategia must trip `NoChildren`.
7678        for estrategia in [
7679            RestartStrategy::OneForOne,
7680            RestartStrategy::OneForAll,
7681            RestartStrategy::RestForOne,
7682        ] {
7683            let s = SupervisorSpec {
7684                estrategia,
7685                children: Vec::new(),
7686                ..SupervisorSpec::default()
7687            };
7688            match s.validate().unwrap_err() {
7689                SupervisorError::NoChildren { estrategia: e } => {
7690                    assert_eq!(
7691                        e, estrategia,
7692                        "NoChildren.estrategia must carry the author-\
7693                         declared :supervisor :estrategia variant \
7694                         verbatim (got {e:?}, expected {estrategia:?})",
7695                    );
7696                }
7697                other => panic!(
7698                    "expected NoChildren, got {other:?} for \
7699                     estrategia={estrategia:?}"
7700                ),
7701            }
7702            assert!(
7703                s.children().is_empty(),
7704                "the non-SimpleOneForOne-arm refusal input must be the \
7705                 empty slice per the accessor's projection",
7706            );
7707        }
7708
7709        // (3) Per-child validate loop: a two-child cohort that shares a
7710        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
7711        // reach both entries through the accessor.
7712        let s = SupervisorSpec {
7713            estrategia: RestartStrategy::OneForOne,
7714            children: vec![
7715                child("worker", "^0.1", RestartPolicy::Permanent),
7716                child("worker", "^0.2", RestartPolicy::Transient),
7717            ],
7718            ..SupervisorSpec::default()
7719        };
7720        match s.validate().unwrap_err() {
7721            SupervisorError::DuplicateChildCaixa { caixa } => {
7722                assert_eq!(
7723                    caixa, "worker",
7724                    "DuplicateChildCaixa.caixa must carry the shared \
7725                     child `:caixa` name verbatim",
7726                );
7727            }
7728            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
7729        }
7730        assert_eq!(
7731            s.children().len(),
7732            2,
7733            "the per-child validate loop's traversal input must be a \
7734             two-element slice per the accessor's projection",
7735        );
7736    }
7737
7738    // Shared helper for the M2 per-`:children` per-slot-gate ≡
7739    // `validate` equivalence pins: builds an `OneForOne`-estrategia
7740    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
7741    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
7742    // bracket all pass cleanly so the sole failing surface is the
7743    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
7744    // pins the two-altitude equivalence on the paired probe.
7745    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
7746        let s = SupervisorSpec {
7747            estrategia: RestartStrategy::OneForOne,
7748            children,
7749            ..SupervisorSpec::default()
7750        };
7751        let via_gate = s.validate_children().unwrap_err();
7752        let via_validate = s.validate().unwrap_err();
7753        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
7754        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
7755        assert_eq!(
7756            via_gate, via_validate,
7757            "per-slot gate ≡ validate() must discriminate the same \
7758             refusal shape",
7759        );
7760    }
7761
7762    #[test]
7763    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
7764        // Fail-before-pass-after equivalence pin on the M2
7765        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
7766        // convergence — sibling of the M3 mesh-slot
7767        // `validate_membros_*` / `validate_contratos_*` /
7768        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
7769        // peer per-entry axes. Sweeps four of the five refusal shapes
7770        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
7771        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
7772        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
7773        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
7774        // duplicate-`:caixa` fan-out. Companion pin
7775        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
7776        // covers `ChildVersaoInvalid` (whose parser-owned reason string
7777        // needs pattern-matching, not equality) and the clean-pass
7778        // canonical fixture; together the two pins guarantee the
7779        // per-slot gate and `validate` discriminate the same set on
7780        // every per-child-covered input.
7781        assert_validate_children_matches_gate(
7782            vec![child("", "^0.1", RestartPolicy::Permanent)],
7783            &SupervisorError::EmptyChildName,
7784        );
7785        assert_validate_children_matches_gate(
7786            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
7787            &SupervisorError::ChildCaixaInvalid {
7788                caixa: "Worker".into(),
7789                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
7790            },
7791        );
7792        assert_validate_children_matches_gate(
7793            vec![child("worker", "", RestartPolicy::Permanent)],
7794            &SupervisorError::EmptyChildVersion {
7795                caixa: "worker".into(),
7796            },
7797        );
7798        assert_validate_children_matches_gate(
7799            vec![
7800                child("worker", "^0.1", RestartPolicy::Permanent),
7801                child("worker", "^0.2", RestartPolicy::Transient),
7802            ],
7803            &SupervisorError::DuplicateChildCaixa {
7804                caixa: "worker".into(),
7805            },
7806        );
7807    }
7808
7809    #[test]
7810    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
7811        // Second half of the two-altitude equivalence pin — covers the
7812        // one refusal shape whose reason string is parser-owned
7813        // (`ChildVersaoInvalid`, whose reason comes from the shared
7814        // [`crate::version::parse_requirement`] impl and may drift) and
7815        // the clean-pass canonical fixture. Sibling pin
7816        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
7817        // covers the four equality-comparable refusal shapes.
7818        let s_bad_versao = SupervisorSpec {
7819            estrategia: RestartStrategy::OneForOne,
7820            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
7821            ..SupervisorSpec::default()
7822        };
7823        let via_gate = s_bad_versao.validate_children().unwrap_err();
7824        let via_validate = s_bad_versao.validate().unwrap_err();
7825        match (&via_gate, &via_validate) {
7826            (
7827                SupervisorError::ChildVersaoInvalid {
7828                    caixa: cg,
7829                    versao: vg,
7830                    ..
7831                },
7832                SupervisorError::ChildVersaoInvalid {
7833                    caixa: cv,
7834                    versao: vv,
7835                    ..
7836                },
7837            ) => {
7838                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
7839                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
7840                assert_eq!(cv, "worker", "validate() :caixa carrier");
7841                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
7842            }
7843            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
7844        }
7845        assert_eq!(
7846            via_gate, via_validate,
7847            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
7848        );
7849
7850        let s_ok = SupervisorSpec {
7851            estrategia: RestartStrategy::OneForOne,
7852            children: vec![
7853                child("worker-a", "^0.1", RestartPolicy::Permanent),
7854                child("worker-b", "~0.2.3", RestartPolicy::Transient),
7855                child("collector", "*", RestartPolicy::Temporary),
7856            ],
7857            ..SupervisorSpec::default()
7858        };
7859        s_ok.validate_children()
7860            .expect("per-slot gate must accept the clean-pass fixture");
7861        s_ok.validate()
7862            .expect("validate() must accept the clean-pass fixture");
7863    }
7864
7865    #[test]
7866    fn validate_children_is_self_contained_on_children_slot() {
7867        // Self-containment pin: [`SupervisorSpec::validate_children`]
7868        // resolves the per-child cascade against `&self` alone, without
7869        // depending on the peer `:estrategia`/`:max-restarts`/
7870        // `:restart-window` gates having run first — same posture the M3
7871        // peer per-slot gates carry (`validate_membros`,
7872        // `validate_contratos`, `validate_entrada`, `validate_placement`,
7873        // routing through their own oracles rather than borrowing state
7874        // threaded down from `validate`). A future consumer that reaches
7875        // the per-slot gate directly on a spec whose peer slots would
7876        // fail `validate` still surfaces the per-child refusal, not the
7877        // peer refusal.
7878        //
7879        // Construct a spec whose `:max-restarts` is `0` (which would
7880        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
7881        // the partition-dispatch) and whose `:children` carries a
7882        // `DuplicateChildCaixa` shape: the per-slot gate called directly
7883        // must surface `DuplicateChildCaixa`, proving it does not depend
7884        // on the peer `:max-restarts` gate running first.
7885        let s = SupervisorSpec {
7886            estrategia: RestartStrategy::OneForOne,
7887            max_restarts: 0,
7888            restart_window: Some(Duration::from_secs(60)),
7889            children: vec![
7890                child("worker", "^0.1", RestartPolicy::Permanent),
7891                child("worker", "^0.2", RestartPolicy::Transient),
7892            ],
7893        };
7894        assert_eq!(
7895            s.validate_children().unwrap_err(),
7896            SupervisorError::DuplicateChildCaixa {
7897                caixa: "worker".into(),
7898            },
7899            "per-slot gate must resolve per-child refusal directly against \
7900             `&self` — a dependency on the peer `:max-restarts` gate \
7901             running first would surface ZeroMaxRestarts here instead",
7902        );
7903        // The peer gate is still the surface `validate` reaches — pin
7904        // the ordering to establish that `validate_children` truly runs
7905        // last in `validate`'s dispatch, so a direct call bypasses the
7906        // peer gates on any spec whose per-child cascade would fail.
7907        assert_eq!(
7908            s.validate().unwrap_err(),
7909            SupervisorError::ZeroMaxRestarts,
7910            "validate() must surface the peer `:max-restarts` gate before \
7911             reaching the per-child cascade — this pins the dispatch \
7912             ordering the per-slot gate's self-containment complements",
7913        );
7914    }
7915
7916    #[test]
7917    fn child_spec_restart_accessor_is_const_fn() {
7918        // The [`ChildSpec::restart`] per-`:children` restart-decision-
7919        // policy `Copy`-return scalar accessor is declared
7920        // `#[must_use] pub const fn` — matching the sibling M2
7921        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
7922        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
7923        // both converted in this commit), the sibling M2
7924        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
7925        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
7926        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
7927        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
7928        // `Copy`-return `pub const fn` scalar accessors on the sibling
7929        // M3 surface. Pin the `const`-eval posture here so a future
7930        // accidental downgrade to non-`const` (an added runtime helper
7931        // reachable only from a non-`const` context, an
7932        // `Option<RestartPolicy>`-shape migration on the per-child
7933        // restart-decision axis once heterogeneous per-cluster
7934        // restart-policy overlays land that would silently drop the
7935        // `const` qualifier, a manual hand-rolled shadow) trips at
7936        // caixa-core build time rather than surfacing as a downstream
7937        // `const`-context regression far from the declaration.
7938        //
7939        // Same shape as the sibling M3
7940        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
7941        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
7942        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
7943        // accessor axis — the load-bearing witness lives in the
7944        // module-scope `const fn` wrapper `restart_via_const_fn` below:
7945        // a body that calls [`ChildSpec::restart`] under a `const fn`
7946        // signature is well-formed only when the callee is itself
7947        // `const fn`, so any future accidental downgrade of
7948        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
7949        // build time (const-eval E0015 `cannot call non-const method`),
7950        // strictly stronger than a runtime `assert!(CONST)` and
7951        // side-stepping the destructor-in-const restriction that
7952        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
7953        // items on `ChildSpec`'s `String` carriers.
7954        //
7955        // The runtime body sweeps every closed-set [`RestartPolicy`]
7956        // arm and asserts the wrapped and direct dispatches agree.
7957        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
7958            c.restart()
7959        }
7960        for restart in [
7961            RestartPolicy::Permanent,
7962            RestartPolicy::Transient,
7963            RestartPolicy::Temporary,
7964        ] {
7965            let c = ChildSpec {
7966                caixa: "worker".into(),
7967                versao: "^0.1".into(),
7968                restart,
7969            };
7970            assert_eq!(
7971                restart_via_const_fn(&c),
7972                c.restart(),
7973                "const-fn-wrapped and direct dispatch on \
7974                 ChildSpec::restart must agree for {restart:?}",
7975            );
7976            assert_eq!(
7977                c.restart(),
7978                restart,
7979                "ChildSpec::restart must return the storage-side \
7980                 RestartPolicy verbatim for {restart:?} (a violation \
7981                 means the accessor stopped being a raw field-return \
7982                 copy)",
7983            );
7984        }
7985    }
7986
7987    #[test]
7988    fn supervisor_spec_estrategia_accessor_is_const_fn() {
7989        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
7990        // sibling-restart-strategy `Copy`-return scalar accessor is
7991        // declared `#[must_use] pub const fn` — matching the sibling M2
7992        // per-`:children` [`ChildSpec::restart`] (pinned by
7993        // [`child_spec_restart_accessor_is_const_fn`] above, both
7994        // converted in this commit), the sibling M2 per-`:supervisor`
7995        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
7996        // accessor already `pub const fn`, and mirroring the peer M3
7997        // mesh-slot per-`:placement`
7998        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
7999        // `pub const fn` scalar accessor whose method-name discipline
8000        // the [`SupervisorSpec::estrategia`] method was authored to
8001        // match. Pin the `const`-eval posture here so a future
8002        // accidental downgrade to non-`const` (an added runtime helper
8003        // reachable only from a non-`const` context, an
8004        // `Option<RestartStrategy>`-shape migration once the substrate
8005        // grows per-cluster strategy overlays that would silently drop
8006        // the `const` qualifier, a manual hand-rolled shadow) trips at
8007        // caixa-core build time rather than surfacing as a downstream
8008        // `const`-context regression far from the declaration.
8009        //
8010        // Same shape as the sibling
8011        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
8012        // load-bearing witness lives in the module-scope `const fn`
8013        // wrapper `estrategia_via_const_fn` below: a body that calls
8014        // [`SupervisorSpec::estrategia`] under a `const fn` signature
8015        // is well-formed only when the callee is itself `const fn`,
8016        // side-stepping the destructor-in-const restriction that would
8017        // otherwise block a direct
8018        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
8019        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
8020        // carriers.
8021        //
8022        // The runtime body sweeps every closed-set [`RestartStrategy`]
8023        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
8024        // direct dispatches agree.
8025        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
8026            s.estrategia()
8027        }
8028        for &estrategia in RestartStrategy::ALL {
8029            let s = SupervisorSpec {
8030                estrategia,
8031                max_restarts: 5,
8032                restart_window: Some(Duration::from_secs(60)),
8033                children: Vec::new(),
8034            };
8035            assert_eq!(
8036                estrategia_via_const_fn(&s),
8037                s.estrategia(),
8038                "const-fn-wrapped and direct dispatch on \
8039                 SupervisorSpec::estrategia must agree for {estrategia:?}",
8040            );
8041            assert_eq!(
8042                s.estrategia(),
8043                estrategia,
8044                "SupervisorSpec::estrategia must return the storage-side \
8045                 RestartStrategy verbatim for {estrategia:?} (a violation \
8046                 means the accessor stopped being a raw field-return \
8047                 copy)",
8048            );
8049        }
8050    }
8051
8052    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
8053    // macro definition (see the paired doc-block above the macro
8054    // definition) — every generated `<ctor>(caixa: &str) -> Self`
8055    // constructor folds the uniform `Self::<Variant> { caixa:
8056    // caixa.to_string() }` one-field struct-literal onto one substrate
8057    // primitive. The three per-variant equivalence pins below
8058    // (fail-before-pass-after by construction — a byte-mismatched macro
8059    // arm would trip its equivalence pin first) lock each generated
8060    // constructor to its struct-literal peer under `PartialEq`, so
8061    // every wire-up in [`SupervisorSpec::validate_children`] and
8062    // [`validate_no_self_supervision`] on that variant produces a
8063    // byte-equal `SupervisorError` to the pre-lift open-coded
8064    // struct-literal. The cross-axis pin that follows (non-default
8065    // caixa name) routes the sole constructor input axis through
8066    // `.to_string()`, so the fold does not silently collapse onto a
8067    // fixed name.
8068    //
8069    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
8070    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
8071    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
8072    // `missing_entry_ctor_matches_struct_literal_wrap` /
8073    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
8074    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
8075    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
8076    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
8077    // on the six sibling ctor families the recent trajectory closed
8078    // on the peer `LayoutError` / `AplicacaoError` envelopes.
8079
8080    #[test]
8081    fn empty_child_version_ctor_matches_struct_literal_wrap() {
8082        assert_eq!(
8083            SupervisorError::empty_child_version("worker"),
8084            SupervisorError::EmptyChildVersion {
8085                caixa: "worker".to_string(),
8086            },
8087            "generated empty_child_version ctor must produce byte-equal \
8088             SupervisorError to the open-coded struct-literal wrap on the \
8089             same &str fixture",
8090        );
8091    }
8092
8093    #[test]
8094    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
8095        assert_eq!(
8096            SupervisorError::duplicate_child_caixa("worker"),
8097            SupervisorError::DuplicateChildCaixa {
8098                caixa: "worker".to_string(),
8099            },
8100            "generated duplicate_child_caixa ctor must produce byte-equal \
8101             SupervisorError to the open-coded struct-literal wrap on the \
8102             same &str fixture",
8103        );
8104    }
8105
8106    #[test]
8107    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
8108        assert_eq!(
8109            SupervisorError::child_supervises_self("orquestra"),
8110            SupervisorError::ChildSupervisesSelf {
8111                caixa: "orquestra".to_string(),
8112            },
8113            "generated child_supervises_self ctor must produce byte-equal \
8114             SupervisorError to the open-coded struct-literal wrap on the \
8115             same &str fixture",
8116        );
8117    }
8118
8119    #[test]
8120    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
8121        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
8122        // &str`) through a non-default fixture name against every
8123        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
8124        // so any wrapper-side lowercase / trim / truncate / re-order on
8125        // the `caixa.to_string()` sole-field construction surfaces
8126        // here rather than at a downstream diagnostic-shape mismatch.
8127        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
8128        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
8129        // through_to_string` / `contrato_target_ctors_route_edge_
8130        // triple_through_verbatim` / `contrato_empty_pair_ctors_
8131        // route_edge_pair_through_verbatim` cross-axis routing pins on
8132        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
8133        // here onto the `SupervisorError` `{ caixa: String }` envelope
8134        // so every substrate-primitive ctor family in caixa-core
8135        // guarantees the sole-field construction routes the caller's
8136        // `&str` through `.to_string()` verbatim.
8137        let name = "cache-v2";
8138        assert_eq!(
8139            SupervisorError::empty_child_version(name),
8140            SupervisorError::EmptyChildVersion {
8141                caixa: name.to_string(),
8142            },
8143        );
8144        assert_eq!(
8145            SupervisorError::duplicate_child_caixa(name),
8146            SupervisorError::DuplicateChildCaixa {
8147                caixa: name.to_string(),
8148            },
8149        );
8150        assert_eq!(
8151            SupervisorError::child_supervises_self(name),
8152            SupervisorError::ChildSupervisesSelf {
8153                caixa: name.to_string(),
8154            },
8155        );
8156    }
8157}