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