Skip to main content

caixa_core/
supervisor.rs

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