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