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