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