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