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