Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    matches!(WitShape::classify(wit), WitShape::Http)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    matches!(WitShape::classify(wit), WitShape::PubSub)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    matches!(WitShape::classify(wit), WitShape::Store)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    matches!(WitShape::classify(wit), WitShape::Capability)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361/// Closed 4-arm typed classification of a raw `:contratos :wit` value's
362/// WIT-shape membership — the single-dispatch typed source of truth for
363/// the four-arm partition the free-function classifier family
364/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
365/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) opens on the
366/// raw `&str` axis. Every peer free predicate now routes through
367/// [`Self::classify`] via a `matches!` arm-check, so the raw `&str →
368/// WIT-shape-arm` dispatch lives at one substrate primitive rather than
369/// four open-coded prefix probes plus a triplet negation.
370///
371/// # Compounding
372///
373/// The free predicates fan out to four independent bodies, three of
374/// which read one [`WIT_*_SHAPE_PREFIXES`] const each and one of which
375/// re-negates the trio. A future fifth WIT-shape arm (a hypothetical
376/// `wasi:sockets/*` / `tcp:*` transport-layer shape, an `oci:*`
377/// capability-import carrier, per the sibling [`wit_shape_matches`]
378/// docstring's trajectory bullet) previously required:
379///   1. one new [`WIT_*_SHAPE_PREFIXES`] const,
380///   2. one new `wit_shape_is_<name>` free predicate,
381///   3. an edit to [`wit_shape_is_capability`]'s negation to add the
382///      new arm — which a future author can silently forget, at which
383///      point every downstream capability-shape reader would
384///      misclassify the new arm as capability without a compile-time
385///      signal.
386///
387/// After this lift the third step becomes a compiler-checked
388/// exhaustiveness error: adding a fifth [`WitShape`] variant without
389/// growing [`Self::classify`]'s `match` fails at caixa-core build time
390/// (unhandled arm), and the sibling accessors ([`Self::as_str`], the
391/// [`std::fmt::Display`] and [`AsRef<str>`] impls, the
392/// [`gen_platform::IsVariant`]-derived per-arm predicates) refuse to
393/// compile until the new arm carries a body. The free predicate for
394/// the new arm is then a thin one-line `matches!` on the classifier's
395/// result, and [`wit_shape_is_capability`]'s definition stays a
396/// zero-line delta.
397///
398/// # Peers
399///
400/// Peer of the closed-set typed enums the caixa surface already
401/// carries on adjacent axes:
402/// - [`crate::CaixaKind`] on the top-level `:kind` axis
403/// - [`crate::dialeto::CaixaDialeto`] on the dialect-classification axis
404/// - [`PlacementStrategy`] on the `:placement :estrategia` axis
405/// - [`RateLimitUnit`] on the `:politicas :rate-limit :window` axis
406/// - [`crate::supervisor::RestartStrategy`] /
407///   [`crate::supervisor::RestartPolicy`] on the supervisor-strategy
408///   axes
409///
410/// Distinct from [`WitTarget`] on the same overall `:contratos` slot:
411/// [`WitTarget`] is the *post-validation* payload-carrying view (each
412/// arm carries the payload field its shape requires — an endpoint, a
413/// subject, a slot); [`WitShape`] is the *pre-validation* raw-`&str`
414/// classification (four unit arms — a witness of "which arm would the
415/// downstream validate consume this as?" without materializing the
416/// payload). Both surfaces carry an [`gen_platform::IsVariant`]-derived
417/// arm-predicate family and a `Capability` arm, so any downstream
418/// consumer that pairs a raw `&str` shape witness with a validated
419/// [`WitTarget`] view reads through matched per-arm predicates on both
420/// sides.
421///
422/// # Not a validator
423///
424/// Purely syntactic classification on the raw `:contratos :wit` prefix
425/// set — unlike [`WitContract::target`], which additionally rejects
426/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
427/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
428/// payload-shape mismatches. An empty or structurally malformed `wit`
429/// string classifies here as [`Self::Capability`] (the prefix set
430/// matches nothing), and the surrounding validate-side gate cascade is
431/// where the [`AplicacaoError::EmptyWit`] /
432/// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
433/// enum is the classifier, not the validator.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant)]
435pub enum WitShape {
436    /// HTTP-shaped WIT world — the raw `:contratos :wit` value starts
437    /// with any prefix in [`WIT_HTTP_SHAPE_PREFIXES`] (`wasi:http/`,
438    /// `http:`). Peer of [`WitTarget::Http`] on the paired
439    /// post-validation payload-carrying view.
440    Http,
441    /// Pub-sub-shaped WIT world — the raw `:contratos :wit` value
442    /// starts with any prefix in [`WIT_PUBSUB_SHAPE_PREFIXES`]
443    /// (`nats:`, `kafka:`). Peer of [`WitTarget::PubSub`] on the paired
444    /// post-validation payload-carrying view.
445    ///
446    /// The `IsVariant` derive would auto-name the predicate
447    /// `is_pub_sub` (`discriminant_to_snake("PubSub") == "pub_sub"`);
448    /// the explicit `#[is_variant(name = "pubsub")]` override keeps the
449    /// emitted method name byte-identical to the sibling
450    /// [`WitTarget::is_pubsub`] and [`WitContract::is_pubsub`]
451    /// predicates so all three arm-discriminator axes — raw-`&str`,
452    /// post-validation payload view, and pre-projection `WitContract`
453    /// surface — reach every downstream consumer through the same
454    /// `is_pubsub()` name.
455    #[is_variant(name = "pubsub")]
456    PubSub,
457    /// Key/value-store-shaped WIT world — the raw `:contratos :wit`
458    /// value starts with any prefix in [`WIT_STORE_SHAPE_PREFIXES`]
459    /// (`wasi:keyvalue/`, `kv:`). Peer of [`WitTarget::Store`] on the
460    /// paired post-validation payload-carrying view.
461    Store,
462    /// Payload-less capability edge — none of the three payload-arm
463    /// prefix sets match. Peer of [`WitTarget::Capability`] on the
464    /// paired post-validation view; the fallback arm that catches
465    /// everything the payload-arm probes miss, including the empty
466    /// string and every structurally-malformed `:wit` value the
467    /// surrounding [`WitContract::target`] validator rejects
468    /// downstream.
469    Capability,
470}
471
472impl WitShape {
473    /// Exhaustive iteration surface for every consumer that walks the
474    /// closed four-arm [`WitShape`] partition — a future
475    /// `feira app graph --by-wit-shape` histogram column, the future M4
476    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
477    /// admission-webhook rejection body naming the accepted-shape set,
478    /// any future round-trip fuzz harness that sweeps every arm's
479    /// canonical accept-set. A future variant addition (a hypothetical
480    /// `wasi:sockets/*` transport-layer shape, an `oci:*`
481    /// capability-import carrier per the sibling [`wit_shape_matches`]
482    /// docstring's trajectory bullet) extends this slice as one edit
483    /// and every consumer picks up the new entry through the shared
484    /// iteration; the compiler-checked exhaustiveness on the sibling
485    /// method `match` arms ([`Self::classify`] / [`Self::as_str`]) is
486    /// the build-time guarantee that no arm forgets to grow.
487    ///
488    /// Peer of the sibling closed-set typed enums'
489    /// [`crate::CaixaKind::ALL`] /
490    /// [`crate::dialeto::CaixaDialeto::ALL`] /
491    /// [`PlacementStrategy::ALL`] / [`RateLimitUnit::ALL`] /
492    /// [`crate::supervisor::RestartStrategy::ALL`] /
493    /// [`crate::supervisor::RestartPolicy::ALL`] /
494    /// [`crate::dep::DepList::ALL`] exhaustive-iteration surfaces —
495    /// the next closed-set typed enum on the caixa surface to converge
496    /// onto the same one-canonical-arm-list-per-enum discipline, and
497    /// the first WIT-shape-classification axis (as distinct from an
498    /// OTP-shape M2 slot or an M3 mesh slot) to reach it. Order matches
499    /// variant declaration order verbatim (`Http` → `PubSub` → `Store`
500    /// → `Capability`) so the slice is the canonical ordering every
501    /// listing / rendering consumer defers to, and matches the arm
502    /// preference [`Self::classify`] dispatches on.
503    pub const ALL: &'static [Self] = &[Self::Http, Self::PubSub, Self::Store, Self::Capability];
504
505    /// Classify a raw `:contratos :wit` value into its closed four-arm
506    /// WIT-shape partition — the single canonical dispatch every free
507    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
508    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] predicate
509    /// routes through via a `matches!` arm-check, and the single
510    /// canonical dispatch every future consumer that needs the full
511    /// four-arm answer (rather than a per-arm boolean) reaches for.
512    ///
513    /// Arm preference is `Http` → `PubSub` → `Store` → `Capability`,
514    /// matching the declaration order pinned in [`Self::ALL`]. Under
515    /// the disjointness pins immediately above the impl block
516    /// (`const _: () = assert!(!wit_shape_is_http("nats:events"))` and
517    /// peers), the preference order is unobservable — no `:wit` value
518    /// satisfies more than one payload-arm prefix set. If a future
519    /// prefix-set edit accidentally overlaps two arms (e.g. a `kv:`
520    /// prefix accidentally re-emitted under
521    /// [`WIT_HTTP_SHAPE_PREFIXES`]), the sibling `const _: () =
522    /// assert!(!wit_shape_is_http("kv:cache"))` pin trips at
523    /// caixa-core build time before the preference-order behavior
524    /// becomes observable at any consumer site.
525    ///
526    /// # Const-eval posture
527    ///
528    /// Declared `pub const fn` — routes through the peer `pub const
529    /// fn` [`wit_shape_matches`] combinator on each of the three
530    /// payload-arm prefix-set probes, so every substrate-side
531    /// `const`-context WIT-shape-arm-classifier consumer (any future
532    /// M4 admission-webhook `const fn` per-`:contratos :wit`
533    /// arm-resolver over a raw `&str`, any future `const fn`
534    /// per-`:contratos`-edge WIT-registry prefix-set overlay resolver
535    /// that fans on the classified arm at compile time) reaches
536    /// through the same typed dispatch on the substrate primitive at
537    /// const-eval time as at runtime. Pinned load-bearing by the
538    /// [`tests::wit_shape_classify_is_const_fn`] test's `const fn`
539    /// wrapper — any future accidental downgrade to non-`const` fails
540    /// with E0015 at the wrapper call site at caixa-core build time,
541    /// strictly stronger than a runtime `assert!`.
542    #[must_use]
543    pub const fn classify(wit: &str) -> Self {
544        if wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES) {
545            Self::Http
546        } else if wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES) {
547            Self::PubSub
548        } else if wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES) {
549            Self::Store
550        } else {
551            Self::Capability
552        }
553    }
554
555    /// Canonical short kebab byte-string every consumer that formats a
556    /// [`WitShape`] as census-facing text lands on — returns
557    /// `"http"` / `"pubsub"` / `"store"` / `"capability"`, the same
558    /// byte-strings the [`std::fmt::Display`] and [`AsRef<str>`] impls
559    /// route through and every future histogram-column /
560    /// audit-report / admission-rejection-body reader reads.
561    ///
562    /// Peer of the sibling closed-set typed enums'
563    /// [`crate::CaixaKind::as_str`] /
564    /// [`crate::dialeto::CaixaDialeto::as_str`] /
565    /// [`PlacementStrategy::as_str`] /
566    /// [`RateLimitUnit::as_suffix`] /
567    /// [`crate::supervisor::RestartStrategy::as_str`] /
568    /// [`crate::supervisor::RestartPolicy::as_str`] canonical-projection
569    /// accessors on the sibling closed-set typed-enum discriminator
570    /// axes.
571    #[must_use]
572    pub const fn as_str(self) -> &'static str {
573        match self {
574            Self::Http => "http",
575            Self::PubSub => "pubsub",
576            Self::Store => "store",
577            Self::Capability => "capability",
578        }
579    }
580
581    /// Reverse projection on the [`WitShape`] closed-set enum's
582    /// canonical-projection axis — parses a `"http"` / `"pubsub"` /
583    /// `"store"` / `"capability"` census-label byte-string back to the
584    /// typed enum, or returns [`None`] when `s` lies outside the four-
585    /// arm accept-set [`Self::as_str`] emits. The single `&str → Self`
586    /// projection every future re-entry point on the [`WitShape`]
587    /// census-label axis dispatches through (a future
588    /// `feira app graph --by-wit-shape=<http|pubsub|store|capability>`
589    /// CLI arg-parse that binds the wire byte-string into the typed
590    /// enum before dispatching to the per-arm histogram column, a
591    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
592    /// rejection body re-parsing a prior emission's per-arm audit-column
593    /// tag back to the typed enum for accepted-shape policy classification,
594    /// a `tracing::field::Value::Str`-arm structured-log re-loader binding
595    /// a prior [`std::fmt::Display`]-formatted [`WitShape`] output back to the
596    /// typed enum for cross-run shape-flavor histogram diff) would have
597    /// had to re-inline a four-arm `match s` cascade that expressed no
598    /// compile-time link back to the substrate primitive.
599    ///
600    /// Distinct axis from the peer [`Self::classify`] total classifier,
601    /// which takes the *raw* `:contratos :wit` identifier (`"wasi:http/proxy"`,
602    /// `"nats:events"`, `"wasi:keyvalue/store"`, everything else) and
603    /// returns the arm the payload-arm prefix-set dispatch resolves to —
604    /// a total function on the WIT-identifier axis. [`Self::from_wire`]
605    /// takes the *census-label* byte-string (`"http"` / `"pubsub"` /
606    /// `"store"` / `"capability"`, the paired output of [`Self::as_str`])
607    /// and returns the arm — a partial function on the closed four-string
608    /// census-label axis. The two axes carry different accept-sets by
609    /// design, not drift: [`Self::classify`] accepts every `&str` and
610    /// falls through to [`Self::Capability`] on the empty and every
611    /// structurally-malformed input; [`Self::from_wire`] accepts exactly
612    /// the four census labels [`Self::as_str`] emits and rejects
613    /// everything else (including every raw WIT identifier [`Self::classify`]
614    /// would classify — so a caller who accidentally routes a raw
615    /// `:contratos :wit` value through [`Self::from_wire`] instead of
616    /// [`Self::classify`] observes [`None`] rather than a plausibly-wrong
617    /// arm silently). The paired axis discipline mirrors the sibling
618    /// [`crate::CaixaKind::as_str`] / [`crate::CaixaKind::from_wire`]
619    /// pair on the top-level `:kind` axis.
620    ///
621    /// Same closed-set-reverse-projection discipline the sibling
622    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
623    /// [`crate::dialeto::CaixaDialeto::from_wire`] (d0e65ea) /
624    /// [`crate::supervisor::RestartStrategy::from_wire`] (4eec29c) /
625    /// [`crate::supervisor::RestartPolicy::from_wire`] (dd32ccf) /
626    /// [`PlacementStrategy::from_wire`] (18c7342) /
627    /// [`crate::dep::DepList::from_wire`] (45ee563) /
628    /// [`crate::render::PathShapeViolation::from_wire`] (aebd9c6) /
629    /// `caixa_arch::invariants::InvariantKind::from_wire` (b9e4e61) /
630    /// `caixa_arch::report::ArchVerdict::from_wire` (6afe564) /
631    /// `caixa_lint::diagnostic::Severity::from_wire` (5afff0e) /
632    /// `caixa_lint::diagnostic::FixSafety::from_wire` (bd505a1) /
633    /// `caixa_theme::style::Semantic::from_wire` (e7bca7b) /
634    /// `caixa_provedor::ferrite::FerriteRuntime::from_wire` (1e4cc81)
635    /// typed enums carry on the peer wire-side `str → Self` axes —
636    /// extends the substrate-wide `(as_str, from_wire)` round-trip
637    /// family onto the first `:contratos :wit` raw-classification
638    /// axis to converge on the reverse-projection discipline, matching
639    /// the same two-way `str ↔ Self` round-trip every sibling closed-
640    /// set enum already carries. Method-named `from_wire` (not
641    /// `from_str`) to match the peer shapes verbatim and side-step a
642    /// `clippy::should_implement_trait` lint that a plain `from_str`
643    /// name would otherwise trigger without paired [`std::str::FromStr`]
644    /// impl scaffolding this axis does not carry today. Returns
645    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
646    /// shapes: the caller picks the diagnostic form appropriate for its
647    /// use site (a future `feira app graph --by-wit-shape` CLI arg-parse
648    /// renders its own per-verb error message; a future admission-webhook
649    /// rejection body wraps the [`None`] outcome with the accepted-set
650    /// enumeration `WitShape::ALL.iter().map(WitShape::as_str)` for
651    /// operator diagnostics).
652    ///
653    /// Pinned load-bearing at the substrate-primitive level by
654    /// [`tests::wit_shape_from_wire_accepts_every_as_str_output`]
655    /// (round-trip witness against the peer [`Self::as_str`] axis) and
656    /// [`tests::wit_shape_from_wire_rejects_unknown_byte_strings`]
657    /// (rejection witness against silent accept-set widening,
658    /// including the raw `:contratos :wit` identifiers [`Self::classify`]
659    /// consumes on the sibling axis — so a caller who confuses the two
660    /// axes trips the pin at caixa-core build time rather than at a
661    /// downstream consumer's silent misclassification).
662    #[must_use]
663    pub fn from_wire(s: &str) -> Option<Self> {
664        match s {
665            "http" => Some(Self::Http),
666            "pubsub" => Some(Self::PubSub),
667            "store" => Some(Self::Store),
668            "capability" => Some(Self::Capability),
669            _ => None,
670        }
671    }
672}
673
674/// Route [`std::fmt::Display`] through [`WitShape::as_str`], so every
675/// consumer that formats a [`WitShape`] as user-facing text (future
676/// histogram column headers on `feira app graph --by-wit-shape`,
677/// future admission-webhook rejection bodies enumerating the accepted
678/// shape set, future audit-report per-arm column headers) lands on the
679/// same `"http"` / `"pubsub"` / `"store"` / `"capability"` byte-string
680/// the paired [`AsRef<str>`] impl also routes through. Same
681/// canonical-projection discipline the sibling
682/// [`std::fmt::Display for crate::CaixaKind`] /
683/// [`std::fmt::Display for crate::dialeto::CaixaDialeto`] /
684/// [`std::fmt::Display for PlacementStrategy`] /
685/// [`std::fmt::Display for RateLimitUnit`] impls carry — every text
686/// projection on this closed-set typed enum's dispatch surface reaches
687/// through one accessor.
688impl std::fmt::Display for WitShape {
689    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
690        f.write_str(self.as_str())
691    }
692}
693
694/// Route [`AsRef<str>`] through [`WitShape::as_str`], so every
695/// consumer that borrows a [`WitShape`] as `&str` (a future
696/// `HashMap<&str, _>` keyed lookup, a `&str`-bounded generic that
697/// takes a shape tag) lands on the same byte-string the sibling
698/// [`std::fmt::Display`] impl routes through. Peer of the sibling
699/// closed-set typed enums' [`AsRef<str>`] impls carrying the same
700/// discipline.
701impl AsRef<str> for WitShape {
702    fn as_ref(&self) -> &str {
703        self.as_str()
704    }
705}
706
707impl WitContract {
708    /// Substrate-canonical per-`:contratos` caller-Servico scalar
709    /// accessor every consumer that reads the edge's source endpoint
710    /// keys off — returns the author-declared `:contratos :de`
711    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
712    /// own [`String`] storage.
713    ///
714    /// The `:contratos :de` slot names the caller-side member Servico
715    /// on a typed inter-Servico edge (validated by
716    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
717    /// Aplicacao declares — a stray `:de` that doesn't name a member is
718    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
719    /// caller-attachment miss at cluster-apply time). Peer of the
720    /// sibling [`WitContract::destination`] accessor on the same
721    /// per-`:contratos` entry — the pair `( source(), destination() )`
722    /// jointly names the typed edge every renderer that fans on the
723    /// caller-callee identity keys off (the
724    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
725    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
726    /// map, the per-edge dedup key, the per-edge membership-lookup
727    /// diagnostic).
728    ///
729    /// Prior to this lift the `.de` byte-string was accessed inline at
730    /// four caixa-core sites (the two validate-side membership lookups
731    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
732    /// tuple's caller-arm at
733    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
734    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
735    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
736    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
737    /// — five open-coded `.de.as_str()` field-accesses that expressed
738    /// no compile-time link back to the typed slot. A future extension
739    /// of the `:contratos :de` axis to a richer author surface (a
740    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
741    /// canary flow, a per-cluster caller-alias table the operator pins
742    /// through a future `:placement`-scoped slot, the M4
743    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
744    /// admission-webhook that promotes the scalar to a caller-set
745    /// projection) would have had to be threaded through every
746    /// open-coded copy in lockstep or one consumer would silently
747    /// disagree with the peers on which caller Servico a given edge
748    /// resolves to. Lifting the resolution rule to a typed method on
749    /// the substrate primitive means every downstream caller-facing
750    /// consumer reaches for one typed dispatch — the resolver's
751    /// accept-set migrates as a unit on any future axis addition.
752    ///
753    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
754    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
755    /// axis — same "one typed dispatch on the substrate primitive,
756    /// thin projections at each consumer" discipline extended onto the
757    /// per-`:contratos` caller-Servico byte-string axis.
758    ///
759    /// Declared `pub const fn` — the body composes exclusively through
760    /// the `pub const fn` [`String::as_str`] projection (const-stable
761    /// since Rust 1.87, well within the workspace MSRV), so every
762    /// downstream `const`-context consumer of the per-`:contratos`
763    /// caller-Servico byte-string reaches through the same substrate-
764    /// primitive dispatch at const-eval time as at runtime. Peer of
765    /// the sibling `pub const fn` [`Self::destination`] /
766    /// [`Self::world_ref`] scalar accessors on the same
767    /// per-`:contratos` byte-string trio (the family closure the
768    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
769    /// locks load-bearing), and mirror on the method-surface of the
770    /// sibling free-function [`wit_shape_matches`] +
771    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
772    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
773    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
774    /// dispatch family.
775    #[must_use]
776    pub const fn source(&self) -> &str {
777        self.de.as_str()
778    }
779
780    /// Substrate-canonical per-`:contratos` callee-Servico scalar
781    /// accessor every consumer that reads the edge's destination
782    /// endpoint keys off — returns the author-declared
783    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
784    /// from the typed slot's own [`String`] storage.
785    ///
786    /// The `:contratos :para` slot names the callee-side member Servico
787    /// on a typed inter-Servico edge (validated by
788    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
789    /// Aplicacao declares — a stray `:para` that doesn't name a member
790    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
791    /// callee-attachment miss at cluster-apply time). Callee-side twin
792    /// of the sibling [`WitContract::source`] accessor — the pair
793    /// jointly names the typed edge every renderer that fans on the
794    /// caller-callee identity keys off, and this accessor is also the
795    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
796    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
797    /// composes with `destination()` at every emit site that projects a
798    /// per-edge destination Servico's L4 listener port.
799    ///
800    /// Prior to this lift the `.para` byte-string was accessed inline
801    /// at five sites — four caixa-core (the validate-side membership
802    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
803    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
804    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
805    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
806    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
807    /// — with no compile-time link back to the typed slot. A future
808    /// extension of the `:contratos :para` axis to a richer author
809    /// surface (a multi-callee weighted-fan-out overlay for canary /
810    /// blue-green routing on typed edges, a per-cluster callee-alias
811    /// table the operator pins through a future `:placement`-scoped
812    /// slot, the M4 CR materializer's per-CR admission-webhook that
813    /// promotes the scalar to a callee-set projection) would have had
814    /// to be threaded through every open-coded copy in lockstep or one
815    /// consumer would silently disagree on which callee Servico a given
816    /// edge resolves to (a per-CNP `endpointSelector` that names a
817    /// different destination than its L4 port resolver reads for, a
818    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
819    /// as distinct while the adjacency map collapses them, or vice
820    /// versa). Lifting to a typed method on the substrate primitive
821    /// means every downstream callee-facing consumer reaches for one
822    /// typed dispatch.
823    ///
824    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
825    /// (6db982c) accessor — both name the "destination-Servico
826    /// byte-string" concept on their respective mesh-slot atoms (per-
827    /// ingress apex vs. per-typed-edge callee), and both extend the
828    /// substrate-primitive-owns-the-resolver discipline onto the
829    /// per-slot destination-Servico scalar axis. Composes with
830    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
831    /// emit-side per-edge L4 port reader — the composition
832    /// `spec.port_for_destination(c.destination())` pins the CNP per-
833    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
834    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
835    /// `spec.port_for_destination(entrada.destination())`.
836    ///
837    /// Declared `pub const fn` — sibling in `const`-eval posture to the
838    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
839    /// per-`:contratos` byte-string scalar accessors, all three
840    /// projecting through the `pub const fn` [`String::as_str`]
841    /// (const-stable since Rust 1.87). See [`Self::source`] for the
842    /// family-closure rationale.
843    #[must_use]
844    pub const fn destination(&self) -> &str {
845        self.para.as_str()
846    }
847
848    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
849    /// accessor every consumer that reads the edge's WIT world
850    /// discriminator keys off — returns the author-declared
851    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
852    /// the typed slot's own [`String`] storage.
853    ///
854    /// The `:contratos :wit` slot names the WIT world the typed edge
855    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
856    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
857    /// be a well-shaped WIT world reference via
858    /// [`crate::render::is_wit_world_ref`] and by
859    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
860    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
861    /// [`WitContract::source`] / [`WitContract::destination`] accessors
862    /// on the same per-`:contratos` entry — the triple
863    /// `( source(), destination(), world_ref() )` jointly names the
864    /// typed edge every renderer that fans on the caller-callee-shape
865    /// identity keys off (the per-edge dedup key at
866    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
867    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
868    /// [`caixa_mesh::cilium_network_policies`], the
869    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
870    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
871    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
872    ///
873    /// Prior to this lift the `.wit` byte-string was accessed inline at
874    /// five sites — three caixa-core (the `WitContract::is_*` shape-
875    /// dispatch predicates' `&self.wit` arg, the validate-side empty
876    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
877    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
878    /// printer's `{}` format-slot at `c.wit`) — five open-coded
879    /// `.wit` field-accesses that expressed no compile-time link back to
880    /// the typed slot. A future extension of the `:contratos :wit` axis
881    /// to a richer author surface (an M4 promotion from `String` to a
882    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
883    /// lisp per this struct's own `:wit` field docstring, a per-cluster
884    /// WIT-alias table the operator pins through a future
885    /// `:placement`-scoped slot, a canonicalization pass that lowercases
886    /// `wasi:*` prefixes) would have had to be threaded through every
887    /// open-coded copy in lockstep or one consumer would silently
888    /// disagree with the peers on which WIT shape a given edge resolves
889    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
890    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
891    /// empty-check that missed a whitespace-only string a peer accessor
892    /// stripped, or vice versa). Lifting to a typed method on the
893    /// substrate primitive means every downstream WIT-shape-facing
894    /// consumer reaches for one typed dispatch — the resolver's
895    /// accept-set migrates as a unit on any future axis addition.
896    ///
897    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
898    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
899    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
900    /// 6db982c), per-`:membros` [`Membro::nome`] /
901    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
902    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
903    /// on the substrate primitive, thin projections at each consumer"
904    /// discipline extended onto the last unlifted per-`:contratos`
905    /// scalar (the WIT-world-reference arm).
906    ///
907    /// [fag]: caixa-feira/src/cmd/app.rs
908    ///
909    /// Declared `pub const fn` — sibling in `const`-eval posture to the
910    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
911    /// per-`:contratos` byte-string scalar accessors on the trio, and
912    /// the load-bearing enabler for the paired `pub const fn`
913    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
914    /// [`Self::is_capability`] WIT-shape-predicate family (each
915    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
916    /// the `const`-eval posture by construction once this accessor
917    /// carries it). See [`Self::source`] for the family-closure
918    /// rationale and the paired
919    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
920    /// for the load-bearing witness.
921    #[must_use]
922    pub const fn world_ref(&self) -> &str {
923        self.wit.as_str()
924    }
925
926    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
927    /// payload-target scalar accessor every consumer that reads the
928    /// edge's L7 HTTP request path payload keys off — returns the
929    /// author-declared `:contratos :endpoint` byte-string verbatim as
930    /// an `Option<&str>`, borrowed from the typed slot's own
931    /// `Option<String>` storage; `None` when the slot is absent (the
932    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
933    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
934    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
935    /// [`WitTarget::Capability`] edge carries none of the three).
936    ///
937    /// The `:contratos :endpoint` slot carries the HTTP request path
938    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
939    /// — same shape required of `:entrada :paths`, gated by the shared
940    /// [`crate::render::is_gateway_api_http_path`] predicate) that
941    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
942    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
943    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
944    /// downstream consumer that reads the payload keys off this scalar
945    /// (the [`WitContract::target`] Http-arm payload extraction that
946    /// materializes [`WitTarget::Http { endpoint }`] under the paired
947    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
948    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
949    /// key's endpoint arm that pins the payload as part of the six-tuple
950    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
951    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
952    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
953    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
954    /// emission path that lands the payload verbatim as a Cilium L7
955    /// `path:` rule).
956    ///
957    /// Prior to this lift the `.endpoint` field was accessed inline at
958    /// two production sites in `caixa-core/src/aplicacao.rs` — the
959    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
960    /// self.endpoint.as_deref();` binding at the top of the method, and
961    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
962    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
963    /// field-accesses that expressed no compile-time link back to the
964    /// typed slot. A future extension of the `:contratos :endpoint`
965    /// axis to a richer author surface (an M4 promotion from
966    /// `Option<String>` to a typed HTTP path-template enum once the
967    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
968    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
969    /// alias table the operator pins through a future `:placement`-
970    /// scoped slot, a canonicalization pass that percent-encodes non-
971    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
972    /// materializer applies per-tenant) would have had to be threaded
973    /// through both open-coded copies in lockstep or the two consumers
974    /// would silently disagree on which HTTP path a given edge resolves
975    /// to — the [`WitContract::target`] payload-extraction reading
976    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
977    /// the operator-resolved `"/tenant-a/lookup"` would silently split
978    /// the [`WitTarget::Http`]-arm rendered payload from the actual
979    /// dedup-key uniqueness axis, a two-consumer split at the validator
980    /// far from the source `caixa.lisp` with no field naming the
981    /// payload-drift root cause. Lifting the resolution rule to a typed
982    /// method on the substrate primitive means every downstream
983    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
984    /// L7-payload surface reaches for exactly one typed dispatch — the
985    /// resolver's accept-set migrates as a unit on any future axis
986    /// addition.
987    ///
988    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
989    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
990    /// accessors on the M3 mesh-slot family — same "one typed dispatch
991    /// on the substrate primitive, thin projections at each consumer"
992    /// discipline extended onto the per-`:contratos` HTTP-shaped
993    /// payload-carrier `Option<String>` optional-scalar axis. First
994    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
995    /// atom — opens the "optional per-slot payload-carrier scalar"
996    /// projection pattern the sibling per-`:contratos` `:subject` /
997    /// `:slot` future lifts fold on, matching the closed
998    /// per-`:contratos` scalar-value accessor family
999    /// ([`WitContract::source`] / [`WitContract::destination`] /
1000    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
1001    /// scalar `String` axes. Named `endpoint()` to match the storage
1002    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
1003    /// author-facing label const; the accessor's identity name maps
1004    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1005    /// docstring already carries.
1006    #[must_use]
1007    pub const fn endpoint(&self) -> Option<&str> {
1008        match &self.endpoint {
1009            Some(s) => Some(s.as_str()),
1010            None => None,
1011        }
1012    }
1013
1014    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
1015    /// payload-target scalar accessor every consumer that reads the
1016    /// edge's NATS / Kafka publish subject payload keys off — returns
1017    /// the author-declared `:contratos :subject` byte-string verbatim
1018    /// as an `Option<&str>`, borrowed from the typed slot's own
1019    /// `Option<String>` storage; `None` when the slot is absent (the
1020    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
1021    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
1022    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1023    /// [`WitTarget::Capability`] edge carries none of the three).
1024    ///
1025    /// The `:contratos :subject` slot carries the NATS / Kafka publish
1026    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
1027    /// per-edge target selector — `orders.paid`, `events.>`, whatever
1028    /// subject namespace the author names on the pub-sub edge) that
1029    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
1030    /// arm's `subject: &'a str` payload when the edge's `:wit` world
1031    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
1032    /// downstream consumer that reads the payload keys off this scalar
1033    /// (the [`WitContract::target`] PubSub-arm payload extraction that
1034    /// materializes [`WitTarget::PubSub { subject }`] under the paired
1035    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
1036    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1037    /// key's subject arm that pins the payload as part of the six-tuple
1038    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
1039    /// future M4 per-edge WIT registry resolver's pub-sub-arm
1040    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1041    /// materializer's per-edge NATS admission webhook, the future
1042    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1043    /// as a NATS subject the operator pins per-CR).
1044    ///
1045    /// Prior to this lift the `.subject` field was accessed inline at
1046    /// two production sites in `caixa-core/src/aplicacao.rs` — the
1047    /// [`WitContract::target`] payload-shape dispatch's `let subject =
1048    /// self.subject.as_deref();` binding at the top of the method, and
1049    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1050    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
1051    /// field-accesses that expressed no compile-time link back to the
1052    /// typed slot. A future extension of the `:contratos :subject` axis
1053    /// to a richer author surface (an M4 promotion from `Option<String>`
1054    /// to a typed NATS-subject-template enum once the WIT registry
1055    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
1056    /// struct's own `:wit` field docstring, a per-cluster subject-alias
1057    /// table the operator pins through a future `:placement`-scoped
1058    /// slot, a canonicalization pass that lowercases / dedupes wildcard
1059    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
1060    /// applies per-tenant) would have had to be threaded through both
1061    /// open-coded copies in lockstep or the two consumers would silently
1062    /// disagree on which NATS subject a given edge resolves to — the
1063    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
1064    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
1065    /// resolved `"tenant-a.orders.paid"` would silently split the
1066    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
1067    /// key uniqueness axis, a two-consumer split at the validator far
1068    /// from the source `caixa.lisp` with no field naming the payload-
1069    /// drift root cause. Lifting the resolution rule to a typed method
1070    /// on the substrate primitive means every downstream pub-sub-payload-
1071    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
1072    /// surface reaches for exactly one typed dispatch — the resolver's
1073    /// accept-set migrates as a unit on any future axis addition.
1074    ///
1075    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1076    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
1077    /// carrier axis — second `Option<&str>`-return accessor on the
1078    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
1079    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
1080    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
1081    /// key/value-store arm as the last unlifted per-`:contratos`
1082    /// `Option<String>` axis. Named `subject()` to match the storage
1083    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
1084    /// author-facing label const; the accessor's identity name maps
1085    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1086    /// docstring already carries.
1087    #[must_use]
1088    pub const fn subject(&self) -> Option<&str> {
1089        match &self.subject {
1090            Some(s) => Some(s.as_str()),
1091            None => None,
1092        }
1093    }
1094
1095    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
1096    /// shaped payload-target scalar accessor every consumer that reads
1097    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
1098    /// off — returns the author-declared `:contratos :slot` byte-string
1099    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
1100    /// own `Option<String>` storage; `None` when the slot is absent
1101    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
1102    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
1103    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
1104    /// [`WitTarget::Capability`] edge carries none of the three).
1105    ///
1106    /// The `:contratos :slot` slot carries the key/value store
1107    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
1108    /// arm's per-edge target selector — `carts/{cart_id}`,
1109    /// `sessions/{tenant}/{sid}`, whatever key-template the author
1110    /// names on the store edge) that [`WitContract::target`] projects
1111    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
1112    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
1113    /// accept-set. Every downstream consumer that reads the payload
1114    /// keys off this scalar (the [`WitContract::target`] Store-arm
1115    /// payload extraction that materializes [`WitTarget::Store { slot }`]
1116    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
1117    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1118    /// key's store arm that pins the payload as part of the six-tuple
1119    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
1120    /// the future M4 per-edge WIT registry resolver's store-arm
1121    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1122    /// materializer's per-edge key/value admission webhook, the future
1123    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1124    /// as a key-template the operator pins per-CR).
1125    ///
1126    /// Prior to this lift the `.slot` field was accessed inline at two
1127    /// production sites in `caixa-core/src/aplicacao.rs` — the
1128    /// [`WitContract::target`] payload-shape dispatch's `let slot =
1129    /// self.slot.as_deref();` binding at the top of the method, and
1130    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1131    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
1132    /// field-accesses that expressed no compile-time link back to the
1133    /// typed slot. A future extension of the `:contratos :slot` axis
1134    /// to a richer author surface (an M4 promotion from `Option<String>`
1135    /// to a typed key-template enum once the WIT registry stabilizes
1136    /// key-template parameter shapes in tatara-lisp per this struct's
1137    /// own `:wit` field docstring, a per-cluster slot-alias table the
1138    /// operator pins through a future `:placement`-scoped slot, a
1139    /// canonicalization pass that lowercases the bucket prefix, a
1140    /// per-CR fully-qualified rewrite the M4 CR materializer applies
1141    /// per-tenant) would have had to be threaded through both
1142    /// open-coded copies in lockstep or the two consumers would
1143    /// silently disagree on which key-template a given edge resolves
1144    /// to — the [`WitContract::target`] payload-extraction reading
1145    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
1146    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
1147    /// would silently split the [`WitTarget::Store`]-arm rendered
1148    /// payload from the actual dedup-key uniqueness axis, a
1149    /// two-consumer split at the validator far from the source
1150    /// `caixa.lisp` with no field naming the payload-drift root cause.
1151    /// Lifting the resolution rule to a typed method on the substrate
1152    /// primitive means every downstream store-payload-facing consumer
1153    /// of the Aplicacao's per-`:contratos` payload surface reaches for
1154    /// exactly one typed dispatch — the resolver's accept-set migrates
1155    /// as a unit on any future axis addition.
1156    ///
1157    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1158    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
1159    /// accessors on the M3 mesh-slot payload-carrier axis — third and
1160    /// final `Option<&str>`-return accessor on the per-`:contratos`
1161    /// mesh-slot atom, closes the last unlifted per-`:contratos`
1162    /// `Option<String>` axis and completes the "optional per-slot
1163    /// payload-carrier scalar" projection pattern the peer HTTP /
1164    /// pub-sub arms established across the three payload-shape
1165    /// dispatch arms. Named `slot()` to match the storage field's
1166    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
1167    /// author-facing label const; the accessor's identity name maps
1168    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1169    /// docstring already carries.
1170    #[must_use]
1171    pub const fn slot(&self) -> Option<&str> {
1172        match &self.slot {
1173            Some(s) => Some(s.as_str()),
1174            None => None,
1175        }
1176    }
1177
1178    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
1179    /// caller-callee-pair accessor every consumer that constructs an
1180    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
1181    /// caller-callee pair keys off — returns the author-declared
1182    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
1183    /// owned `(String, String)` tuple, projected through the lifted
1184    /// [`WitContract::source`] / [`WitContract::destination`] scalar
1185    /// accessors so any future rebrand on the caller-arm / callee-arm
1186    /// projection axis (an M4 per-cluster caller-alias table the
1187    /// operator pins through a future `:placement`-scoped slot, a
1188    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
1189    /// a per-`:membros` alias overlay from the future `:membros
1190    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1191    /// acknowledges) reaches every diagnostic-construction site by
1192    /// construction.
1193    ///
1194    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
1195    /// owned form" primitive every per-`:contratos` diagnostic variant on
1196    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
1197    /// nine variants [`AplicacaoError::EmptyWit`],
1198    /// [`AplicacaoError::ContratoEndpointEmpty`],
1199    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
1200    /// [`AplicacaoError::ContratoEndpointInvalid`],
1201    /// [`AplicacaoError::ContratoSubjectEmpty`],
1202    /// [`AplicacaoError::ContratoSubjectInvalid`],
1203    /// [`AplicacaoError::ContratoSlotEmpty`],
1204    /// [`AplicacaoError::ContratoSlotInvalid`], and
1205    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
1206    /// para: String` field pair the constructor site reads verbatim off
1207    /// the [`WitContract`] the diagnostic points at, so a diagnostic
1208    /// whose `de:` and `para:` labels silently drift off the source
1209    /// caller/callee — a per-cluster caller-alias rewrite that landed on
1210    /// one variant's inline `de: c.de.clone()` field access but not on
1211    /// its sibling variant's, an accidental swap of the `de:` and `para:`
1212    /// arms in a copy-paste of the constructor block — would emit a
1213    /// build-time error whose "which caixa is at fault" question the
1214    /// operator answers wrongly, far from the source `caixa.lisp`.
1215    ///
1216    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
1217    /// pair was inlined at seven [`WitContract::target`] error-
1218    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
1219    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
1220    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
1221    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
1222    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
1223    /// the [`AplicacaoError::ContratoSlotEmpty`] /
1224    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
1225    /// two [`AplicacaoSpec::validate`] error-construction sites (the
1226    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
1227    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
1228    /// insert-first-seen closure) — nine open-coded `.de.clone() +
1229    /// .para.clone()` pairs that expressed no compile-time contract that
1230    /// the caller-arm and callee-arm arms of the same diagnostic
1231    /// construction reach for the same [`WitContract`] instance or that
1232    /// the `de:` and `para:` label pair binds to the fields the author
1233    /// declared. Any future rebrand on the axis — an M4 per-cluster
1234    /// caller/callee-alias rewrite the operator pins through a future
1235    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1236    /// per-CR fully-qualified namespace prefix the M4
1237    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1238    /// per-tenant, a canonicalization pass that lowercases the caller +
1239    /// callee identifiers post-parse — would have had to be threaded
1240    /// through every open-coded copy in lockstep or one variant's
1241    /// diagnostic would silently name a different caller/callee pair
1242    /// than its peer, silently degrading the "which caixa is at fault"
1243    /// self-locating signal every operator-facing typed diagnostic
1244    /// exists to carry. Lifting the pair to a typed method on the
1245    /// substrate primitive means every downstream diagnostic-construction
1246    /// site reaches for exactly one typed dispatch — the resolver's
1247    /// projection migrates as a unit on any future axis addition.
1248    ///
1249    /// Peer of the sibling per-`:contratos` scalar accessor family
1250    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
1251    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
1252    /// scalar-value axes — first composite-projection accessor on the
1253    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
1254    /// form `.clone()` field-accesses that pair the sibling
1255    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
1256    /// one typed dispatch. Named `edge_pair()` to reflect the identity
1257    /// name of the projected tuple (the typed-edge caller-callee pair,
1258    /// distinct from the sibling triple-projection
1259    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
1260    /// closure in [`WitContract::target`] + the paired
1261    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
1262    /// site's `(de, para, wit)` triple onto one typed dispatch).
1263    #[must_use]
1264    pub fn edge_pair(&self) -> (String, String) {
1265        (self.source().to_string(), self.destination().to_string())
1266    }
1267
1268    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
1269    /// :wit)` triple every per-edge diagnostic constructor that names
1270    /// all three axes threads verbatim into its `de:` / `para:` /
1271    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
1272    /// / missing-target / invalid-wit / capability-with-payload arms
1273    /// (eight sites all shape `let (de, para, wit) = edge();
1274    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
1275    /// accessor landed) and the sibling
1276    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
1277    /// constructor (which paired `edge_pair()` for the `(de, para)`
1278    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
1279    /// typed-dispatch + raw-field-access shape the sibling accessor
1280    /// family already flagged as a drift risk). Nine total call sites
1281    /// collapse onto this helper.
1282    ///
1283    /// Lifted with the same one-source-of-truth discipline
1284    /// [`WitContract::edge_pair`] carries on the paired
1285    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
1286    /// arms compose through the lifted [`WitContract::source`] /
1287    /// [`WitContract::destination`] / [`WitContract::world_ref`]
1288    /// scalar accessors byte-for-byte (pinned by the paired
1289    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
1290    /// composition-pin), so any future rebrand on the per-`:contratos`
1291    /// caller / callee / world-ref axis (an M4 per-cluster
1292    /// caller/callee-alias rewrite the operator pins through a future
1293    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1294    /// per-CR fully-qualified namespace prefix the M4
1295    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1296    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
1297    /// on `source()` / `destination()`, a per-CR canonicalization pass
1298    /// that lowercases the WIT world ref post-parse) migrates as a
1299    /// single caixa-core edit rather than a coordinated rewrite of
1300    /// nine open-coded triple-constructors.
1301    ///
1302    /// Peer of the sibling per-`:contratos` composite-projection
1303    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
1304    /// composite-value axes — closes the last unlifted owned-form
1305    /// composite-tuple axis on the per-`:contratos` diagnostic-
1306    /// construction surface. Named `edge_triple()` to reflect the
1307    /// identity name of the projected tuple (the typed-edge
1308    /// caller-callee-wit triple, sibling to the caller-callee-only
1309    /// pair `edge_pair()` returns).
1310    #[must_use]
1311    pub fn edge_triple(&self) -> (String, String, String) {
1312        (
1313            self.source().to_string(),
1314            self.destination().to_string(),
1315            self.world_ref().to_string(),
1316        )
1317    }
1318
1319    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
1320    /// dedups typed edges keys off — routes through the lifted
1321    /// [`WitContract::source`] / [`WitContract::destination`] /
1322    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
1323    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
1324    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
1325    /// type alias's six axes migrate as a unit on any future axis
1326    /// addition (adding a seventh field to [`WitContract`] is one
1327    /// [`ContratoIdentity`] alias edit + one accessor addition + one
1328    /// arm here, not a coordinated rewrite of every open-coded
1329    /// six-tuple builder that dedups on the identity axis).
1330    ///
1331    /// Sibling of [`WitContract::edge_pair`] /
1332    /// [`WitContract::edge_triple`] on the composite-projection axis:
1333    /// the pair projects the caller-callee axes, the triple extends it
1334    /// with the world-ref, this method extends it with the three
1335    /// payload-carrier axes. Every projection returns the same six
1336    /// scalar accessors' outputs; the three methods differ only in
1337    /// which arms they surface.
1338    ///
1339    /// Declared `pub const fn` — every callee is itself `pub const fn`
1340    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
1341    /// project through `pub const fn` [`String::as_str`], const-stable
1342    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
1343    /// [`Self::slot`] project through the same `String::as_str` under a
1344    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
1345    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1346    /// closed the const-eval surface on) and tuple construction from
1347    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1348    /// itself trivially const. The `ContratoIdentity<'_>` alias
1349    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1350    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1351    /// no heap allocation, no non-const call folded through the tuple's
1352    /// construction. Sibling in `const`-eval posture to the peer
1353    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1354    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1355    /// composite-projection family the sibling
1356    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1357    /// already anchors — this extends the same `const`-eval-surface
1358    /// posture onto the peer six-arm composite-projection axis where
1359    /// the projection surfaces the full identity tuple rather than a
1360    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1361    /// bearing by
1362    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1363    /// (a future accidental downgrade fires E0015 at the wrapper at
1364    /// caixa-core build time).
1365    #[must_use]
1366    pub const fn identity(&self) -> ContratoIdentity<'_> {
1367        (
1368            self.source(),
1369            self.destination(),
1370            self.world_ref(),
1371            self.endpoint(),
1372            self.subject(),
1373            self.slot(),
1374        )
1375    }
1376
1377    /// True when this contract targets an HTTP-shaped WIT world.
1378    ///
1379    /// Declared `pub const fn` — routes through the paired `pub const
1380    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1381    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1382    /// (d46420c). Sibling in `const`-eval posture to the peer
1383    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1384    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1385    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1386    /// the same `const`-eval-surface posture as the free-function
1387    /// classifier family it composes through. Pinned load-bearing by
1388    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1389    /// test (a future accidental downgrade to non-`const` fires E0015
1390    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1391    /// build time).
1392    #[must_use]
1393    pub const fn is_http(&self) -> bool {
1394        wit_shape_is_http(self.world_ref())
1395    }
1396
1397    /// True when this contract targets a pub-sub-shaped WIT world.
1398    ///
1399    /// Declared `pub const fn` — sibling in `const`-eval posture to
1400    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1401    /// [`Self::is_capability`] WIT-shape-predicate family. See
1402    /// [`Self::is_http`] for the family-closure rationale.
1403    #[must_use]
1404    pub const fn is_pubsub(&self) -> bool {
1405        wit_shape_is_pubsub(self.world_ref())
1406    }
1407
1408    /// True when this contract targets a key/value-shaped WIT world.
1409    ///
1410    /// Declared `pub const fn` — sibling in `const`-eval posture to
1411    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1412    /// [`Self::is_capability`] WIT-shape-predicate family. See
1413    /// [`Self::is_http`] for the family-closure rationale.
1414    #[must_use]
1415    pub const fn is_store(&self) -> bool {
1416        wit_shape_is_store(self.world_ref())
1417    }
1418
1419    /// True when this contract targets *none* of the three known payload-
1420    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1421    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1422    /// open on the [`WitContract`] surface. Returns the exact-inverse
1423    /// disjunction of the peer trio — `true` when none of the three
1424    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1425    /// author-declared WIT world is a pure typed capability edge with no
1426    /// payload selector (the shape [`WitContract::target`] projects onto
1427    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1428    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1429    ///
1430    /// The `:contratos :wit` shape-space is closed at four arms
1431    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1432    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1433    /// everything else on the payload-less capability arm), and every
1434    /// downstream consumer that must filter contratos by shape-class
1435    /// keys off the four sibling predicates (the [`WitContract::target`]
1436    /// dispatch's implicit `else` after the three payload-shape arm
1437    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1438    /// every future substrate-side capability-shape-only emitter — the
1439    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1440    /// future `feira app graph --capability` per-Aplicacao capability-
1441    /// column filter, the future per-cluster capability-scope reconciler
1442    /// that skips L4/L7 emission for payload-less edges since Cilium
1443    /// can't introspect WASI capability calls, the future
1444    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1445    /// shape shape-count histogram). Every such consumer reaches for one
1446    /// typed dispatch on the substrate primitive so the "which arm
1447    /// carries the capability-only shape?" answer lives at one caixa-core
1448    /// edit rather than open-coded across per-consumer
1449    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1450    /// negations, each of which would silently drop a future fourth
1451    /// payload-arm addition without a compile-time signal at the
1452    /// consumer site.
1453    ///
1454    /// Prior to this lift the "not one of the three known payload
1455    /// shapes" classification sat inline at [`WitContract::target`]'s
1456    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1457    /// [`WitTarget::Capability`] admission arm after the three `if
1458    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1459    /// { … }` guards) with no named accessor for downstream consumers
1460    /// to reach through. A future substrate-side capability-only
1461    /// filter or a future capability-scope reconciler would have had to
1462    /// re-inline the same triplet negation at every emit site with no
1463    /// compile-time link back to the sibling trio, and a future arm
1464    /// addition (a hypothetical fourth payload-shape prefix set — a
1465    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1466    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1467    /// trajectory bullet) would land the new predicate on the payload-
1468    /// carrying trio and silently misclassify the new shape as
1469    /// capability at every triplet-negation consumer site, propagating
1470    /// the drift far from the caixa-core prefix-set commit.
1471    ///
1472    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1473    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1474    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1475    /// axis, mirroring the paired post-projection [`WitTarget`]
1476    /// `gen_platform::IsVariant`-derived 4-way predicate set
1477    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1478    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1479    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1480    /// arm-set). The two typed axes — pre-projection on the raw
1481    /// `:contratos :wit` string, post-projection on the validated typed
1482    /// view — now carry a matched 4-arm predicate discipline: every
1483    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1484    /// predicate on the [`WitContract`] surface, and any future
1485    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1486    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1487    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1488    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1489    /// pre-projection axis through a matching peer prefix-set + peer
1490    /// predicate lift by construction — the compile-time exhaustiveness
1491    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1492    /// the post-projection accessor family stays in sync, and the sibling
1493    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1494    /// partition-witness pin locks the pre-projection classification in
1495    /// load-bearing so a peer prefix-set addition that widened one arm's
1496    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1497    /// surfaces as a test failure at caixa-core build time rather than a
1498    /// silent per-consumer split at renderer emit time.
1499    ///
1500    /// Composes byte-for-byte through the lifted peer trio
1501    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1502    /// any future rebrand of any prefix-set const flows through this
1503    /// method by construction without a coordinated per-consumer rewrite
1504    /// (pinned by the sibling
1505    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1506    /// composition-witness).
1507    ///
1508    /// Note: purely syntactic classification on the `:wit` prefix-set —
1509    /// unlike [`Self::target`], which additionally rejects value-shape-
1510    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1511    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1512    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1513    /// structurally malformed returns `true` from `is_capability()` (the
1514    /// prefix set matches nothing), and the surrounding
1515    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1516    /// is where the [`AplicacaoError::EmptyWit`] /
1517    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1518    /// predicate is the classifier, not the validator.
1519    ///
1520    /// Declared `pub const fn` — closes the WIT-shape-predicate
1521    /// family's `const`-eval-surface pass at the fourth (payload-less)
1522    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1523    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1524    /// See [`Self::is_http`] for the family-closure rationale.
1525    #[must_use]
1526    pub const fn is_capability(&self) -> bool {
1527        wit_shape_is_capability(self.world_ref())
1528    }
1529
1530    /// True when this contract's caller equals its callee — a
1531    /// structurally degenerate typed edge that no `:contratos` entry can
1532    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1533    /// Servico B" is an *inter*-Servico contract between two distinct
1534    /// graph nodes). A Servico contracting with itself resolves to an
1535    /// in-process call the wasm-engine never routes through the mesh at
1536    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1537    /// per-edge policy can express the intended shape — the pub-sub
1538    /// path silently rendered a self-allow rule that is a no-op (intra-
1539    /// pod traffic bypasses the mesh entirely), and the synchronous
1540    /// paths surfaced as a misleading `ContratoCycle` whose path was
1541    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1542    /// deadlock. Every downstream consumer that must reject the shape
1543    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1544    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1545    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1546    /// axis, every future adjacency-graph builder that must skip self-
1547    /// edges rather than fold them into an incidental cycle) now keys
1548    /// off exactly one typed dispatch on the substrate primitive, so
1549    /// any future rebrand on the axis (an M4-typed-caller enum whose
1550    /// identity comparison rule the accessor could route through, an
1551    /// operator-side per-cluster caller/callee-alias table the
1552    /// materializer resolves per-CR before the equality probe, a
1553    /// promotion of the pointwise `==` to a set-membership check once
1554    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1555    /// so a per-replica self-edge is rejected under the same predicate)
1556    /// migrates as a single caixa-core edit rather than a coordinated
1557    /// rewrite of every downstream self-edge consumer. Composes
1558    /// byte-for-byte through the lifted [`Self::source`] /
1559    /// [`Self::destination`] scalar accessors — the accessor pair every
1560    /// per-`:contratos` scalar-value axis already routes through — so
1561    /// any future rebrand of the underlying `:de` / `:para` storage
1562    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1563    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1564    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1565    /// same one body without a coordinated per-consumer rewrite.
1566    ///
1567    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1568    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1569    /// on the `:wit` world-ref axis — extended onto the per-edge
1570    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1571    /// partition the WIT-shape-space; `is_self_loop` partitions the
1572    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1573    /// the graph-theoretic identity of the shape (a loop from a graph
1574    /// node to itself, distinct from the sibling multi-node
1575    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1576    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1577    /// variant already carrying the term.
1578    ///
1579    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1580    /// shape-predicate on the substrate's `const`-eval surface. The peer
1581    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1582    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1583    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1584    /// posture on the WIT-world-ref classifier axis; this lift extends it
1585    /// onto the peer caller-callee identity-space predicate. The body
1586    /// projects the `:de` / `:para` `String` storage through the sibling
1587    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1588    /// accessors, then compares the resulting `&str` byte-slices under a
1589    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1590    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1591    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1592    /// — every operation `const`-eval-callable on stable Rust, no
1593    /// iterator methods, no `PartialEq for str` trait dispatch (which
1594    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1595    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1596    /// loop verbatim on the paired-slice-equality shape. Every downstream
1597    /// substrate-side `const`-context consumer of the per-`:contratos`
1598    /// self-edge partition (a future `const _: () = assert!(…)` module-
1599    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1600    /// the type's carriers admit `const`-context construction, a future
1601    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1602    /// composer that fans on the identity-space partition at compile
1603    /// time) reaches through the same typed dispatch on the substrate
1604    /// primitive at const-eval time as at runtime. Pinned by
1605    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1606    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1607    /// future accidental downgrade to non-`const` trips at caixa-core
1608    /// build time with E0015 (`cannot call non-const method`), strictly
1609    /// stronger than a runtime `assert!`.
1610    #[must_use]
1611    pub const fn is_self_loop(&self) -> bool {
1612        // Compose through the paired `pub const fn` [`Self::source`] /
1613        // [`Self::destination`] scalar accessors so any future rebrand of
1614        // the underlying `:de` / `:para` storage (a lift from `String` to
1615        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1616        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1617        // inline-buffer swap) flows through the same one body without a
1618        // coordinated per-consumer rewrite. Peer of the sibling
1619        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1620        // [`Self::is_capability`] shape-predicate family — each of which
1621        // composes through the paired [`Self::world_ref`] scalar accessor
1622        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1623        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1624        // [`wit_shape_is_capability`] free-function classifier — the same
1625        // "typed dispatch composes with typed dispatch, not raw field
1626        // access" discipline extended onto the caller-callee identity-
1627        // space partition. Pinned by
1628        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1629        // above.
1630        let a = self.source().as_bytes();
1631        let b = self.destination().as_bytes();
1632        if a.len() != b.len() {
1633            return false;
1634        }
1635        // Manual byte-level equality loop — mirrors the peer
1636        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1637        // verbatim on the paired-slice-equality shape. `PartialEq for
1638        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1639        // trait dispatch it routes through is not `const`), so a naive
1640        // `self.source() == self.destination()` body would trip on
1641        // `const`-eval-callability; the byte-slice loop dispatches
1642        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1643        // const-stable slice indexing (since Rust 1.79) — every
1644        // operation `const`-eval-callable on stable.
1645        let mut i = 0;
1646        while i < a.len() {
1647            if a[i] != b[i] {
1648                return false;
1649            }
1650            i += 1;
1651        }
1652        true
1653    }
1654
1655    /// Reject a `:contratos` entry whose `:de` or `:para` names a
1656    /// caixa the `:membros` graph does not contain — the substrate-
1657    /// primitive per-edge graph-membership gate every consumer of the
1658    /// typed inter-Servico edge's endpoint-resolution axis reaches
1659    /// through one dispatch.
1660    ///
1661    /// A `:contratos` entry is a typed directed edge between two
1662    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1663    /// address graph nodes, so a reference to a node the graph does
1664    /// not contain is a build error"). Both endpoints must resolve
1665    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1666    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1667    /// framing does not distinguish `:de` from `:para` (both arms
1668    /// carry the offending `caixa` name verbatim without a
1669    /// slot-discriminator field, unlike the sibling per-arm shape
1670    /// gate [`validate_contrato_caixa`] whose paired
1671    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1672    /// variants each carry a `slot: &'static str` tag). So the two
1673    /// arms are byte-identical modulo the accessor projection they
1674    /// key off, and folding them into one per-edge dispatch preserves
1675    /// every existing diagnostic-fired output byte-for-byte while
1676    /// closing the last inline duplication the substrate-primitive
1677    /// per-edge gate family carried inside
1678    /// [`AplicacaoSpec::validate_contratos`].
1679    ///
1680    /// Routes through the paired [`Self::source`] / [`Self::destination`]
1681    /// scalar accessors so every future rebrand of the underlying
1682    /// `:de` / `:para` storage (a lift from `String` to a typed
1683    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1684    /// the M4 CR materializer authors, a per-cluster caller-alias
1685    /// table the operator pins through a future `:placement`-scoped
1686    /// slot, an M4 promotion from `String` to a typed edge-endpoint
1687    /// enum) flows through the same body without a coordinated
1688    /// per-consumer rewrite. Peer of the sibling per-edge substrate
1689    /// primitives already lifted on the same `impl WitContract`
1690    /// surface ([`Self::is_self_loop`] on the identity-space arm,
1691    /// [`Self::target`] on the payload-shape ↔ target-consistency
1692    /// arm, [`Self::identity`] on the dedup-key arm) — this run
1693    /// extends the shape to the last per-edge axis
1694    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1695    /// twin-arm cascade.
1696    ///
1697    /// Every future consumer that wants to re-check *one* edge's
1698    /// graph-membership reaches through one call: the M4
1699    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1700    /// admission-webhook re-checking `:contratos` after a
1701    /// per-`(:de, :para)` edge patch without re-walking the whole
1702    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1703    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1704    /// resolves an effective per-edge [`MeshPolicy`] and must
1705    /// re-check the edge's endpoints against the same membership
1706    /// oracle before it can key a per-edge override off the endpoint
1707    /// tuple. Pre-lift each such consumer was structurally forced to
1708    /// either re-inline the twin `if !names.contains(...)` cascade
1709    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1710    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1711    /// walk to re-check one edge. Post-lift each reaches the axis
1712    /// through one dispatch on the substrate primitive.
1713    ///
1714    /// `:de` runs before `:para` per the canonical edge-direction
1715    /// order the sibling per-arm shape gate
1716    /// [`validate_contrato_caixa`] arm ordering, the self-loop
1717    /// diagnostic string, and every peer arm ordering in
1718    /// [`AplicacaoSpec::validate_contratos`] already use — a
1719    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1720    /// phantom `:para`, preserving byte-equal ordering with the
1721    /// pre-lift inline cascade.
1722    fn require_endpoints_in(
1723        &self,
1724        names: &std::collections::HashSet<&str>,
1725    ) -> Result<(), AplicacaoError> {
1726        if !names.contains(self.source()) {
1727            return Err(AplicacaoError::contrato_member_missing(self.source()));
1728        }
1729        if !names.contains(self.destination()) {
1730            return Err(AplicacaoError::contrato_member_missing(self.destination()));
1731        }
1732        Ok(())
1733    }
1734
1735    /// Typed view of the contract's payload target. Enforces that the
1736    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1737    /// fields agree, and that each carried value is itself
1738    /// value-shape valid:
1739    ///
1740    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1741    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1742    ///     `PathPrefix` invariant — same shape required of `:entrada
1743    ///     :paths`)
1744    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1745    ///     non-empty (NATS / Kafka publish without a subject is a
1746    ///     no-op subscribe, never the author's intent)
1747    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1748    ///     non-empty (an empty slot template addresses the bucket
1749    ///     root, defeating the per-key isolation the slot exists for)
1750    ///   - Anything else ⇒ none of the three; the contract is a pure
1751    ///     typed capability edge with no payload selector.
1752    ///
1753    /// Translates the Apollo Federation discipline ("conflicts are
1754    /// errors at compile time, not warnings at runtime";
1755    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1756    /// a contract whose WIT shape disagrees with its target field, or
1757    /// whose target field carries a value-shape-invalid string, is a
1758    /// build error — not a silent renderer drop. The returned
1759    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1760    /// non-empty (and absolute, for `Http`); every downstream consumer
1761    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1762    /// the M4 per-edge policy resolver) can rely on that without
1763    /// re-checking.
1764    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1765        // Route the HTTP-shaped payload-target extraction through the
1766        // lifted [`WitContract::endpoint`] accessor rather than the raw
1767        // `self.endpoint.as_deref()` field access — the two production
1768        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1769        // payload-carrier scalar (this method's Http-arm payload
1770        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1771        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1772        // off exactly one typed dispatch on the substrate primitive, so
1773        // any future rebrand on the axis (an M4 per-cluster endpoint-
1774        // alias rewrite, a per-CR fully-qualified path prefix the M4
1775        // materializer applies per-tenant, an M4 promotion from
1776        // `Option<String>` to a typed HTTP path-template enum) migrates
1777        // as a single caixa-core edit rather than a coordinated rewrite
1778        // of the two call sites — peer of the sibling M3 per-`:placement`
1779        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1780        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1781        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1782        let endpoint = self.endpoint();
1783        let subject = self.subject();
1784        // Route the store-arm payload-carrier scalar through the
1785        // lifted [`WitContract::slot`] accessor rather than the raw
1786        // `self.slot.as_deref()` field access — the two production
1787        // consumers of the per-`:contratos :slot` key/value-store-
1788        // shaped payload-carrier scalar (this method's Store-arm
1789        // payload extraction, the [`AplicacaoSpec::validate`]
1790        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1791        // arm) now key off exactly one typed dispatch on the substrate
1792        // primitive. Closes the last unlifted per-`:contratos`
1793        // `Option<String>` axis, completing the payload-carrier
1794        // accessor family peer of the sibling per-`:contratos`
1795        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1796        // (90de675) lifts across the HTTP / pub-sub arms.
1797        let slot = self.slot();
1798        // Route the local `(de, para, wit)` triple-projection closure
1799        // through the lifted [`WitContract::edge_triple`] typed accessor
1800        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1801        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1802        // triple-carrying diagnostic constructors below (wrong-target /
1803        // missing-target on all three payload arms + capability-with-
1804        // payload + invalid-wit) now key off exactly one typed dispatch
1805        // on the substrate-primitive composite projection, sibling to
1806        // the peer [`WitContract::edge_pair`]-routed
1807        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1808        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1809        // diagnostic constructors on the same per-`:contratos`
1810        // diagnostic-construction surface.
1811        let edge = || self.edge_triple();
1812
1813        // The `:wit` value drives every downstream dispatch — the
1814        // is_http/is_pubsub/is_store prefix matchers below, the
1815        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1816        // exclusion. Until this gate landed `target()` accepted any
1817        // non-empty string and silently demoted unrecognized shapes to
1818        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1819        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1820        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1821        // package, the paste-from-binary footgun a multi-line blob
1822        // accidentally landing in the slot, the un-percent-encoded
1823        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1824        // routing, got L4-only" footgun. Empty is still pre-checked at
1825        // the [`AplicacaoSpec::validate`] call site via the narrower
1826        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1827        // validate layer); the value-shape gate here picks up the
1828        // structurally-invalid non-empty cases the empty check misses,
1829        // and remains correct under direct `target()` calls outside
1830        // validate (the predicate's defensive empty arm returns a
1831        // parser-shaped reason rather than silently falling through to
1832        // the Capability arm). Same trajectory as c4213a4 (WitContract
1833        // endpoint/subject/slot value-shape gates lifted into
1834        // `target()`) on the peer payload axes.
1835        //
1836        // Routed through the lifted [`WitContract::world_ref`] accessor
1837        // rather than the raw `&self.wit` field access — the two
1838        // production consumers of the per-`:contratos :wit` world-ref
1839        // byte-string on the value-shape axis (this method's invalid-
1840        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1841        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1842        // [`WitContract::identity`]) now key off exactly one typed
1843        // dispatch on the substrate primitive, so any future rebrand on
1844        // the axis (an M4 promotion from `String` to a typed WIT
1845        // world-ref enum once the WIT registry stabilizes in
1846        // tatara-lisp, a per-CR canonicalization pass that lowercases
1847        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1848        // inline-buffer swap on the storage arm) migrates as a single
1849        // caixa-core edit rather than a coordinated rewrite of the two
1850        // call sites — sibling of the peer [`WitContract::endpoint`] /
1851        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1852        // routed payload-carrier extractions above on the same
1853        // [`WitContract::target`] body, completing the per-`:contratos`
1854        // scalar-accessor-routing pass at the last unlifted raw-field-
1855        // access site inside `impl WitContract`. Same "typed dispatch
1856        // composes with typed dispatch, not with raw field access"
1857        // discipline the sibling [`WitContract::edge_pair`] /
1858        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1859        // composite-projection accessors and the
1860        // [`WitContract::is_self_loop`] identity-space predicate
1861        // already route through. Pinned by
1862        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1863        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1864            return Err(AplicacaoError::contrato_wit_invalid(
1865                self.edge_pair(),
1866                self.world_ref(),
1867                reason,
1868            ));
1869        }
1870
1871        if self.is_http() {
1872            if subject.is_some() || slot.is_some() {
1873                return Err(AplicacaoError::contrato_wrong_target(
1874                    edge(),
1875                    WitTarget::HTTP_FIELD_NAME,
1876                ));
1877            }
1878            let ep = endpoint.ok_or_else(|| {
1879                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
1880            })?;
1881            if ep.is_empty() {
1882                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
1883            }
1884            if !ep.starts_with('/') {
1885                return Err(AplicacaoError::contrato_endpoint_not_absolute(
1886                    self.edge_pair(),
1887                    ep,
1888                ));
1889            }
1890            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1891            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1892            // API v1 HTTPPathMatch.value admission grammar with the
1893            // sibling `:entrada :paths` axis. Until this gate landed
1894            // `target()` only refused the empty string + the missing-
1895            // leading-`/` form; a structurally invalid endpoint
1896            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1897            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1898            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1899            // path-traversal segment, the >1024-byte slug) silently
1900            // passed validate and the failure surfaced at apply time
1901            // as a Cilium policy rejection / silent traffic drop, far
1902            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1903            // grammar `:entrada :paths` already gates (55410e4), now
1904            // shared with `:contratos :endpoint` through the lifted
1905            // `crate::render::is_gateway_api_http_path` predicate.
1906            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1907                return Err(AplicacaoError::contrato_endpoint_invalid(
1908                    self.edge_pair(),
1909                    ep,
1910                    reason,
1911                ));
1912            }
1913            return Ok(WitTarget::Http { endpoint: ep });
1914        }
1915        if self.is_pubsub() {
1916            if endpoint.is_some() || slot.is_some() {
1917                return Err(AplicacaoError::contrato_wrong_target(
1918                    edge(),
1919                    WitTarget::PUBSUB_FIELD_NAME,
1920                ));
1921            }
1922            let s = subject.ok_or_else(|| {
1923                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
1924            })?;
1925            if s.is_empty() {
1926                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
1927            }
1928            // The `:subject` lands at runtime as the NATS subject the
1929            // producer publishes to and the consumer subscribes from.
1930            // Until this gate landed `target()` only refused the
1931            // empty string; a structurally invalid subject
1932            // (`"foo..bar"` — empty token between separators,
1933            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1934            // server's subject parser rejects, `"foo bar"` —
1935            // un-percent-encoded whitespace, `"foo.café"` —
1936            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1937            // empty leading/trailing tokens, the >256-byte
1938            // paste-from-binary slug) silently passed validate and
1939            // the failure surfaced at runtime as a NATS server-side
1940            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1941            // a silent message drop, far from the source caixa.lisp.
1942            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1943            // trajectory `:contratos :endpoint` (4f0390b) and
1944            // `:contratos :wit` (6226bf4) already gate, now shared
1945            // with `:contratos :subject` through the lifted
1946            // `crate::render::is_nats_subject` predicate.
1947            if let Err(reason) = crate::render::is_nats_subject(s) {
1948                return Err(AplicacaoError::contrato_subject_invalid(
1949                    self.edge_pair(),
1950                    s,
1951                    reason,
1952                ));
1953            }
1954            return Ok(WitTarget::PubSub { subject: s });
1955        }
1956        if self.is_store() {
1957            if endpoint.is_some() || subject.is_some() {
1958                return Err(AplicacaoError::contrato_wrong_target(
1959                    edge(),
1960                    WitTarget::STORE_FIELD_NAME,
1961                ));
1962            }
1963            let sl = slot.ok_or_else(|| {
1964                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
1965            })?;
1966            if sl.is_empty() {
1967                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
1968            }
1969            // Value-shape gate on the third (and last) typed payload
1970            // axis the `WitContract::target` dispatch carries — the
1971            // peer of [`crate::render::is_gateway_api_http_path`] for
1972            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1973            // for `:subject` (63e18a0). Until this gate landed
1974            // `target()` only refused the empty string; a structurally
1975            // invalid slot (`"check out/$order"` — un-percent-encoded
1976            // whitespace whose runtime behavior varies unpredictably
1977            // across kv backends, `"checkout/\x01order"` — control
1978            // character that Redis admits but corrupts on next read
1979            // and DynamoDB rejects outright, `"chéckout/$order"` —
1980            // un-percent-encoded non-ASCII byte each backend re-encodes
1981            // differently, `"checkout\n/$order"` — embedded newline,
1982            // the 513-byte paste-from-binary slug) silently passed
1983            // validate and surfaced at runtime as a per-backend kv
1984            // write rejection (DynamoDB / etcd) or as a silent
1985            // next-read corruption (Redis-via-RESP3), far from the
1986            // source caixa.lisp with no field naming which `:contratos`
1987            // edge carried the typo. The lifted predicate makes the
1988            // kv-backend intersection-floor a substrate-level
1989            // invariant at validate time, not a runtime "this passed
1990            // validate but the kv backend rejected on first write"
1991            // surprise — closes the typed payload-axis value-shape
1992            // trajectory across all three legs of the four
1993            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1994            // that caixa-mesh + the future kv emitters land in.
1995            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1996                return Err(AplicacaoError::contrato_slot_invalid(
1997                    self.edge_pair(),
1998                    sl,
1999                    reason,
2000                ));
2001            }
2002            return Ok(WitTarget::Store { slot: sl });
2003        }
2004
2005        // Unrecognized WIT world — must not carry any payload target.
2006        if endpoint.is_some() || subject.is_some() || slot.is_some() {
2007            return Err(AplicacaoError::contrato_wrong_target(
2008                edge(),
2009                WitTarget::CAPABILITY_EXPECTED,
2010            ));
2011        }
2012        Ok(WitTarget::Capability)
2013    }
2014
2015    /// Substrate-canonical post-validation projection of the typed
2016    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
2017    /// downstream of an [`AplicacaoSpec`] that has already crossed the
2018    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
2019    /// [`typed_view`]-shaped entry point that composes `validate` into
2020    /// the projection) reaches through when it needs the typed
2021    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
2022    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
2023    /// coherence for every `:contratos` entry. The peer accessor to the
2024    /// [`Self::target`] `Result`-returning validator on the same
2025    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
2026    /// pre-validation validator that computes the projection *and* raises
2027    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
2028    /// (`:wit`, payload) mismatch; this method is the post-validation
2029    /// projection every downstream consumer reaches through once the
2030    /// pre-validation gate has succeeded.
2031    ///
2032    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2033    ///
2034    /// Prior to this lift the "call `.target()` then `.expect(…)` with
2035    /// the same message" pattern sat inline at two production sites with
2036    /// no compile-time link between them: the
2037    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
2038    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
2039    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
2040    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
2041    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
2042    /// (`c.target().expect("validated by typed_view").graph_label()`),
2043    /// each open-coding the same `.target().expect("validated by
2044    /// typed_view")` pair with the message spelled twice. A future
2045    /// vocabulary shift on the panic-message axis (a tightening from
2046    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
2047    /// validate"` as the substrate's validator entry-point vocabulary
2048    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
2049    /// panic to a `debug_assert` under a `--release` build profile) would
2050    /// have had to be threaded through both open-coded call sites in
2051    /// lockstep or one consumer would silently disagree with the peer on
2052    /// which invariant the panic message names. Same "same shape written
2053    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
2054    /// discipline the sibling [`Self::edge_pair`] /
2055    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
2056    /// lifts already establish on the paired composite-projection axis;
2057    /// this lift extends it onto the post-validation typed-view axis.
2058    ///
2059    /// Every future downstream consumer of the projected typed view
2060    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
2061    /// CR materializer's per-edge admission webhook, the future
2062    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
2063    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
2064    /// resolver, the future `feira app graph --l7` / `--pubsub` /
2065    /// `--kv` per-shape column emitters) reaches through this one typed
2066    /// dispatch on the substrate primitive rather than an open-coded
2067    /// per-consumer `.target().expect(…)` pair with the message
2068    /// re-inlined. The invariant the accessor's panic path pins — "this
2069    /// call is only reachable after [`AplicacaoSpec::validate`] has
2070    /// succeeded on the containing spec" — is the substrate's answer to
2071    /// give exactly once, at the primitive, not once per consumer.
2072    ///
2073    /// # Panics
2074    ///
2075    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
2076    /// would return an `Err` — i.e. if this contract's
2077    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
2078    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
2079    /// this accessor only from a code path that has already reached the
2080    /// containing [`AplicacaoSpec`] through a validating entry-point
2081    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
2082    /// [`typed_view`] compose, the future M4 CR admission webhook's
2083    /// per-CR validate). Use [`Self::target`] instead on any pre-
2084    /// validation code path.
2085    ///
2086    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2087    #[must_use]
2088    pub fn target_projected(&self) -> WitTarget<'_> {
2089        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
2090    }
2091
2092    /// Canonical panic message the [`Self::target_projected`]
2093    /// post-validation projection accessor threads through when the
2094    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
2095    /// has succeeded" precondition. Lifted as a `pub const` on the
2096    /// [`WitContract`] surface so the byte-string lives in one place
2097    /// across the substrate — the [`Self::target_projected`] method
2098    /// body, the two prior production call sites' comments now naming
2099    /// the const, and every future consumer that must format-match the
2100    /// panic-message shape (a future test suite that asserts the panic-
2101    /// message byte-string across a fuzzed invalid-contract corpus,
2102    /// a future custom-panic hook in `caixa-operator` that surfaces the
2103    /// message with per-`:contratos` telemetry, the future admission
2104    /// webhook's per-CR validate-error report) reaches through the same
2105    /// canonical `&'static str`. A future rebrand on the panic-message
2106    /// axis (a tightening from `"validated by typed_view"` to `"validated
2107    /// by AplicacaoSpec::validate"` as the substrate's validator
2108    /// entry-point vocabulary sharpens once caixa-core grows a
2109    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
2110    /// [`typed_view`]) lands at one caixa-core edit rather than a
2111    /// coordinated per-consumer sweep — same "one canonical declaration
2112    /// per axis, next to the accessor that reads it" discipline the peer
2113    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
2114    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
2115    /// const family already establishes on the paired per-consumer-axis
2116    /// diagnostic-scalar surface.
2117    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
2118}
2119
2120/// Borrowed identity key for the typed-graph duplicate-`:contratos`
2121/// gate (see [`AplicacaoSpec::validate`]): every field that
2122/// distinguishes one contract from another, in declaration order
2123/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
2124/// with equal [`ContratoIdentity`]s are the same typed edge declared
2125/// twice — the graph-edge analogue of duplicate `:membros` /
2126/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
2127/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
2128/// clippy's `type_complexity` lint (and so a future axis added to
2129/// `WitContract` is one alias edit, not a coordinated rewrite of
2130/// every set instantiation).
2131pub type ContratoIdentity<'a> = (
2132    &'a str,
2133    &'a str,
2134    &'a str,
2135    Option<&'a str>,
2136    Option<&'a str>,
2137    Option<&'a str>,
2138);
2139
2140/// Typed view of a [`WitContract`]'s payload target. Each variant
2141/// carries the field its WIT shape requires; constructing a `Http`
2142/// view without an endpoint is impossible by the type system.
2143///
2144/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
2145/// instead of probing `Option<String>` fields one by one — the
2146/// "which payload field is set?" question is answered once, at
2147/// validation time.
2148#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
2149pub enum WitTarget<'a> {
2150    /// HTTP-shaped WIT world. Carries the configured request path.
2151    Http { endpoint: &'a str },
2152    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
2153    ///
2154    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
2155    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
2156    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
2157    /// method name byte-identical to the sibling
2158    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
2159    /// arm-discriminator that routes through
2160    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
2161    /// through `matches!` on the variant), so the two arm-discriminator
2162    /// axes — target-side variant-arm and shape-side ref-prefix — reach
2163    /// every downstream consumer through the same `is_pubsub()` name.
2164    #[is_variant(name = "pubsub")]
2165    PubSub { subject: &'a str },
2166    /// Key-value-shaped WIT world. Carries the slot template.
2167    Store { slot: &'a str },
2168    /// A typed capability edge with no payload selector — the WIT
2169    /// world stands on its own (rare; reserved for plain capability
2170    /// imports or M4-and-later WIT worlds we haven't shaped yet).
2171    Capability,
2172}
2173
2174impl<'a> WitTarget<'a> {
2175    /// Canonical author-facing `:contratos` payload field name for the
2176    /// HTTP-shaped arm — the `expected: &'static str` scalar the
2177    /// [`AplicacaoError::ContratoMissingTarget`] /
2178    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2179    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
2180    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
2181    /// the `feira app graph` verb prints. Peer of
2182    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
2183    /// on the payload-field-name axis; declared as a peer const next
2184    /// to the [`WitTarget::Http`] variant so a future rename on the
2185    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
2186    /// :endpoint …)))` field lands in exactly one place, not scattered
2187    /// across the [`WitContract::target`] gate's six `expected:`
2188    /// literals, the label template, and every downstream consumer
2189    /// that prints a per-arm prefix. Same trajectory as the peer
2190    /// [`WitTarget::label`] lift (174e96a): a single source of truth
2191    /// for the arm's shape, next to the variant declaration.
2192    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
2193    /// Canonical author-facing `:contratos` payload field name for the
2194    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
2195    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
2196    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2197    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
2198    /// Canonical author-facing `:contratos` payload field name for the
2199    /// key/value-store-shaped arm. Peer of
2200    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
2201    /// on the payload-field-name axis; see
2202    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2203    pub const STORE_FIELD_NAME: &'static str = "slot";
2204
2205    /// Canonical stable human-readable label the payload-less
2206    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
2207    /// the byte-string every consumer that formats a payload-less
2208    /// typed capability edge as text lands on (the
2209    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
2210    /// naming which identical edge was declared twice, the future
2211    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
2212    /// policy resolver's audit view, the operator's mesh-graph audit).
2213    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
2214    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
2215    /// author-facing label-scalar consts — the same
2216    /// "one canonical declaration per arm, next to the variant, so a
2217    /// future rename lands in one place" discipline extended to the
2218    /// payload-less arm. Until this lift landed the byte-string sat
2219    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
2220    /// match arm, once in the pin test asserting the label's
2221    /// [`WitTarget::Capability`] output — with no compile-time link
2222    /// between the two: a rebrand on either side (an operator-facing
2223    /// vocabulary shift, a per-consumer disambiguation like
2224    /// `"(capability — no payload; typed edge only)"`) would silently
2225    /// desynchronize until a downstream consumer surfaced the drift at
2226    /// runtime.
2227    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
2228
2229    /// Canonical `expected:` scalar the
2230    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2231    /// through for the payload-less [`WitTarget::Capability`] arm — the
2232    /// byte-string authors read as "this WIT world's shape is not one
2233    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
2234    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
2235    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2236    /// [`Self::STORE_FIELD_NAME`] consts on the
2237    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
2238    /// same "which payload field name goes in the diagnostic" dispatch
2239    /// the three payload-arm consts cover, extended to the payload-less
2240    /// arm. Until this lift landed the byte-string sat twice — once
2241    /// inline in the [`Self::target`] Capability-arm rejection at the
2242    /// production dispatch, once in the pin test asserting the
2243    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
2244    /// no compile-time link between the two: a rebrand on either side
2245    /// (an author-facing vocabulary shift to `"capability"` /
2246    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
2247    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
2248    /// [`WitTarget::Capability`] into per-shape peers) would silently
2249    /// desynchronize until a downstream consumer surfaced the drift at
2250    /// runtime. Same "one canonical declaration per arm, next to the
2251    /// variant, so a future rename lands in one place" discipline the
2252    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
2253    /// established for the payload-less arm's human-readable label
2254    /// axis; this lift extends it onto the peer diagnostic-scalar axis
2255    /// so both halves of the "how does the Capability arm surface at
2256    /// its two consumer axes (human-readable label, wrong-target
2257    /// diagnostic)" pipeline route through peer consts declared next
2258    /// to the variant.
2259    ///
2260    /// Pairwise-distinctness against the three payload-arm scalars
2261    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2262    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
2263    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
2264    /// test — the 4-way closure of the 3-way
2265    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
2266    /// the `ContratoWrongTarget::expected` axis, matching the peer
2267    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
2268    /// scalar-value distinctness discipline the sibling M3 typed-enum
2269    /// discriminator axis already carries.
2270    pub const CAPABILITY_EXPECTED: &'static str = "none";
2271
2272    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
2273    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
2274    /// as under [`Self::graph_label`] — the sibling
2275    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
2276    /// payload-column axis (the graph verb spells payload-less as
2277    /// `(capability-only)`, distinct from the duplicate-`:contratos`
2278    /// diagnostic's `(capability — no payload)` on the human-readable
2279    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
2280    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
2281    /// family — extends the "one canonical declaration per arm, next to
2282    /// the variant, so a future rename lands in one place" discipline
2283    /// onto the third payload-less-arm consumer axis (`feira app graph`
2284    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
2285    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
2286    /// axis).
2287    ///
2288    /// Until this lift landed the byte-string sat inline in
2289    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
2290    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
2291    /// `"(capability-only)".to_string()` literal, with no compile-time link
2292    /// back to the [`WitTarget::Capability`] variant declaration nor to
2293    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
2294    /// peer consts already carrying the "one canonical declaration per
2295    /// payload-less-arm consumer axis" discipline. A rebrand on either
2296    /// side (the graph verb's operator-facing vocabulary tightening from
2297    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
2298    /// the WIT registry vocabulary sharpens, an M4 split of
2299    /// [`Self::Capability`] into per-shape peers) would silently
2300    /// desynchronize the graph-verb byte-string from the paired
2301    /// per-arm-adjacent const and land two spellings of the same axis in
2302    /// two spots.
2303    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
2304
2305    /// The `(author-facing field name, payload)` pair this typed target
2306    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
2307    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
2308    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
2309    /// [`Self::Store`], `None` for the payload-less
2310    /// [`Self::Capability`] arm.
2311    ///
2312    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
2313    /// (formats `":{field} {payload:?}"` on `Some`, falls to
2314    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
2315    /// (returns the first component) route through, so a future
2316    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
2317    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
2318    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
2319    /// exactly one new match-arm here (a compile-time exhaustiveness
2320    /// error otherwise), not a coordinated three-way rewrite of the
2321    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
2322    /// + every downstream consumer that reaches for the pair.
2323    ///
2324    /// Until this lift landed the three payload arms sat in
2325    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
2326    /// invocations (one per variant, each hand-quoting the paired
2327    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2328    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
2329    /// "same shape, written N times" duplication THEORY.md §I.3.5
2330    /// ("Generation first, composition second, hand-authoring last;
2331    /// the duplication budget is zero") promotes to a build-time
2332    /// concern, with each per-arm site paired to its own const with no
2333    /// compile-time link between the format template and the arm's
2334    /// payload extraction.
2335    #[must_use]
2336    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
2337        match *self {
2338            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
2339            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
2340            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
2341            WitTarget::Capability => None,
2342        }
2343    }
2344
2345    /// The canonical author-facing `:contratos` payload field name
2346    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2347    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2348    /// `None` for the payload-less `Capability` arm.
2349    ///
2350    /// Routes through [`Self::payload_pair`] — the single 4-arm
2351    /// dispatch [`Self::label`] also reads — so a future variant
2352    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2353    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2354    /// dispatch, thin projections at each consumer" trajectory the
2355    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2356    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2357    #[must_use]
2358    pub const fn field_name(&self) -> Option<&'static str> {
2359        match self.payload_pair() {
2360            Some((f, _)) => Some(f),
2361            None => None,
2362        }
2363    }
2364
2365    /// The underlying scalar the payload-carrying arm carries — the
2366    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2367    /// subject ([`Self::PubSub`] `:subject`), or slot template
2368    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2369    /// `&'a str` storage — or `None` on the payload-less
2370    /// [`Self::Capability`] arm.
2371    ///
2372    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2373    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2374    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2375    /// the paired sub-selector axis. Both per-half accessors read from
2376    /// one authoritative match, so a future [`WitTarget`] variant
2377    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2378    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2379    /// on [`Self::payload_pair`] and both per-half projections + every
2380    /// downstream consumer picks the new arm up by construction — no
2381    /// coordinated N-way rewrite across the paired accessor dispatches,
2382    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2383    /// and every future WIT-registry-shaped consumer.
2384    ///
2385    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2386    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2387    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2388    /// both per-half projections as thin readers, every downstream
2389    /// consumer through the same match" discipline extended onto the
2390    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2391    /// gap between the two paired-dispatch surfaces: the peer
2392    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2393    /// the first-component projection until this lift; the second-
2394    /// component sibling now sits alongside so both halves reach every
2395    /// future consumer through the same substrate-primitive dispatch.
2396    ///
2397    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2398    #[must_use]
2399    pub const fn payload(&self) -> Option<&'a str> {
2400        match self.payload_pair() {
2401            Some((_, p)) => Some(p),
2402            None => None,
2403        }
2404    }
2405
2406    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2407    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2408    /// returns the [`Self::Http`]-arm's author-declared request path
2409    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2410    /// projected target is [`Self::Http { endpoint }`], `None` on the
2411    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2412    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2413    /// definition).
2414    ///
2415    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2416    /// `path:` rule payload every substrate-side L7-introspecting
2417    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2418    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2419    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2420    /// on the L7 introspection branch; every peer WIT shape stays
2421    /// L4-only because Cilium can't introspect NATS / key-value / plain
2422    /// capability edges), and every future L7-introspecting consumer
2423    /// of the projected target's HTTP endpoint (the future M4
2424    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2425    /// materializer's per-edge L7 admission-webhook overlay, the
2426    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2427    /// path bucket-key resolver, the future per-`:contratos`-edge
2428    /// mTLS-required overlay's HTTP-shape scope filter, the future
2429    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2430    /// through the same typed dispatch.
2431    ///
2432    /// Prior to this lift the sole production consumer of the projected-
2433    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2434    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2435    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2436    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2437    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2438    /// match that expressed no compile-time link back to the substrate
2439    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2440    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2441    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2442    /// with no post-projection peer on the typed-view surface. A future
2443    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2444    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2445    /// gRPC-shaped worlds per this enum's own docstring at
2446    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2447    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2448    /// would have had to be threaded through the caixa-mesh L7 emit
2449    /// branch's raw `if let` in lockstep — either coalescing the two
2450    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2451    /// emit path per-arm — with no substrate-primitive dispatch making
2452    /// the "which arms count as L7-HTTP-shaped for path-emission
2453    /// purposes" question the substrate's answer to give. Lifting the
2454    /// resolution to a typed method on the substrate primitive means
2455    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2456    /// projected-target HTTP endpoint reaches for exactly one typed
2457    /// dispatch — the resolver's accept-set migrates as a unit on any
2458    /// future arm-family widening, and the caixa-mesh L7 emit branch
2459    /// reads through the same substrate primitive.
2460    ///
2461    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2462    /// (7020470) `Option<&str>` scalar accessor on the raw
2463    /// `:contratos :endpoint` field-access axis — same "one typed
2464    /// dispatch on the substrate primitive, thin projections at each
2465    /// consumer" discipline extended onto the peer post-projection typed-
2466    /// view surface (the [`WitContract::endpoint`] pre-projection
2467    /// accessor returns `Some` for any author-declared `:endpoint`
2468    /// value regardless of the paired `:wit` world's HTTP-shape
2469    /// classification — the raw slot before validation crosses it —
2470    /// while this post-projection [`Self::http_endpoint`] accessor
2471    /// returns `Some` iff the target has been projected onto the
2472    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2473    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2474    /// coherence; the two accessors close the pre-projection /
2475    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2476    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2477    /// the three payload-carrying arms) — extends the per-arm
2478    /// projection family onto the [`Self::Http`] specialization axis
2479    /// that the pan-arm accessor's shape blends into a single arm-
2480    /// agnostic view; paired with [`Self::pubsub_subject`] /
2481    /// [`Self::store_slot`] on the sibling per-arm axes so every
2482    /// per-payload-arm shape carries a named post-projection accessor
2483    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2484    /// accept-set the substrate primitive owns.
2485    #[must_use]
2486    pub const fn http_endpoint(&self) -> Option<&'a str> {
2487        match *self {
2488            WitTarget::Http { endpoint } => Some(endpoint),
2489            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2490        }
2491    }
2492
2493    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2494    /// consumer that fans on the pub-sub-shaped payload keys off —
2495    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2496    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2497    /// the projected target is [`Self::PubSub { subject }`], `None` on
2498    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2499    /// [`Self::Capability`], each of which carries no NATS-shaped
2500    /// subject by definition).
2501    ///
2502    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2503    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2504    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2505    /// CR materializer's `spec.subjects[]` projection, the future
2506    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2507    /// bucket-key resolver, the future `feira app graph --pubsub`
2508    /// per-Aplicacao subject column, any future substrate-lifted
2509    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2510    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2511    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2512    /// future pub-sub-shape consumer reaches for the same typed
2513    /// dispatch this accessor exposes so the "which arm carries the
2514    /// subject scalar?" answer lives at one caixa-core edit rather
2515    /// than open-coded across per-consumer `if let WitTarget::PubSub
2516    /// { subject } = c.target()…` pattern-matches.
2517    ///
2518    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2519    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2520    /// the pre-projection [`WitContract::subject`] scalar accessor on
2521    /// the raw `:contratos :subject` field-access axis — same "one
2522    /// typed dispatch on the substrate primitive, thin projections at
2523    /// each consumer" discipline extended onto the per-arm pub-sub
2524    /// post-projection axis. The pre-projection accessor returns
2525    /// `Some` for any author-declared `:subject` value regardless of
2526    /// the paired `:wit` world's pub-sub-shape classification (the raw
2527    /// slot before validation crosses it); this post-projection
2528    /// accessor returns `Some` iff the target has been projected onto
2529    /// the [`Self::PubSub`] arm, i.e. only after the
2530    /// [`WitContract::target`] gate has admitted the
2531    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2532    /// the pre-/post-projection pair on the pub-sub-subject axis to
2533    /// match the pair the [`WitContract::endpoint`] +
2534    /// [`Self::http_endpoint`] surfaces already close on the peer
2535    /// HTTP-endpoint axis.
2536    ///
2537    /// Sibling of the unified pan-arm [`Self::payload`]
2538    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2539    /// extends the per-arm projection family onto the [`Self::PubSub`]
2540    /// specialization axis that the pan-arm accessor's shape blends
2541    /// into a single arm-agnostic view; the pair
2542    /// (`pubsub_subject`, `store_slot`) closes the trio
2543    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2544    /// payload arm now carries its own per-arm-shape post-projection
2545    /// accessor.
2546    #[must_use]
2547    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2548        match *self {
2549            WitTarget::PubSub { subject } => Some(subject),
2550            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2551        }
2552    }
2553
2554    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2555    /// every consumer that fans on the store-shaped payload keys off —
2556    /// returns the [`Self::Store`]-arm's author-declared slot template
2557    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2558    /// projected target is [`Self::Store { slot }`], `None` on the
2559    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2560    /// [`Self::Capability`], each of which carries no
2561    /// key/value-store slot by definition).
2562    ///
2563    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2564    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2565    /// every future substrate-side store-introspecting per-`(:de,
2566    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2567    /// namespace / prefix reconciler's per-slot projection, the future
2568    /// per-store-backend routing overlay's slot-shape gate, the future
2569    /// `feira app graph --store` per-Aplicacao slot column, any future
2570    /// substrate-lifted store-shape emitter that reads a projected
2571    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2572    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2573    /// Every future store-shape consumer reaches for the same typed
2574    /// dispatch this accessor exposes so the "which arm carries the
2575    /// slot scalar?" answer lives at one caixa-core edit rather than
2576    /// open-coded across per-consumer
2577    /// `if let WitTarget::Store { slot } = c.target()…`
2578    /// pattern-matches.
2579    ///
2580    /// Peer of the sibling [`Self::http_endpoint`] +
2581    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2582    /// axes and of the pre-projection [`WitContract::slot`] scalar
2583    /// accessor on the raw `:contratos :slot` field-access axis — same
2584    /// "one typed dispatch on the substrate primitive, thin projections
2585    /// at each consumer" discipline extended onto the per-arm store
2586    /// post-projection axis. Closes the pre-/post-projection pair on
2587    /// the store-slot axis to match the pairs the
2588    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2589    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2590    /// already close on the peer HTTP-endpoint and pub-sub-subject
2591    /// axes; the substrate-side pre-/post-projection accessor family
2592    /// now spans all three payload arms as a matched trio, so any
2593    /// future arm-shape widening (a `Rest`/`Grpc` split of
2594    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2595    /// lands one accessor without threading through the sibling
2596    /// pre-projection or the peer per-arm post-projection surfaces a
2597    /// compile-time exhaustiveness error at the substrate primitive,
2598    /// not a silent per-consumer split at renderer emit time.
2599    ///
2600    /// Sibling of the unified pan-arm [`Self::payload`]
2601    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2602    /// closes the per-arm projection family onto the [`Self::Store`]
2603    /// specialization axis that the pan-arm accessor's shape blends
2604    /// into a single arm-agnostic view. The trio
2605    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2606    /// pan-arm accept-set on every payload-carrying arm: exactly one
2607    /// per-arm accessor returns `Some(payload)` and the two peers
2608    /// return `None`, and every payload-less [`Self::Capability`]
2609    /// input returns `None` on all three — the partition the sibling
2610    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2611    /// pin locks in load-bearing.
2612    #[must_use]
2613    pub const fn store_slot(&self) -> Option<&'a str> {
2614        match *self {
2615            WitTarget::Store { slot } => Some(slot),
2616            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2617        }
2618    }
2619
2620    /// Render this typed target as a stable human-readable label
2621    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2622    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2623    /// the WIT world is a pure capability edge).
2624    ///
2625    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2626    /// gate so the diagnostic names *which* identical edge was
2627    /// declared twice (not just which `(de, para, wit)` triple).
2628    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2629    /// on the payload-carrying arms (`Some((field, payload)) →
2630    /// format!(":{field} {payload:?}")`) and through the lifted
2631    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2632    /// [`Self::Capability`] arm — so a future variant addition (the
2633    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2634    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2635    /// `Queue`-shaped peer) becomes a single new match-arm on
2636    /// [`Self::payload_pair`] rather than a rewrite of this template
2637    /// (and every downstream consumer that reaches for the label
2638    /// shape: the per-edge policy resolver in M4, the `feira app
2639    /// graph` view, the operator's mesh-graph audit). Until this
2640    /// lift landed the three payload arms carried three near-identical
2641    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2642    /// [`Self::Capability`] arm carried the payload-less byte-string
2643    /// twice (once inline here, once in the pin test) — closing the
2644    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2645    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2646    /// / 4a1e490) peer-const lifts already established for the
2647    /// payload-carrying arms.
2648    #[must_use]
2649    pub fn label(&self) -> String {
2650        match self.payload_pair() {
2651            Some((field, payload)) => format!(":{field} {payload:?}"),
2652            None => Self::CAPABILITY_LABEL.to_string(),
2653        }
2654    }
2655
2656    /// Render this typed target as the `feira app graph` per-`:contratos`
2657    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2658    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2659    /// payload-less arm).
2660    ///
2661    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2662    /// on the payload-carrying arms (`Some((field, payload)) →
2663    /// format!("{field}={payload}")`) and through the lifted
2664    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2665    /// [`Self::Capability`] arm — so a future variant addition
2666    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2667    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2668    /// `Queue`-shaped peer) becomes one match-arm edit at
2669    /// [`Self::payload_pair`], propagating through this graph-verb
2670    /// projection at zero call-site cost, sibling to the peer
2671    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2672    /// same 4-arm dispatch.
2673    ///
2674    /// Until this lift landed the [`caixa-feira`]
2675    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2676    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2677    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2678    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2679    /// `format!("{}={endpoint}", ...)` template and hard-coding
2680    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2681    /// back to the paired [`WitTarget::Capability`] variant declaration.
2682    /// A future variant addition would have had to be threaded through
2683    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2684    /// verb's inline match in lockstep or the two projections would
2685    /// silently disagree on the arm-set the graph verb prints — the
2686    /// duplicate-`:contratos` diagnostic reading one shape while the
2687    /// graph verb's payload column silently dropped the new arm to
2688    /// `(capability-only)`. Lifting the graph-verb projection onto the
2689    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2690    /// the axis: both projections migrate as a unit.
2691    ///
2692    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2693    /// quoting) shape is graph-verb-canonical — distinct from the
2694    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2695    /// duplicate-`:contratos` diagnostic seeds (see
2696    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2697    /// on the payload-less axis for the paired distinction).
2698    #[must_use]
2699    pub fn graph_label(&self) -> String {
2700        match self.payload_pair() {
2701            Some((field, payload)) => format!("{field}={payload}"),
2702            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2703        }
2704    }
2705}
2706
2707/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2708/// pretty-printed byte-string every consumer that formats a typed
2709/// payload target as user-facing text lands on (the
2710/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2711/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2712/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2713/// graph` per-`:contratos`-edge payload column that reaches the graph
2714/// verb through `format!("{target}")`, the future M4 per-edge policy
2715/// resolver's per-edge audit-log line, the operator's mesh-graph
2716/// per-edge inspection view) reaches for the same lifted
2717/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2718/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2719/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2720/// routes through — extending the three-path-convergence
2721/// (`Debug` for structural inspection, `Display` for user-facing text,
2722/// per-arm typed accessor for the canonical byte-string) discipline the
2723/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2724/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2725/// onto the fourth (and only remaining) typed-shape-discriminator axis
2726/// on the caixa surface.
2727///
2728/// Pre-lift the two paths were structurally independent — every consumer
2729/// reaching for a payload byte-string past the [`WitTarget::label`]
2730/// helper had to pick between three paths ([`WitTarget::label`],
2731/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2732/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2733/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2734/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2735/// that reached for `format!("{target}")` — the canonical shape every
2736/// user-facing pretty-print site on the sibling typed-enum axes already
2737/// uses — would silently land on the `Debug` derive's structural output
2738/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2739/// than the `label()` helper's stable byte-string (`:endpoint
2740/// "/charge"` — the author-facing `:contratos` keyword form) the
2741/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2742/// already threads through. The two spellings would diverge silently in
2743/// every downstream diagnostic / graph / audit line reached through
2744/// `format!` rather than through the `label()` helper. Routing
2745/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2746/// path: every `format!("{v}")` call reaches the same
2747/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2748/// and the duplicate-`:contratos` gate already route through, so a
2749/// future variant addition (the M4-and-later per-edge WIT registry may
2750/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2751/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2752/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2753/// match — rather than fanning out through hand-rolled per-arm
2754/// [`std::fmt::Display`] arms.
2755///
2756/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2757/// is the typed view returned by [`WitContract::target`], not a
2758/// closed-set discriminator enum with a gen-platform Discriminant
2759/// registration, so the `Debug` derive's structural output (which every
2760/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2761/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2762/// shape for structural inspection; `Display` (via `label`) reveals the
2763/// stable author-facing payload projection.
2764///
2765/// Pin tests
2766/// [`tests::wit_target_display_routes_through_label_helper`] and
2767/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2768/// assert the two paths agree byte-for-byte on every variant, so a
2769/// future variant addition or `label()` reimplementation that hand-rolls
2770/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2771/// build error visible at caixa-core test time, not a silent
2772/// per-consumer dispatch miss at diagnostic / audit / graph time.
2773impl std::fmt::Display for WitTarget<'_> {
2774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2775        f.write_str(&self.label())
2776    }
2777}
2778
2779// ── one Aplicacao member ─────────────────────────────────────────────
2780
2781/// A Servico participating in the Aplicacao. Same shape as
2782/// `crate::supervisor::ChildSpec` but without a restart policy —
2783/// supervision is per-Servico (each member has its own
2784/// `:supervisor`), the Aplicacao orchestrates *placement*.
2785#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2786#[serde(rename_all = "camelCase")]
2787pub struct Membro {
2788    /// Member caixa's `:nome`. Resolves through the same dep
2789    /// resolution path as `crate::dep::Dep`.
2790    pub caixa: String,
2791
2792    /// Semver constraint.
2793    pub versao: String,
2794}
2795
2796impl Membro {
2797    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2798    /// accessor every consumer that reads the member's Servico identity
2799    /// keys off — returns the author-declared `:membros :caixa`
2800    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2801    /// own [`String`] storage.
2802    ///
2803    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2804    /// participating in the Aplicacao — validated by
2805    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2806    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2807    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2808    /// [`validate_no_self_membership`]) — and every downstream consumer
2809    /// that fans on the member's identity keys off this scalar (the
2810    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2811    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2812    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2813    /// identity, the self-membership gate, the
2814    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2815    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2816    /// CR materializer's per-member resolver).
2817    ///
2818    /// Prior to this lift the `.caixa` byte-string was read inline at
2819    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2820    /// set collector at
2821    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2822    /// [`validate_membros`] validation-side member-caixa gate at
2823    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2824    /// per-member duplicate-gate dedup key at
2825    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2826    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2827    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2828    /// [`validate_no_self_membership`] self-loop gate at
2829    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2830    /// expressed no compile-time link back to the typed slot. Every
2831    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2832    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2833    /// `name:` axis, so a future extension of the `:membros :caixa`
2834    /// axis to a richer author surface — a per-cluster alias table the
2835    /// operator pins through a future `:placement`-scoped slot, a
2836    /// namespace-qualified rewrite the M4 CR materializer applies
2837    /// per-CR, a per-member overlay from the future `:membros
2838    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2839    /// acknowledges — would have had to be threaded through every
2840    /// open-coded copy in lockstep or one consumer would silently
2841    /// disagree with the peers on which caixa a given member resolves
2842    /// to. A member-set lookup that treated the name as `"cart"` while
2843    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2844    /// silently split the `:contratos` membership-lookup diagnostic from
2845    /// the cycle-detector's node identity — a two-consumer split at the
2846    /// validator far from the source `caixa.lisp` with no field naming
2847    /// the identity-drift root cause. Lifting the resolution rule to a
2848    /// typed method on the substrate primitive means every downstream
2849    /// consumer of the Aplicacao's per-`:membros` identity surface
2850    /// reaches for exactly one typed dispatch — the resolver's
2851    /// accept-set migrates as a unit on any future axis addition.
2852    ///
2853    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2854    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2855    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2856    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2857    /// destination-Servico scalar accessors — same "one typed dispatch
2858    /// on the substrate primitive, thin projections at each consumer"
2859    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2860    /// byte-string axis. Named `nome()` to match the tatara-lisp
2861    /// author-surface term the field's docstring already reaches for
2862    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2863    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2864    /// already carries — the accessor's name maps directly onto the
2865    /// canonical caixa-identity vocabulary rather than shadowing the
2866    /// field's storage-side `caixa` label.
2867    #[must_use]
2868    pub const fn nome(&self) -> &str {
2869        self.caixa.as_str()
2870    }
2871
2872    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2873    /// requirement scalar accessor every consumer that reads the
2874    /// member's version pin keys off — returns the author-declared
2875    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2876    /// from the typed slot's own [`String`] storage.
2877    ///
2878    /// The `:membros :versao` slot carries the Cargo-shaped semver
2879    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2880    /// pins which release of the member-caixa the Aplicacao composes
2881    /// against — the same requirement grammar the peer `:deps :versao`
2882    /// / `:children :versao` axes carry, resolved through the shared
2883    /// [`crate::render::require_valid_versao_requirement`] cascade and
2884    /// the shared [`crate::version::parse_requirement`] parser. Every
2885    /// downstream consumer that fans on the member's version pin keys
2886    /// off this scalar (the [`validate_membros`] per-member requirement
2887    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2888    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2889    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2890    /// version-lock overlay the operator pins through a future
2891    /// `:placement`-scoped slot, the future
2892    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2893    /// version resolver, the future `feira app deploy` pipeline's
2894    /// per-member lacre BLAKE3-closure lookup).
2895    ///
2896    /// Prior to this lift the `.versao` byte-string was accessed inline
2897    /// at two `&str`-shaped sites — the [`validate_membros`]
2898    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2899    /// …)` and the `feira app graph` per-member printer's `println!(
2900    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2901    /// prior to this lift) — two open-coded field-accesses that expressed
2902    /// no compile-time link back to the typed slot. A future extension of
2903    /// the `:membros :versao` axis to a richer author surface (a
2904    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2905    /// flow, a lacre-projected concrete-version rewrite the operator
2906    /// materializes at CR-admission time, a future `:membros :versao-lock`
2907    /// per-cluster override slot) would have had to be threaded through
2908    /// every open-coded copy in lockstep or one consumer would silently
2909    /// disagree with the peers on which release constraint a given
2910    /// member resolves to. Lifting the resolution rule to a typed method
2911    /// on the substrate primitive means every downstream requirement-
2912    /// facing consumer reaches for exactly one typed dispatch — the
2913    /// resolver's accept-set migrates as a unit on any future axis
2914    /// addition.
2915    ///
2916    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2917    /// member-caixa `:nome` scalar accessor — the pair
2918    /// `(nome(), versao_requirement())` jointly projects the
2919    /// `(caixa, versao)` field pair every renderer that fans on
2920    /// per-member identity + version pin keys off, closing the last
2921    /// unlifted per-`:membros` scalar axis so every downstream
2922    /// per-`:membros` reader now routes through a typed dispatch on the
2923    /// substrate primitive. Named `versao_requirement()` rather than
2924    /// `versao()` because the field's storage-side `.versao` label is
2925    /// already the author-surface term (`:versao`); the accessor's name
2926    /// carries the semantic role — the semver *requirement* string the
2927    /// shared [`crate::version::parse_requirement`] entry-point consumes
2928    /// — so a raw field access and a typed dispatch read differently at
2929    /// every consumer site.
2930    ///
2931    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2932    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2933    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2934    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2935    /// destination-Servico scalar accessors — same "one typed dispatch
2936    /// on the substrate primitive, thin projections at each consumer"
2937    /// discipline extended onto the per-`:membros` member-`:versao`
2938    /// semver-requirement byte-string axis.
2939    #[must_use]
2940    pub const fn versao_requirement(&self) -> &str {
2941        self.versao.as_str()
2942    }
2943}
2944
2945// ── mesh-level policies ──────────────────────────────────────────────
2946
2947/// Mesh policies that apply to every `:contratos` edge unless
2948/// overridden per-edge in M4. V0 is a single global policy block.
2949#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2950#[serde(rename_all = "camelCase")]
2951pub struct MeshPolicy {
2952    /// Per-call timeout. Authored as a duration string (`"30s"`).
2953    #[serde(
2954        default,
2955        skip_serializing_if = "Option::is_none",
2956        with = "supervisor::duration_codec"
2957    )]
2958    pub timeout: Option<Duration>,
2959
2960    /// Number of retries on transient failure. None = no retries.
2961    #[serde(default, skip_serializing_if = "Option::is_none")]
2962    pub retries: Option<u32>,
2963
2964    /// Circuit breaker config. Trips after N failures within W
2965    /// duration; closes after a cooldown.
2966    #[serde(default, skip_serializing_if = "Option::is_none")]
2967    pub circuit_breaker: Option<CircuitBreaker>,
2968
2969    /// Whether mTLS is required for every contrato. Default: true
2970    /// (sandboxing-by-default; explicit opt-out only).
2971    #[serde(default, skip_serializing_if = "Option::is_none")]
2972    pub mtls_required: Option<bool>,
2973
2974    /// Token-bucket rate limit. Authored as `"100/s"` or
2975    /// `"5000/m"`; stored as `(rate, window)`.
2976    #[serde(
2977        default,
2978        skip_serializing_if = "Option::is_none",
2979        with = "rate_limit_codec"
2980    )]
2981    pub rate_limit: Option<RateLimit>,
2982}
2983
2984/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
2985/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
2986/// constructor rather than the derive-generated per-field
2987/// `<Option<_> as Default>::default` cascade — one source of truth for
2988/// the "canonical unset per-`:politicas` slot" shape across the two
2989/// paths every downstream consumer already reaches through (the
2990/// derived-until-now [`Default::default`] the `..Default::default()`
2991/// struct-update-syntax on every one-axis-under-test fixture in this
2992/// crate's test module rests on, and the `pub const fn`
2993/// [`MeshPolicy::empty`] constructor every `const`-context consumer
2994/// reaches through).
2995///
2996/// Prior to this fold the two paths were byte-equal by *coincidence*
2997/// under the pinning test
2998/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
2999/// byte-equal by *construction* — the derive-generated
3000/// [`Default::default`] resolved each `Option<_>` field through its
3001/// own `<Option<_> as Default>::default` (which returns `None`) and
3002/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
3003/// `None` arms verbatim in its struct-literal. Two hand-authored (or
3004/// derive-authored) sources of the same "canonical unset baseline"
3005/// shape on the same primitive is exactly the substrate-canonical-
3006/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
3007/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
3008/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
3009/// forward `const`-context path — extending the same discipline onto
3010/// the paired [`Default`] impl means every consumer of the derived-
3011/// until-now [`Default::default`] surface (every `..Default::default()`
3012/// struct-update-syntax fixture in this crate's test module — the
3013/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
3014/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
3015/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
3016/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
3017/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
3018/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
3019/// M4 per-edge `:politicas` overlay CR materializer's admission-time
3020/// default-overlay-emit gate, every future `..Default::default()`
3021/// struct-update-syntax fixture-builder arm) also routes through the
3022/// substrate primitive's single source of truth.
3023///
3024/// A future extension of the `:politicas` axis set (a per-edge
3025/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
3026/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
3027/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3028/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3029/// reaches this impl's return value through exactly one edit on
3030/// [`MeshPolicy::empty`] — the derived path could silently disagree
3031/// with the constructor's shape on any new field whose
3032/// `Default::default` is not `None` (a future non-`Option<_>` field
3033/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
3034/// defaulting to an empty vector, an enum arm-carrying field with a
3035/// non-`Default::default` canonical unset arm), while this delegated
3036/// impl reaches the constructor directly and picks up every future
3037/// extension by construction.
3038///
3039/// Direct peer of [`crate::LimitsSpec`]'s
3040/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
3041/// the M2 `:limits` typed slot — same "one source of truth for the
3042/// canonical unset baseline" discipline extended onto the M3
3043/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
3044/// on the M2 `:behavior` slot is the third and last established
3045/// candidate for the same delegation fold once the per-slot peer pin
3046/// on this axis lands in a future run. Pinned load-bearing by
3047/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
3048/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
3049/// sharpening the pre-existing
3050/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
3051/// paths byte-equal by coincidence" invariant into a "two paths
3052/// byte-equal by construction — one delegates to the other" invariant)
3053/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
3054/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
3055/// value-shape gate is `if let Some(_)` guarded and every cross-axis
3056/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
3057/// `let (Some(_), Some(_))` pattern, so an all-`None` input
3058/// structurally short-circuits every arm; the pin makes the invariant
3059/// load-bearing so a future extension that adds a non-`Option`-guarded
3060/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
3061/// rather than at a downstream consumer that composed
3062/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
3063/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
3064impl Default for MeshPolicy {
3065    #[inline]
3066    fn default() -> Self {
3067        Self::empty()
3068    }
3069}
3070
3071impl MeshPolicy {
3072    /// Substrate-canonical `const`-context peer of the derived
3073    /// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
3074    /// per-`:politicas` slot (every one of the five `Option<_>`-carrying
3075    /// per-axis fields set to `None`), materializable at `const`-eval
3076    /// time.
3077    ///
3078    /// Named `empty()` (not `default()` / `new()`) to match the sibling
3079    /// `is_empty()` predicate on the same primitive: the pair
3080    /// (`empty()` / `is_empty()`) forms the round-trip discipline
3081    /// `MeshPolicy::empty().is_empty() == true` the pin
3082    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3083    /// locks load-bearing, and every `const`-context consumer that
3084    /// wants a canonical unset baseline reads through this constructor
3085    /// rather than the derived (non-`const`) [`Default::default`] or
3086    /// the five-field struct-literal `MeshPolicy { timeout: None,
3087    /// retries: None, circuit_breaker: None, mtls_required: None,
3088    /// rate_limit: None }` open-coded per-site.
3089    ///
3090    /// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
3091    /// M2 `:limits` typed slot — same "`const`-context peer of the
3092    /// derived non-`const` [`Default::default`]" discipline extended
3093    /// onto the M3 `:politicas` typed slot. The two lifted `pub const
3094    /// fn` constructors together now cover the two per-slot
3095    /// [`Default`]-carrying M2/M3 typed slots that also carry an
3096    /// `is_empty()` emptiness predicate: every `const`-context consumer
3097    /// of a canonical unset per-slot baseline reads through the same
3098    /// paired-`(empty(), is_empty())` shape on either slot without a
3099    /// runtime dispatch on the derived [`Default::default`].
3100    ///
3101    /// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
3102    /// was reached through one of two paths — the derived
3103    /// [`Default::default`] (`fn`, not `const fn` — a downstream
3104    /// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
3105    /// because [`Default::default`] is not `const`-stable on stable
3106    /// Rust; the tracking issue on `const Default` still blocks the
3107    /// promotion) or an open-coded struct-literal with five `None`
3108    /// arms threaded verbatim at every call site (the five
3109    /// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
3110    /// `MeshPolicy { retries: Some(_), ..Default::default() }` /
3111    /// sibling per-axis-only fixtures in this crate's own test module
3112    /// each rest on `..Default::default()` for the four peer arms; a
3113    /// future axis addition silently drifts the fixture's intent from
3114    /// "one axis under test, the other four unset" to "one axis under
3115    /// test, N axes unset, one field forgotten"). A future extension
3116    /// of the axis (a per-edge `:politicas` overlay the M4 roadmap
3117    /// grows once per-`:contratos`-edge overrides land, a sixth
3118    /// `:politicas` sub-slot the roadmap
3119    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3120    /// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3121    /// reaches this constructor at one edit (one added struct field
3122    /// on the type + one added `<axis>: None` line here) rather than
3123    /// a coordinated rewrite of every open-coded struct-literal at
3124    /// every downstream consumer.
3125    ///
3126    /// `pub const fn` — matches the sibling
3127    /// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
3128    /// every downstream consumer that folds a canonical unset
3129    /// baseline into a `const` position (a `const EMPTY: MeshPolicy =
3130    /// MeshPolicy::empty();` module-scope binding a future per-edge
3131    /// `:politicas` overlay reads through as its "no override
3132    /// declared" arm, a compile-time per-fixture-builder default the
3133    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3134    /// admission-time default-overlay-emit gate consults, a
3135    /// compile-time lookup table the LSP hover renderer materializes
3136    /// per typed-slot fixture) reads through one `const` dispatch
3137    /// rather than being forced onto the runtime code path. Pinned
3138    /// load-bearing at the substrate-primitive level by
3139    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3140    /// (round-trip pin against [`Self::is_empty`]),
3141    /// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
3142    /// pin against the derived [`Default::default`]), and
3143    /// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
3144    /// pin via `const` binding — any future accidental downgrade to
3145    /// `pub fn` fires E0015 at the binding at caixa-core build time,
3146    /// strictly stronger than a runtime `assert!`).
3147    #[must_use]
3148    pub const fn empty() -> Self {
3149        Self {
3150            timeout: None,
3151            retries: None,
3152            circuit_breaker: None,
3153            mtls_required: None,
3154            rate_limit: None,
3155        }
3156    }
3157
3158    /// True when no `:politicas` axis carries a value — every field is
3159    /// `None`. The same emptiness contract every other M2/M3 typed
3160    /// surface carries ([`crate::LimitsSpec::is_empty`],
3161    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
3162    /// typed slot onto a cluster artifact key off this predicate to
3163    /// decide "emit the slot" vs "skip the slot entirely", so an
3164    /// authored-but-unset `:politicas (())` round-trips to a rendered
3165    /// artifact that's structurally identical to one that omits the
3166    /// slot. Lifted as a typed predicate (rather than per-renderer
3167    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
3168    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
3169    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
3170    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
3171    /// not a coordinated rewrite of every consumer that's reaching
3172    /// for the emptiness semantic.
3173    #[must_use]
3174    pub const fn is_empty(&self) -> bool {
3175        self.timeout().is_none()
3176            && self.retries().is_none()
3177            && self.circuit_breaker().is_none()
3178            && self.mtls_required().is_none()
3179            && self.rate_limit().is_none()
3180    }
3181
3182    /// Substrate-canonical cross-axis coherence predicate on the
3183    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
3184    /// failure-observation interval span at least one full
3185    /// `:timeout`-bounded call?
3186    ///
3187    /// The first *cross-axis* invariant on the `:politicas` surface —
3188    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
3189    /// zero-floor + canonical-form + cap brackets) validates one axis
3190    /// in isolation, so a `MeshPolicy` whose axes are each individually
3191    /// well-formed could still name a structurally inert pair. The
3192    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
3193    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
3194    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
3195    /// both above the zero floor) and is nonetheless a breaker that
3196    /// cannot trip on the failure mode it exists to catch: a call
3197    /// dispatched at t=0 is declared failed at t=30s, by which point
3198    /// the 10s window open at dispatch has rolled twice over, so no
3199    /// window can ever hold even one timeout-derived failure however
3200    /// high the call volume. Envoy's `outlier_detection.interval`
3201    /// carries the identical relation against the per-route request
3202    /// timeout; Hystrix ships the canonical ratio in its defaults
3203    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
3204    /// `execution.isolation.thread.timeoutInMilliseconds`).
3205    ///
3206    /// Vacuously `true` when either axis is absent — a `:politicas`
3207    /// that names only one of the pair declares no relation for the
3208    /// substrate to hold it to (`:timeout` alone is a per-call deadline
3209    /// with no breaker; `:circuit-breaker` alone is a breaker whose
3210    /// failures arrive from the transport's own error signal rather
3211    /// than from a substrate-imposed deadline, so no dispatch-to-report
3212    /// lag is knowable at author time). This is the same
3213    /// "unset means the cluster default applies, not zero" partition
3214    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
3215    /// arm already carry.
3216    ///
3217    /// Lifted as a typed predicate on the substrate primitive rather
3218    /// than open-coded at the validate gate so every downstream
3219    /// consumer of the pair reaches the invariant through one dispatch:
3220    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3221    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3222    /// (MESH-COMPOSITION §III.2 #3) that must emit
3223    /// `outlier_detection.interval` and the per-route `timeout` as one
3224    /// coherent Envoy block, the future M4
3225    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3226    /// webhook, and the future per-`:contratos`-edge `:politicas`
3227    /// override that same roadmap acknowledges — which resolves an
3228    /// *effective* pair per edge (edge-level `:timeout` against the
3229    /// Aplicacao-level `:window`, or vice versa) and so must re-check
3230    /// the relation on a pair neither axis's declaration site can see
3231    /// whole. Naming the invariant once means that resolver folds this
3232    /// predicate over its resolved pair instead of re-deriving the
3233    /// comparison, exactly as the sibling cross-slot
3234    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
3235    /// `:placement`/`:shard-key` relation for its own consumers.
3236    #[must_use]
3237    pub const fn breaker_window_observes_timeout(&self) -> bool {
3238        match (self.timeout(), self.circuit_breaker()) {
3239            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
3240            _ => true,
3241        }
3242    }
3243
3244    /// Substrate-canonical cross-axis coherence predicate on the
3245    /// `:politicas` slot: can the token-bucket rate declared by
3246    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
3247    /// :window` to reach `:max-failures`?
3248    ///
3249    /// The second cross-axis invariant on the `:politicas` surface —
3250    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3251    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
3252    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
3253    /// pair is validated in isolation by the per-axis brackets in
3254    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
3255    /// max-failures zero-floor + cap, both windows zero-floor +
3256    /// integer-millisecond + cap, rate-limit window canonical-form),
3257    /// so a `MeshPolicy` whose axes are each individually well-formed
3258    /// can still name a structurally inert pair. The pair
3259    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
3260    /// "10s") }` passes every per-axis bracket and is nonetheless a
3261    /// breaker that cannot trip on the failure mode it exists to
3262    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
3263    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
3264    /// no window can accumulate five failures however catastrophically
3265    /// the upstream is failing. Envoy's
3266    /// `outlier_detection.consecutive_5xx` paired against
3267    /// `local_rate_limit.token_bucket.max_tokens` /
3268    /// `fill_interval` carries the identical relation; every
3269    /// production playbook that pairs the two axes (Envoy, Istio, AWS
3270    /// App Mesh, Kong) recommends sizing the rate at or above the
3271    /// breaker's minimum-request-volume threshold for exactly this
3272    /// reason.
3273    ///
3274    /// The typed test is the integer inequality
3275    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
3276    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
3277    /// so no floating-point division mediates the comparison and so
3278    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
3279    /// exactly). Both multiplicands are `saturating_mul`'d into
3280    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
3281    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
3282    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
3283    /// panic the predicate; a saturated pair collapses to the
3284    /// "vacuously coherent" branch the peer per-axis brackets reject
3285    /// via their own zero-floor / cap arms first.
3286    ///
3287    /// Vacuously `true` when either axis is absent — a `:politicas`
3288    /// that names only one of the pair declares no relation for the
3289    /// substrate to hold it to (`:rate-limit` alone is a per-edge
3290    /// token-bucket declaration with no failure counter to starve;
3291    /// `:circuit-breaker` alone is a rolling-window failure counter
3292    /// whose call rate is unconstrained by the substrate, so no
3293    /// bucket-derived upper bound on calls-per-window is knowable at
3294    /// author time). Same "unset means the cluster default applies,
3295    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
3296    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3297    /// carry.
3298    ///
3299    /// Lifted as a typed predicate on the substrate primitive rather
3300    /// than open-coded at the validate gate so every downstream
3301    /// consumer of the pair reaches the invariant through one
3302    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3303    /// below, the future `CiliumClusterwideEnvoyConfig`
3304    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3305    /// must emit `local_rate_limit.token_bucket.{max_tokens,
3306    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
3307    /// / `outlier_detection.interval` as one coherent Envoy block,
3308    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3309    /// materializer's admission webhook, and the future
3310    /// per-`:contratos`-edge `:politicas` override the same roadmap
3311    /// acknowledges — which resolves an *effective* pair per edge
3312    /// (edge-level `:rate-limit` against the Aplicacao-level
3313    /// `:circuit-breaker`, or vice versa) and so must re-check the
3314    /// relation on a pair neither axis's declaration site can see
3315    /// whole. Naming the invariant once means that resolver folds
3316    /// this predicate over its resolved pair instead of re-deriving
3317    /// the comparison, exactly as the sibling cross-axis
3318    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3319    /// names the `(:timeout, :window)` relation for its own consumers.
3320    #[must_use]
3321    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
3322        match (self.rate_limit(), self.circuit_breaker()) {
3323            (Some(rl), Some(cb)) => {
3324                let calls_per_cb_window =
3325                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
3326                let trip_threshold_per_cb_window =
3327                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
3328                calls_per_cb_window >= trip_threshold_per_cb_window
3329            }
3330            _ => true,
3331        }
3332    }
3333
3334    /// Substrate-canonical cross-axis coherence predicate on the
3335    /// `:politicas` slot: can one client's declared `:retries` all
3336    /// complete before `:circuit-breaker :max-failures` trips the
3337    /// breaker mid-retry?
3338    ///
3339    /// The third cross-axis invariant on the `:politicas` surface —
3340    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3341    /// the `(:timeout, :circuit-breaker :window)` pair and
3342    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3343    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
3344    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
3345    /// the pair is validated in isolation by the per-axis brackets in
3346    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3347    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
3348    /// are each individually well-formed can still name a
3349    /// structurally-inert retry policy. The pair
3350    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
3351    /// passes every per-axis bracket and is nonetheless a retry
3352    /// policy the substrate cannot honor: one client's initial attempt
3353    /// plus three retries is four attempts, but the breaker trips on
3354    /// the third failure — the fourth attempt (the last declared
3355    /// retry) is blocked by the open breaker, so the substrate
3356    /// declared four attempts and structurally allows three.
3357    ///
3358    /// The typed test is the integer inequality
3359    /// `cb.max_failures() > retries` — the retries count is the
3360    /// *number of retry attempts beyond the initial* (Envoy's
3361    /// `retry_policy.num_retries` semantics), so a client makes at
3362    /// most `retries + 1` attempts per client call, each of which may
3363    /// fail. For the breaker to *admit* the retry policy through
3364    /// completion, its trip threshold must not be reached by one
3365    /// client's failures alone: `retries + 1 <= max_failures`,
3366    /// equivalently `retries < max_failures`, equivalently
3367    /// `max_failures > retries`. The boundary case
3368    /// `max_failures == retries + 1` accepts (the R+1th failure — the
3369    /// last retry — trips the breaker exactly as it completes; retries
3370    /// are fully executed). The strict-below case
3371    /// `max_failures <= retries` rejects (the breaker trips before
3372    /// retries exhaust, silently truncating the declared retry policy
3373    /// mid-run — the same declared-but-structurally-inert footgun the
3374    /// sibling per-axis cap arms close on the single-axis surfaces).
3375    ///
3376    /// Vacuously `true` when either axis is absent — a `:politicas`
3377    /// that names only one of the pair declares no relation for the
3378    /// substrate to hold it to (`:retries` alone is a client-retry
3379    /// policy with no failure counter to trip; `:circuit-breaker`
3380    /// alone is a failure counter whose per-client attempt count is
3381    /// unconstrained by the substrate, so no per-client saturation
3382    /// bound on failures-per-client-call is knowable at author time).
3383    /// Same "unset means the cluster default applies, not zero"
3384    /// partition [`MeshPolicy::is_empty`] and the sibling
3385    /// [`MeshPolicy::breaker_window_observes_timeout`] /
3386    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3387    /// carry.
3388    ///
3389    /// Lifted as a typed predicate on the substrate primitive rather
3390    /// than open-coded at the validate gate so every downstream
3391    /// consumer of the pair reaches the invariant through one
3392    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3393    /// below, the future `CiliumClusterwideEnvoyConfig`
3394    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3395    /// must emit `retry_policy.num_retries` alongside
3396    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
3397    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3398    /// materializer's admission webhook, and the future
3399    /// per-`:contratos`-edge `:politicas` override the same roadmap
3400    /// acknowledges — which resolves an *effective* pair per edge
3401    /// (edge-level `:retries` against the Aplicacao-level
3402    /// `:circuit-breaker`, or vice versa) and so must re-check the
3403    /// relation on a pair neither axis's declaration site can see
3404    /// whole. Naming the invariant once means that resolver folds
3405    /// this predicate over its resolved pair instead of re-deriving
3406    /// the comparison, exactly as the sibling cross-axis
3407    /// [`MeshPolicy::breaker_window_observes_timeout`] and
3408    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3409    /// name the `(:timeout, :window)` and `(:rate-limit,
3410    /// :circuit-breaker)` relations for their own consumers.
3411    #[must_use]
3412    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
3413        match (self.retries(), self.circuit_breaker()) {
3414            (Some(retries), Some(cb)) => cb.max_failures() > retries,
3415            _ => true,
3416        }
3417    }
3418
3419    /// Substrate-canonical cross-axis coherence predicate on the
3420    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
3421    /// admit one client's full `:retries + 1` attempt burst inside a
3422    /// single refill window?
3423    ///
3424    /// The fourth cross-axis invariant on the `:politicas` surface,
3425    /// completing the triangle of pairs the three sibling gates carve
3426    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
3427    /// on the `(:timeout, :circuit-breaker :window)` pair,
3428    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3429    /// `(:rate-limit, :circuit-breaker)` pair, and
3430    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
3431    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
3432    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
3433    /// among the three scalar `:politicas` axes (`:retries`,
3434    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
3435    /// coherence surface every production overlay (Envoy, Istio,
3436    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
3437    /// the pair is validated in isolation by the per-axis brackets in
3438    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3439    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
3440    /// whose axes are each individually well-formed can still name a
3441    /// structurally-truncated retry policy the rate limiter refuses to
3442    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
3443    /// per-axis bracket and is nonetheless a retry policy the substrate
3444    /// cannot honor: one client's initial attempt plus five retries is
3445    /// six attempts, but the token bucket admits at most three tokens
3446    /// per one-second refill window, so the fourth attempt onward is
3447    /// blocked by the rate limiter itself — the substrate declared six
3448    /// attempts and structurally allows three. Envoy's
3449    /// `local_rate_limit.token_bucket.max_tokens` paired against
3450    /// `retry_policy.num_retries` carries the identical relation; every
3451    /// production playbook that pairs the two axes recommends sizing
3452    /// the bucket capacity above any single client's retry budget so
3453    /// the retry policy is not silently truncated by the same rate
3454    /// limiter it feeds through.
3455    ///
3456    /// The typed test is the integer inequality
3457    /// `rl.rate() >= retries + 1` — the retries count is the *number of
3458    /// retry attempts beyond the initial* (Envoy's
3459    /// `retry_policy.num_retries` semantics), so a client makes at most
3460    /// `retries + 1` attempts per client call, each of which consumes
3461    /// one token from the local rate-limit bucket. For the bucket to
3462    /// *admit* the retry burst without dropping tokens, its capacity
3463    /// must not be reached by one client's attempts alone:
3464    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
3465    /// boundary case `rate == retries + 1` accepts (the bucket admits
3466    /// exactly one client's full retry sequence per refill window —
3467    /// retries fully executed). The strict-below case `rate <= retries`
3468    /// rejects (the bucket exhausts before retries complete, silently
3469    /// truncating the declared retry policy mid-run — the same
3470    /// declared-but-structurally-inert footgun the sibling per-axis cap
3471    /// arms close on the single-axis surfaces). The equivalent
3472    /// coherent-direction form `rl.rate() > retries` sidesteps the
3473    /// `retries + 1` addition entirely (both `rate` and `retries` are
3474    /// `u32`; the `>` comparison is total on the type with no overflow
3475    /// against past-the-guard struct-literal `retries` values a caller
3476    /// might pass before `validate` runs), matching the peer
3477    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
3478    /// `>`-comparison discipline on the sibling
3479    /// `(:retries, :max-failures)` pair.
3480    ///
3481    /// Vacuously `true` when either axis is absent — a `:politicas`
3482    /// that names only one of the pair declares no relation for the
3483    /// substrate to hold it to (`:retries` alone is a client-retry
3484    /// policy with no rate limiter to saturate; `:rate-limit` alone is
3485    /// a token-bucket declaration whose per-client attempt count is
3486    /// unconstrained by the substrate, so no per-client saturation
3487    /// bound on tokens-per-client-call is knowable at author time).
3488    /// Same "unset means the cluster default applies, not zero"
3489    /// partition [`MeshPolicy::is_empty`] and the three sibling
3490    /// cross-axis predicates
3491    /// ([`MeshPolicy::breaker_window_observes_timeout`],
3492    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
3493    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
3494    ///
3495    /// Lifted as a typed predicate on the substrate primitive rather
3496    /// than open-coded at the validate gate so every downstream
3497    /// consumer of the pair reaches the invariant through one dispatch:
3498    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3499    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3500    /// (MESH-COMPOSITION §III.2 #3) that must emit
3501    /// `local_rate_limit.token_bucket.max_tokens` alongside
3502    /// `retry_policy.num_retries` as one coherent Envoy block, the
3503    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3504    /// admission webhook, and the future per-`:contratos`-edge
3505    /// `:politicas` override the same roadmap acknowledges — which
3506    /// resolves an *effective* pair per edge (edge-level `:retries`
3507    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
3508    /// so must re-check the relation on a pair neither axis's
3509    /// declaration site can see whole. Naming the invariant once means
3510    /// that resolver folds this predicate over its resolved pair
3511    /// instead of re-deriving the comparison, exactly as the three
3512    /// sibling cross-axis predicates name the
3513    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
3514    /// `(:retries, :max-failures)` relations for their own consumers,
3515    /// closing the fourth and last cross-axis relation on the scalar
3516    /// `:politicas` axis-triple.
3517    #[must_use]
3518    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3519        match (self.retries(), self.rate_limit()) {
3520            (Some(retries), Some(rl)) => rl.rate() > retries,
3521            _ => true,
3522        }
3523    }
3524
3525    /// Substrate-canonical fold over the four cross-axis coherence
3526    /// predicates on the `:politicas` slot — returns the *first*
3527    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3528    /// canonical "more-foundational-cross-axis first" ordering
3529    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3530    /// `(:timeout, :circuit-breaker :window)` →
3531    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3532    /// `(:rate-limit, :circuit-breaker)` →
3533    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3534    /// `(:retries, :circuit-breaker :max-failures)` →
3535    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3536    /// :rate-limit)`. Returns `None` when every cross-axis relation
3537    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3538    /// coherent shape both land here).
3539    ///
3540    /// The ordering discipline this method encodes was open-coded four
3541    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3542    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3543    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3544    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3545    /// axis-fetch step depended on the predicate having just returned
3546    /// `false` (structurally guaranteed both paired axes are `Some`,
3547    /// but the compiler cannot see through the predicate body, so
3548    /// every arm re-called the accessor with `.expect(…)` to reach
3549    /// the axis it just tested). Two unsound consequences: (1) the
3550    /// validate gate carried eight `.expect(…)` panic call sites the
3551    /// predicate contract already forbids on every well-typed input
3552    /// but the type system does not enforce; (2) the
3553    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3554    /// twice — once in each predicate's own doc comments and once at
3555    /// the validate call site's four-arm cascade. Lifting the four-arm
3556    /// cascade onto this substrate primitive collapses both
3557    /// duplications: the predicate contract and the axis-fetch step
3558    /// live in the same body (no `.expect(…)` — the pattern match at
3559    /// each arm rebinds the paired axes so their `Some` presence is a
3560    /// compile-time property of the local scope), and the ordering
3561    /// discipline lives once at the top of the primitive rather than
3562    /// scattered across four sibling doc-comment blocks that must
3563    /// stay in lockstep.
3564    ///
3565    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3566    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3567    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3568    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3569    /// §III.2 #3 acknowledges — the last of which resolves an
3570    /// *effective* per-edge pair and must emit *the same* diagnostic
3571    /// on the same paired-axis input as `feira build`) reaches through
3572    /// one call rather than re-inlining the four pattern-matches +
3573    /// accessor-fetches + variant-constructions + ordering-cascade.
3574    ///
3575    /// Returns owned copies of every axis carried into the diagnostic:
3576    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3577    /// occurs on the happy path when no violation fires.
3578    #[must_use]
3579    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3580        // Ordering discipline this fold encodes matches the four
3581        // per-arm predicate doc comments' pairwise-ordering contract:
3582        // window-below-timeout wins over every arm that names `:rate-
3583        // limit` or `:retries` (its diagnostic is more self-locating —
3584        // the pair is a per-call-deadline invariant every synchronous
3585        // edge carries whether or not `:rate-limit`/`:retries` is
3586        // declared); the starve arm wins over the two retry arms (its
3587        // diagnostic reasons across the token-bucket-vs-breaker
3588        // relation, an axis the retry arms do not touch); the
3589        // retries-saturate arm wins over the retries-burst arm (its
3590        // diagnostic reasons across the per-client-vs-breaker
3591        // relation, which carries whether or not `:rate-limit` is
3592        // declared). Each arm rebinds the paired axes through the
3593        // pattern match, so the `.expect(…)` panics the four-block
3594        // cascade at `validate_politicas` carried collapse to no-op
3595        // pattern rebindings the compiler statically proves exhaust.
3596        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3597            && !self.breaker_window_observes_timeout()
3598        {
3599            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3600        }
3601        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3602            && !self.breaker_can_trip_under_rate_limit()
3603        {
3604            return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
3605                &rl, &cb,
3606            ));
3607        }
3608        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3609            && !self.retries_fit_under_breaker_trip_threshold()
3610        {
3611            return Some(
3612                AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
3613            );
3614        }
3615        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3616            && !self.rate_limit_admits_retry_burst()
3617        {
3618            return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
3619                retries, &rl,
3620            ));
3621        }
3622        None
3623    }
3624
3625    /// Substrate-canonical compound entry gate over the whole
3626    /// `:politicas` typed slot — folds every per-axis bracket
3627    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3628    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3629    /// window-canonical-form) *and* the compound cross-axis fold
3630    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3631    /// consumer of a validated [`MeshPolicy`] reaches through.
3632    ///
3633    /// Returns the first violation as its [`AplicacaoError`] variant,
3634    /// or `Ok(())` when every per-axis value lies in its accept-set and
3635    /// every cross-axis relation holds. Per-axis brackets run strictly
3636    /// before the cross-axis fold — the sibling
3637    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3638    /// ordering discipline for the same reason: a per-axis
3639    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3640    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3641    /// diagnostic first, ahead of any cross-axis arm that would send
3642    /// the author to reconcile two values one of which is not a
3643    /// meaningful window at all. Within the per-axis phase, arms fire
3644    /// in the same slot-order the peer per-axis brackets carry
3645    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3646    /// each internally ordered zero-floor before canonical-form before
3647    /// cap by [`crate::render::require_positive_bounded_u32`] /
3648    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3649    /// within the cross-axis phase, arms fire in the canonical
3650    /// more-foundational-cross-axis-first ordering
3651    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3652    ///
3653    /// Lifted as a typed method on the substrate primitive so every
3654    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3655    /// invariant through one dispatch: the
3656    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3657    /// body collapses to `self.politicas().validate()`), the future
3658    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3659    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3660    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3661    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3662    /// emit *the same* diagnostic on the same input as `feira build`.
3663    /// Naming the compound gate once on the substrate primitive means
3664    /// every downstream consumer inherits both the per-axis brackets
3665    /// *and* the cross-axis fold through one call, rather than
3666    /// re-inlining the four-per-axis + one-cross-axis cascade in
3667    /// lockstep with `validate_politicas`.
3668    ///
3669    /// Peer of the per-kind compound entry gates lifted at
3670    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3671    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3672    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3673    /// layout axis, and the sibling compound cross-axis fold
3674    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3675    /// `:politicas` axis — extended here onto the per-slot per-axis +
3676    /// cross-axis compound entry gate that folds both surfaces.
3677    pub fn validate(&self) -> Result<(), AplicacaoError> {
3678        if let Some(t) = self.timeout() {
3679            crate::render::require_positive_canonical_bounded_duration(
3680                t,
3681                POLICY_TIMEOUT_MAX,
3682                || AplicacaoError::PolicyTimeoutZero,
3683                AplicacaoError::policy_timeout_not_canonical,
3684                AplicacaoError::policy_timeout_exceeds_cap,
3685            )?;
3686        }
3687        if let Some(r) = self.retries() {
3688            crate::render::require_positive_bounded_u32(
3689                r,
3690                POLICY_RETRIES_MAX,
3691                || AplicacaoError::PolicyRetriesZero,
3692                AplicacaoError::policy_retries_exceeds_cap,
3693            )?;
3694        }
3695        if let Some(cb) = self.circuit_breaker() {
3696            crate::render::require_positive_bounded_u32(
3697                cb.max_failures(),
3698                POLICY_BREAKER_MAX_FAILURES_MAX,
3699                || AplicacaoError::PolicyBreakerZeroFailures,
3700                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3701            )?;
3702            crate::render::require_positive_canonical_bounded_duration(
3703                cb.window(),
3704                POLICY_BREAKER_WINDOW_MAX,
3705                || AplicacaoError::PolicyBreakerZeroWindow,
3706                AplicacaoError::policy_breaker_window_not_canonical,
3707                AplicacaoError::policy_breaker_window_exceeds_cap,
3708            )?;
3709        }
3710        if let Some(rl) = self.rate_limit() {
3711            crate::render::require_positive_bounded_u32(
3712                rl.rate(),
3713                POLICY_RATE_LIMIT_MAX,
3714                || AplicacaoError::PolicyRateLimitZero,
3715                AplicacaoError::policy_rate_limit_exceeds_cap,
3716            )?;
3717            if rl.canonical_unit().is_none() {
3718                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3719                    rl.window(),
3720                ));
3721            }
3722        }
3723        if let Some(err) = self.first_cross_axis_violation() {
3724            return Err(err);
3725        }
3726        Ok(())
3727    }
3728
3729    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3730    /// per-call-deadline scalar accessor every consumer of the
3731    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3732    /// returns the author-declared `:politicas :timeout` typed
3733    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3734    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3735    /// is `Copy`, so the accessor returns by value; no borrow of
3736    /// `&self` past the call). `None` when the slot is absent (the
3737    /// "cluster default applies — typically the gateway class's
3738    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3739    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3740    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3741    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3742    /// round-trips to a rendered `HTTPRoute` structurally identical to
3743    /// one that omits the slot).
3744    ///
3745    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3746    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3747    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3748    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3749    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3750    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3751    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3752    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3753    /// Every downstream consumer that reads the per-call cap keys off
3754    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3755    /// renderers key off to decide "emit :politicas overlay" vs "skip
3756    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3757    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3758    /// fans the deadline into every rule via
3759    /// [`crate::render::single_field_overlay`], the future M4 per-
3760    /// Aplicacao Gateway API reconciler materialization pass, the
3761    /// future per-`:contratos`-edge timeout-override overlay the
3762    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3763    ///
3764    /// Prior to this lift the `.timeout` field was accessed inline at
3765    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3766    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3767    /// …)` call — two open-coded field-accesses that expressed no
3768    /// compile-time link back to the typed slot. A future extension of
3769    /// the `:politicas :timeout` axis to a richer author surface — a
3770    /// per-`:contratos`-edge timeout override the operator pins through
3771    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3772    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3773    /// M4 CR materializer resolves per-CR, a split of the single
3774    /// per-call `Duration` into a richer `{request, backendRequest}`
3775    /// pair once the Gateway API's per-rule `timeouts` block grows the
3776    /// upstream-facing backendRequest arm alongside the client-facing
3777    /// request arm — would have had to be threaded through both open-
3778    /// coded copies in lockstep or the emptiness predicate and the
3779    /// caixa-mesh emit path would silently disagree on which per-call
3780    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3781    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3782    /// == false` while the renderer's overlay-emit path silently read
3783    /// a drifted other value, or vice versa: an author's `:timeout
3784    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3785    /// the emptiness predicate still classified the policy as non-
3786    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3787    /// | grep -A2 timeouts` audit would land on a route whose author's
3788    /// typed slot value silently vanished at the renderer layer).
3789    /// Lifting the resolution to a typed method on the substrate
3790    /// primitive means every downstream consumer of the Aplicacao's
3791    /// per-`:politicas` deadline surface reaches for exactly one typed
3792    /// dispatch — the resolver's accept-set migrates as a unit on any
3793    /// future axis addition.
3794    ///
3795    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3796    /// family (sibling of the peer per-`:politicas`
3797    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3798    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3799    /// `Option<bool>` accessor — same "one typed dispatch on the
3800    /// substrate primitive, thin projections at each consumer"
3801    /// discipline extended onto the peer per-`:politicas` typed-
3802    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3803    /// numeric-Copy-T scalar" projection pattern the sibling
3804    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3805    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3806    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3807    /// than a scalar). Named `timeout()` to match the storage field's
3808    /// name; the accessor's identity maps onto the canonical MESH-
3809    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3810    #[must_use]
3811    pub const fn timeout(&self) -> Option<Duration> {
3812        self.timeout
3813    }
3814
3815    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3816    /// retry-budget scalar accessor every consumer of the Aplicacao's
3817    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3818    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3819    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3820    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3821    /// value; no borrow of `&self` past the call). `None` when the slot
3822    /// is absent (the "cluster default applies — typically 'no retries
3823    /// beyond a single dispatch attempt'" arm the caixa-mesh
3824    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3825    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3826    /// this predicate too, so an authored-but-unset `:politicas
3827    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3828    /// identical to one that omits the slot).
3829    ///
3830    /// The `:politicas :retries` slot carries the "transient failure
3831    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3832    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3833    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3834    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3835    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3836    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3837    /// Every downstream consumer that reads the retry cap keys off this
3838    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3839    /// renderers key off to decide "emit :politicas overlay" vs "skip
3840    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3841    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3842    /// the value into every rule via [`crate::render::single_field_overlay`],
3843    /// the future M4 per-Aplicacao Gateway API reconciler
3844    /// materialization pass, the future per-`:contratos`-edge retry-
3845    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3846    /// acknowledges).
3847    ///
3848    /// Prior to this lift the `.retries` field was accessed inline at
3849    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3850    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3851    /// …)` call — two open-coded field-accesses that expressed no
3852    /// compile-time link back to the typed slot. A future extension of
3853    /// the `:politicas :retries` axis to a richer author surface — a
3854    /// per-`:contratos`-edge retry override the operator pins through a
3855    /// future `:contratos :retries` slot, a per-cluster retry-default
3856    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3857    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3858    /// backoff}` sub-block once the Gateway API grows the peer
3859    /// `retry.codes` / `retry.backoff` axes — would have had to be
3860    /// threaded through both open-coded copies in lockstep or the
3861    /// emptiness predicate and the caixa-mesh emit path would silently
3862    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3863    /// (a `:politicas` block whose only axis is a `Some :retries` would
3864    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3865    /// path silently read a drifted other value, or vice versa: an
3866    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3867    /// block while the emptiness predicate still classified the policy
3868    /// as non-empty). Lifting the resolution to a typed method on the
3869    /// substrate primitive means every downstream consumer of the
3870    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3871    /// one typed dispatch — the resolver's accept-set migrates as a
3872    /// unit on any future axis addition.
3873    ///
3874    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3875    /// family (sibling of the peer per-`:politicas`
3876    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3877    /// same "one typed dispatch on the substrate primitive, thin
3878    /// projections at each consumer" discipline extended onto the
3879    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3880    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3881    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3882    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3883    /// fold on). Named `retries()` to match the storage field's name;
3884    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3885    /// §III.2 vocabulary the slot's docstring already carries.
3886    #[must_use]
3887    pub const fn retries(&self) -> Option<u32> {
3888        self.retries
3889    }
3890
3891    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3892    /// enforcement-toggle scalar accessor every consumer of the
3893    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3894    /// — returns the author-declared `:politicas :mtls-required` typed
3895    /// bool verbatim as an `Option<bool>`, copied out of the typed
3896    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3897    /// the accessor returns by value; no borrow of `&self` past the
3898    /// call). `None` when the slot is absent (the "cluster default
3899    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3900    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3901    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3902    /// this predicate too, so an authored-but-unset `:politicas
3903    /// (:mtls-required ())` round-trips to a rendered
3904    /// `CiliumNetworkPolicy` structurally identical to one that omits
3905    /// the slot).
3906    ///
3907    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3908    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3909    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3910    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3911    /// Cilium `authentication.mode` bijection through
3912    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3913    /// handshake enforced), `Some(false) → "disabled"` (handshake
3914    /// skipped — the debug-edge opt-out), `None` → omit the block
3915    /// (cluster default applies). Every downstream consumer that
3916    /// reads the toggle keys off this scalar (the
3917    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3918    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3919    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3920    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3921    /// ingress rule via [`crate::render::single_field_overlay`], the
3922    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3923    /// materialization pass, the future per-`:contratos`-edge mTLS
3924    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3925    ///
3926    /// Prior to this lift the `.mtls_required` field was accessed
3927    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3928    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3929    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3930    /// two open-coded field-accesses that expressed no compile-time
3931    /// link back to the typed slot. A future extension of the
3932    /// `:politicas :mtls-required` axis to a richer author surface —
3933    /// a per-`:contratos`-edge mTLS override the operator pins through
3934    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3935    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3936    /// M4 CR materializer resolves per-CR, a three-valued
3937    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3938    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3939    /// would have had to be threaded through both open-coded copies in
3940    /// lockstep or the emptiness predicate and the caixa-mesh emit
3941    /// path would silently disagree on which toggle a given
3942    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3943    /// axis is a `Some`
3944    /// `:mtls-required` would satisfy `is_empty() == false` while the
3945    /// renderer's overlay-emit path silently read a drifted other
3946    /// value, or vice versa). Lifting the resolution to a typed method
3947    /// on the substrate primitive means every downstream consumer of
3948    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3949    /// for exactly one typed dispatch — the resolver's accept-set
3950    /// migrates as a unit on any future axis addition.
3951    ///
3952    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3953    /// family (peer of the sibling per-`:placement`
3954    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3955    /// same "one typed dispatch on the substrate primitive, thin
3956    /// projections at each consumer" discipline extended onto the
3957    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3958    /// the "optional per-slot Copy-T scalar" projection pattern the
3959    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3960    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3961    /// `mtls_required()` to match the storage field's name; the
3962    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3963    /// §III.2 vocabulary the slot's docstring already carries.
3964    #[must_use]
3965    pub const fn mtls_required(&self) -> Option<bool> {
3966        self.mtls_required
3967    }
3968
3969    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3970    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3971    /// accessor every consumer of the Aplicacao's per-`:politicas`
3972    /// per-`(rate, window)` rate-limit surface keys off — returns the
3973    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3974    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3975    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3976    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3977    /// past the call). `None` when the slot is absent (the "cluster
3978    /// default applies — typically 'no per-Aplicacao rate declaration,
3979    /// gateway-class per-listener default applies'" arm the future
3980    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3981    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3982    /// `rate_limit().is_none()` arm reads this predicate too, so an
3983    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3984    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3985    /// identical to one that omits the slot).
3986    ///
3987    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3988    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3989    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3990    /// (rate lower-bounded by 1 through
3991    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3992    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3993    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3994    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3995    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3996    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3997    /// `:politicas` overlay emits. Every downstream consumer that
3998    /// reads the rate declaration keys off this scalar (the
3999    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4000    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4001    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
4002    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
4003    /// `rl.window` against [`is_canonical_rate_limit_window`], the
4004    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
4005    /// the future per-`:contratos`-edge rate-limit override the
4006    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4007    ///
4008    /// Prior to this lift the `.rate_limit` field was accessed inline
4009    /// at two sites — [`MeshPolicy::is_empty`]'s
4010    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
4011    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
4012    /// field-accesses that expressed no compile-time link back to the
4013    /// typed slot. A future extension of the `:politicas :rate-limit`
4014    /// axis to a richer author surface — a per-`:contratos`-edge
4015    /// rate-limit override the operator pins through a future
4016    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
4017    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
4018    /// the M4 CR materializer resolves per-CR, a promotion of the
4019    /// plain `(rate, window)` scalar pair to a richer
4020    /// `{rate, window, burst, key}` sub-block once Envoy's
4021    /// `local_rate_limit` grows the peer `burst_size` /
4022    /// `descriptor_key` axes — would have had to be threaded through
4023    /// both open-coded copies in lockstep or the emptiness predicate
4024    /// and the validate gate would silently disagree on which rate
4025    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
4026    /// block whose only axis is a `Some :rate-limit` would satisfy
4027    /// `is_empty() == false` while the validate path silently read a
4028    /// drifted other value, or vice versa: an author's
4029    /// `:rate-limit "100/s"` would omit the value-shape gate while the
4030    /// emptiness predicate still classified the policy as non-empty).
4031    /// Lifting the resolution to a typed method on the substrate
4032    /// primitive means every downstream consumer of the Aplicacao's
4033    /// per-`:politicas` rate-limit surface reaches for exactly one
4034    /// typed dispatch — the resolver's accept-set migrates as a unit
4035    /// on any future axis addition.
4036    ///
4037    /// First `Option<Copy-composite-T>`-return accessor on the M3
4038    /// mesh-slot family — closes the last un-lifted per-`:politicas`
4039    /// scalar-value axis. Peer of the sibling per-`:politicas`
4040    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
4041    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
4042    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
4043    /// "one typed dispatch on the substrate primitive, thin
4044    /// projections at each consumer" discipline extended onto the
4045    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
4046    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
4047    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
4048    /// sub-accessors rather than a top-level accessor because
4049    /// consumers reach for the axes not the aggregate). Named
4050    /// `rate_limit()` to match the storage field's name; the
4051    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4052    /// §III.2 vocabulary the slot's docstring already carries.
4053    #[must_use]
4054    pub const fn rate_limit(&self) -> Option<RateLimit> {
4055        self.rate_limit
4056    }
4057
4058    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
4059    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
4060    /// declaration scalar accessor every consumer of the Aplicacao's
4061    /// per-`:politicas` breaker declaration keys off — returns the
4062    /// author-declared `:politicas :circuit-breaker` typed
4063    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
4064    /// copied out of the typed slot's own `Option<CircuitBreaker>`
4065    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
4066    /// by value; no borrow of `&self` past the call). `None` when the
4067    /// slot is absent (the "cluster default applies — typically 'no
4068    /// per-Aplicacao breaker declaration, gateway-class per-listener
4069    /// default applies'" arm the future caixa-mesh
4070    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
4071    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
4072    /// arm reads this predicate too, so an authored-but-unset
4073    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
4074    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
4075    /// that omits the slot).
4076    ///
4077    /// The `:politicas :circuit-breaker` slot carries the
4078    /// "per-Aplicacao consecutive-transient-failure trip declaration"
4079    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4080    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
4081    /// zero-floor rejected through
4082    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4083    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
4084    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
4085    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
4086    /// canonical-form pinned through
4087    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
4088    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
4089    /// bijection the future `CiliumClusterwideEnvoyConfig`
4090    /// per-`:politicas` overlay emits. Every downstream consumer that
4091    /// reads the breaker declaration keys off this scalar (the
4092    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4093    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4094    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
4095    /// that brackets `cb.max_failures()` against
4096    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
4097    /// [`POLICY_BREAKER_WINDOW_MAX`] via
4098    /// [`crate::render::require_positive_canonical_bounded_duration`],
4099    /// the future M4 per-Aplicacao Envoy reconciler materialization
4100    /// pass, the future per-`:contratos`-edge breaker override the
4101    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4102    ///
4103    /// Prior to this lift the `.circuit_breaker` field was accessed
4104    /// inline at two sites — [`MeshPolicy::is_empty`]'s
4105    /// `self.circuit_breaker.is_none()` arm and the
4106    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
4107    /// bind — two open-coded field-accesses that expressed no
4108    /// compile-time link back to the typed slot. A future extension of
4109    /// the `:politicas :circuit-breaker` axis to a richer author
4110    /// surface — a per-`:contratos`-edge breaker override the operator
4111    /// pins through a future `:contratos :circuit-breaker` slot the
4112    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
4113    /// breaker-default overlay the M4 CR materializer resolves per-CR,
4114    /// a promotion of the plain `(max_failures, window)` scalar pair to
4115    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
4116    /// sub-block once Envoy's `outlier_detection` grows the peer
4117    /// ejection-percentage / ejection-time axes — would have had to be
4118    /// threaded through both open-coded copies in lockstep or the
4119    /// emptiness predicate and the validate gate would silently
4120    /// disagree on which breaker declaration a given [`MeshPolicy`]
4121    /// resolves to (a `:politicas` block whose only axis is a
4122    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
4123    /// the validate path silently read a drifted other value, or vice
4124    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
4125    /// "60s"))` would omit the value-shape gate while the emptiness
4126    /// predicate still classified the policy as non-empty). Lifting
4127    /// the resolution to a typed method on the substrate primitive
4128    /// means every downstream consumer of the Aplicacao's
4129    /// per-`:politicas` breaker surface reaches for exactly one typed
4130    /// dispatch — the resolver's accept-set migrates as a unit on any
4131    /// future axis addition.
4132    ///
4133    /// Second `Option<Copy-composite-T>`-return accessor on the M3
4134    /// mesh-slot family (sibling of the peer per-`:politicas`
4135    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
4136    /// on the same composite-Copy shape, and of the sibling per-
4137    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
4138    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
4139    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
4140    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
4141    /// same "one typed dispatch on the substrate primitive, thin
4142    /// projections at each consumer" discipline extended onto the last
4143    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
4144    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
4145    /// match the storage field's name; the accessor's identity maps
4146    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4147    /// docstring already carries. Closes the last unlifted
4148    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
4149    /// reader now routes through a typed dispatch on the substrate
4150    /// primitive.
4151    #[must_use]
4152    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
4153        self.circuit_breaker
4154    }
4155}
4156
4157#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
4158#[serde(rename_all = "camelCase")]
4159pub struct CircuitBreaker {
4160    pub max_failures: u32,
4161    #[serde(with = "supervisor::duration_codec_required")]
4162    pub window: Duration,
4163}
4164
4165impl CircuitBreaker {
4166    /// Substrate-canonical per-`:politicas :circuit-breaker`
4167    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
4168    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4169    /// breaker trip-count keys off — returns the author-declared
4170    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
4171    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
4172    /// so the accessor returns by value; no borrow of `&self` past the
4173    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
4174    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
4175    /// axis; a `CircuitBreaker` past pattern-match is definitionally
4176    /// present, and its `:max-failures` field carries the trip count as a
4177    /// required-axis scalar).
4178    ///
4179    /// The `:politicas :circuit-breaker :max-failures` axis carries the
4180    /// "consecutive-transient-failure trip threshold" contract
4181    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
4182    /// (zero-floor rejected through
4183    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4184    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
4185    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
4186    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
4187    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
4188    /// Every downstream consumer that reads the trip threshold keys off
4189    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4190    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
4191    /// canonical `require_positive_bounded_u32` helper, the future M4
4192    /// per-Aplicacao Envoy config reconciler materialization pass, the
4193    /// future per-`:contratos`-edge breaker-override overlay the
4194    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4195    ///
4196    /// Prior to this lift the `.max_failures` field was accessed inline
4197    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
4198    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
4199    /// open-coded field-access that expressed no compile-time link back
4200    /// to the typed sub-struct axis. A future extension of the
4201    /// `:max-failures` axis to a richer author surface — a
4202    /// per-`:contratos`-edge breaker override the operator pins through a
4203    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
4204    /// #3 roadmap acknowledges, a per-cluster max-failures-default
4205    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
4206    /// plain `u32` trip count to a richer
4207    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
4208    /// tuple once Envoy's `outlier_detection` block's peer axes come into
4209    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
4210    /// count arms — would have had to be threaded through every open-
4211    /// coded copy in lockstep or the validate gate and the future M4
4212    /// emit path would silently disagree on which trip threshold a given
4213    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
4214    /// would satisfy validate while the emit path silently read a drifted
4215    /// other value, or vice versa: a validated typed slot would land at
4216    /// the emit boundary as a no-op breaker whose trip threshold is
4217    /// structurally never reached). Lifting the resolution to a typed
4218    /// method on the substrate primitive means every downstream consumer
4219    /// of the Aplicacao's per-`:politicas :circuit-breaker`
4220    /// trip-threshold surface reaches for exactly one typed dispatch —
4221    /// the resolver's accept-set migrates as a unit on any future axis
4222    /// addition.
4223    ///
4224    /// First sub-struct scalar accessor on the M3 mesh-slot family
4225    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
4226    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
4227    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
4228    /// closes the last unlifted per-`:politicas` scalar-value axis after
4229    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
4230    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
4231    /// Same "one typed dispatch on the substrate primitive, thin
4232    /// projections at each consumer" discipline the peer
4233    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4234    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4235    /// [`Membro::versao_requirement`] (a40b0e3),
4236    /// [`Entrada::destination`] (6db982c) accessors carry on their
4237    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
4238    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
4239    /// match the storage field's name; the accessor's identity maps onto
4240    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4241    /// docstring already carries.
4242    #[must_use]
4243    pub const fn max_failures(&self) -> u32 {
4244        self.max_failures
4245    }
4246
4247    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
4248    /// Envoy-outlier-detection rolling-observation-interval scalar
4249    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4250    /// breaker rolling-window duration keys off — returns the
4251    /// author-declared `:politicas :circuit-breaker :window` typed
4252    /// `Duration` verbatim, copied out of the typed slot's own
4253    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
4254    /// by value; no borrow of `&self` past the call). Non-optional (the
4255    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
4256    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
4257    /// `CircuitBreaker` past pattern-match is definitionally present,
4258    /// and its `:window` field carries the rolling-observation interval
4259    /// as a required-axis scalar).
4260    ///
4261    /// The `:politicas :circuit-breaker :window` axis carries the
4262    /// "consecutive-transient-failure rolling-observation interval"
4263    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4264    /// `Duration` accept-set (zero-floor rejected through
4265    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
4266    /// residue rejected through
4267    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
4268    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
4269    /// Envoy `outlier_detection.interval` per-cluster
4270    /// ejection-observation-interval scalar (equivalently the future
4271    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4272    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4273    /// consumer that reads the rolling-observation interval keys off
4274    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4275    /// integer-millisecond canonical-form + cap bracket at
4276    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
4277    /// [`crate::render::require_positive_canonical_bounded_duration`]
4278    /// helper, the future M4 per-Aplicacao Envoy config reconciler
4279    /// materialization pass, the future per-`:contratos`-edge
4280    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4281    /// acknowledges).
4282    ///
4283    /// Prior to this lift the `.window` field was accessed inline at
4284    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
4285    /// `require_positive_canonical_bounded_duration(cb.window, …)`
4286    /// call — one open-coded field-access that expressed no compile-
4287    /// time link back to the typed sub-struct axis. A future extension
4288    /// of the `:window` axis to a richer author surface — a
4289    /// per-`:contratos`-edge window override the operator pins through
4290    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
4291    /// #3 roadmap acknowledges, a per-cluster window-default overlay
4292    /// the M4 CR materializer resolves per-CR, a promotion of the plain
4293    /// `Duration` observation interval to a richer
4294    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
4295    /// once Envoy's `outlier_detection` block's peer axes come into
4296    /// scope, a per-Envoy-cluster minimum-request-volume gate before
4297    /// the window arms — would have had to be threaded through every
4298    /// open-coded copy in lockstep or the validate gate and the future
4299    /// M4 emit path would silently disagree on which observation
4300    /// interval a given [`CircuitBreaker`] resolves to (an author's
4301    /// `:window "60s"` would satisfy validate while the emit path
4302    /// silently read a drifted other value, or vice versa: a validated
4303    /// typed slot would land at the emit boundary as a breaker whose
4304    /// observation window is structurally so wide that no realistic
4305    /// failure-rate shape can trip it). Lifting the resolution to a
4306    /// typed method on the substrate primitive means every downstream
4307    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
4308    /// observation-window surface reaches for exactly one typed
4309    /// dispatch — the resolver's accept-set migrates as a unit on any
4310    /// future axis addition.
4311    ///
4312    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
4313    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
4314    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
4315    /// required-axis, extended onto the per-sub-struct required-`Duration`
4316    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
4317    /// axis. Same "one typed dispatch on the substrate primitive, thin
4318    /// projections at each consumer" discipline the peer
4319    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4320    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4321    /// [`Membro::versao_requirement`] (a40b0e3),
4322    /// [`Entrada::destination`] (6db982c) accessors carry on their
4323    /// respective per-mesh-slot-atom scalar-value axes, extended onto
4324    /// the per-sub-struct required-`Duration` axis. Named `window()` to
4325    /// match the storage field's name; the accessor's identity maps onto
4326    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4327    /// docstring already carries.
4328    #[must_use]
4329    pub const fn window(&self) -> Duration {
4330        self.window
4331    }
4332}
4333
4334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4335pub struct RateLimit {
4336    /// Requests per window.
4337    pub rate: u32,
4338    /// Window duration.
4339    pub window: Duration,
4340}
4341
4342impl RateLimit {
4343    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
4344    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
4345    /// every consumer of the Aplicacao's per-`:contratos`-edge
4346    /// rate-limit-bucket capacity keys off — returns the author-declared
4347    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
4348    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
4349    /// returns by value; no borrow of `&self` past the call). Non-optional
4350    /// (the surrounding `Option<RateLimit>` is the "slot present?"
4351    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
4352    /// `RateLimit` past pattern-match is definitionally present, and its
4353    /// `:rate` field carries the token-bucket capacity as a required-axis
4354    /// scalar).
4355    ///
4356    /// The `:politicas :rate-limit` `:rate` axis carries the
4357    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
4358    /// the typed slot's `u32` accept-set (zero-floor rejected through
4359    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
4360    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
4361    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
4362    /// token-bucket-capacity scalar (equivalently the future
4363    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4364    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4365    /// consumer that reads the token-bucket capacity keys off this
4366    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4367    /// cap bracket that gates on the canonical
4368    /// [`crate::render::require_positive_bounded_u32`] helper, the
4369    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4370    /// emits the `<n>/<s|m|h>` author surface, the future M4
4371    /// per-Aplicacao Envoy config reconciler materialization pass, the
4372    /// future per-`:contratos`-edge rate-limit-override overlay the
4373    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4374    ///
4375    /// Prior to this lift the `.rate` field was accessed inline at three
4376    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
4377    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
4378    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
4379    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
4380    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
4381    /// field-accesses that expressed no compile-time link back to the
4382    /// typed sub-struct axis. A future extension of the `:rate` axis
4383    /// to a richer author surface — a per-`:contratos`-edge rate
4384    /// override the operator pins through a future `:contratos :rate`
4385    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
4386    /// per-cluster rate-default overlay the M4 CR materializer resolves
4387    /// per-CR, a promotion of the plain `u32` token capacity to a
4388    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
4389    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4390    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
4391    /// before the token arms — would have had to be threaded through
4392    /// every open-coded copy in lockstep or the validate gate, the
4393    /// codec's render path, and the future M4 emit path would silently
4394    /// disagree on which token capacity a given [`RateLimit`] resolves
4395    /// to (an author's `:rate-limit "100/s"` would satisfy validate
4396    /// while the render / emit paths silently read a drifted other
4397    /// value, or vice versa: a validated typed slot would land at the
4398    /// emit boundary as a no-op limiter whose token capacity is
4399    /// structurally so high that no realistic per-edge traffic shape
4400    /// can drain it). Lifting the resolution to a typed method on the
4401    /// substrate primitive means every downstream consumer of the
4402    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
4403    /// reaches for exactly one typed dispatch — the resolver's
4404    /// accept-set migrates as a unit on any future axis addition.
4405    ///
4406    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
4407    /// in shape to the peer per-`CircuitBreaker`
4408    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
4409    /// on the peer per-sub-struct required-axis, extended onto the
4410    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
4411    /// required-axis scalar" projection pattern the sibling
4412    /// [`RateLimit::window`] future lift folds on. Same "one typed
4413    /// dispatch on the substrate primitive, thin projections at each
4414    /// consumer" discipline the peer [`WitContract::source`] /
4415    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
4416    /// (0804823), [`Membro::nome`] (4a32abf),
4417    /// [`Membro::versao_requirement`] (a40b0e3),
4418    /// [`Entrada::destination`] (6db982c),
4419    /// [`CircuitBreaker::max_failures`] (3a74062),
4420    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
4421    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
4422    /// to match the storage field's name; the accessor's identity maps
4423    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4424    /// docstring already carries.
4425    #[must_use]
4426    pub const fn rate(&self) -> u32 {
4427        self.rate
4428    }
4429
4430    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
4431    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
4432    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4433    /// rate-limit-bucket refill period keys off — returns the
4434    /// author-declared `:politicas :rate-limit` typed `Duration`
4435    /// verbatim, copied out of the typed slot's own `Duration` storage
4436    /// (`Duration` is `Copy`, so the accessor returns by value; no
4437    /// borrow of `&self` past the call). Non-optional (the surrounding
4438    /// `Option<RateLimit>` is the "slot present?" projection at the
4439    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
4440    /// pattern-match is definitionally present, and its `:window`
4441    /// field carries the token-bucket refill period as a required-axis
4442    /// scalar).
4443    ///
4444    /// The `:politicas :rate-limit` `:window` axis carries the
4445    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
4446    /// — the typed slot's `Duration` accept-set (constrained to the
4447    /// three canonical windows `{1s, 60s, 3600s}` the
4448    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
4449    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
4450    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
4451    /// per-cluster token-bucket-refill-period scalar (equivalently the
4452    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4453    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4454    /// consumer that reads the token-bucket refill period keys off
4455    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
4456    /// canonical-window gate that keys off
4457    /// [`is_canonical_rate_limit_window`], the
4458    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4459    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
4460    /// [`rate_limit_window_unit`] and non-canonical fallback via
4461    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
4462    /// reconciler materialization pass, the future per-`:contratos`-
4463    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
4464    /// roadmap acknowledges).
4465    ///
4466    /// Prior to this lift the `.window` field was accessed inline at
4467    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
4468    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
4469    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
4470    /// error-payload construction on refusal, and the two
4471    /// [`rate_limit_codec::render`] arms
4472    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
4473    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
4474    /// open-coded field-accesses that expressed no compile-time link
4475    /// back to the typed sub-struct axis. A future extension of the
4476    /// `:window` axis to a richer author surface — a per-`:contratos`-
4477    /// edge window override the operator pins through a future
4478    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
4479    /// acknowledges, a per-cluster window-default overlay the M4 CR
4480    /// materializer resolves per-CR, a promotion of the plain
4481    /// `Duration` refill period to a richer
4482    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
4483    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4484    /// axis comes into scope, an addition of a `"d"` day suffix once
4485    /// Envoy's `rate_limit_action` grows daily-bucket support — would
4486    /// have had to be threaded through every open-coded copy in
4487    /// lockstep or the validate gate, the codec's render path, and
4488    /// the future M4 emit path would silently disagree on which
4489    /// refill period a given [`RateLimit`] resolves to (an author's
4490    /// `:rate-limit "100/s"` would satisfy validate while the render
4491    /// / emit paths silently read a drifted other value, or vice
4492    /// versa: a validated typed slot would land at the emit boundary
4493    /// as a limiter whose refill period is structurally so long that
4494    /// no realistic per-edge traffic shape stays inside the token
4495    /// budget). Lifting the resolution to a typed method on the
4496    /// substrate primitive means every downstream consumer of the
4497    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
4498    /// reaches for exactly one typed dispatch — the resolver's
4499    /// accept-set migrates as a unit on any future axis addition.
4500    ///
4501    /// Second sub-struct scalar accessor on the `RateLimit` axis —
4502    /// sibling in shape to the just-landed [`RateLimit::rate`]
4503    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
4504    /// required-axis, extended onto the per-sub-struct
4505    /// required-`Duration` axis; closes the last unlifted
4506    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
4507    /// per-sub-struct accessor coverage is now complete across both
4508    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
4509    /// the substrate primitive, thin projections at each consumer"
4510    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4511    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4512    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4513    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4514    /// [`Membro::nome`] (4a32abf),
4515    /// [`Membro::versao_requirement`] (a40b0e3),
4516    /// [`Entrada::destination`] (6db982c) accessors carry on their
4517    /// respective per-mesh-slot-atom scalar-value axes. Named
4518    /// `window()` to match the storage field's name; the accessor's
4519    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4520    /// vocabulary the slot's docstring already carries.
4521    #[must_use]
4522    pub const fn window(&self) -> Duration {
4523        self.window
4524    }
4525
4526    /// Recognize this rate-limit's `:window` as a canonical
4527    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4528    /// exactly matches one of the three closed-set arm-Durations
4529    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4530    /// non-canonical magnitude the codec's round-trip would break on
4531    /// (sub-second residue, or a second-magnitude outside the set
4532    /// [`RateLimitUnit::ALL`] enumerates).
4533    ///
4534    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4535    /// returns `Some` here — the validate gate's
4536    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4537    /// rejects every window this accessor returns `None` on. Downstream
4538    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4539    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4540    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4541    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4542    /// acknowledges) that read the typed unit off a validated slot can
4543    /// pattern-match on the returned `Some` without re-checking
4544    /// canonicality at the consumer layer — the typed enum surface is
4545    /// the load-bearing carrier of the canonicality invariant.
4546    ///
4547    /// Preferred over the free [`is_canonical_rate_limit_window`]
4548    /// module-private helper at any call site that has the typed
4549    /// [`RateLimit`] in hand (the codec's `render` arm at
4550    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4551    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4552    /// per-`:contratos` edge-override overlay resolver): those consumers
4553    /// reach for the typed enum without going through the
4554    /// `.window()` scalar-projection layer, and get the enum value
4555    /// directly (which the codec's render arm can then format via
4556    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4557    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4558    /// primitive" discipline the sibling [`RateLimit::rate`] and
4559    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4560    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4561    /// projection axis (the third scalar accessor on the [`RateLimit`]
4562    /// axis, first typed-enum-return projection).
4563    ///
4564    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4565    /// the canonical [`RateLimitUnit`] arm now carries the same
4566    /// `const`-eval-surface posture the sibling `pub const fn`
4567    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4568    /// this typed sub-struct already carry, composing through the
4569    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4570    /// reverse-resolver in `const` context. Any downstream substrate-
4571    /// side `const`-context consumer of the typed unit (a module-scope
4572    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4573    /// invariant pin on a typed fixture, a future M4 admission-webhook
4574    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4575    /// resolver over a typed [`RateLimit`], any future `const fn`
4576    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4577    /// the substrate primitive) now reaches the same typed dispatch on
4578    /// the substrate primitive at const-eval time as at runtime.
4579    ///
4580    /// Pinned load-bearing at the substrate-primitive level by
4581    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4582    /// eval-surface pin via `const fn` wrapper).
4583    #[must_use]
4584    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4585        RateLimitUnit::from_window(self.window)
4586    }
4587}
4588
4589/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4590/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4591/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4592///
4593/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4594/// the `:politicas :rate-limit` unit surface reads from
4595/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4596/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4597/// [`is_canonical_rate_limit_window`] predicate the
4598/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4599/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4600/// projection) now lives inside this typed enum's `match self` arms — a
4601/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4602/// `rate_limit_action` grows daily-bucket support) is one new variant
4603/// plus the exhaustiveness arms on the four methods, so every consumer
4604/// picks it up by compile-time construction rather than a runtime
4605/// table-scan miss.
4606///
4607/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4608/// scanned via `find_map` at every projection call — an untyped runtime
4609/// walk that carried no compile-time link between the parse arm's
4610/// accepted suffixes, the render arm's emitted suffixes, and the
4611/// validate gate's accepted windows. A future rate-limit-unit addition
4612/// that landed one row without threading through the other consumers
4613/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4614/// silently split the accepted-set across the three consumers — the
4615/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4616/// for a 24h window that parse can't round-trip, the validate gate
4617/// misses one canonical window. Lifting the pairs onto a typed
4618/// closed-set enum with exhaustive `match` arms makes any such
4619/// half-landed extension a caixa-core build error (the compiler enforces
4620/// arm coverage on every method), not a silent per-consumer drift
4621/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4622/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4623/// [`crate::supervisor::RestartStrategy`],
4624/// [`crate::supervisor::RestartPolicy`],
4625/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4626/// closed-set typed enums carry on their respective closed-set axes —
4627/// extended onto the seventh closed-set typed-enum discriminator axis
4628/// on the caixa typed surface (the `:politicas :rate-limit :window`
4629/// canonical-unit axis).
4630#[derive(
4631    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4632)]
4633pub enum RateLimitUnit {
4634    /// 1-second window — canonical author-surface suffix `"s"`
4635    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4636    /// with a 1s magnitude.
4637    Second,
4638    /// 1-minute window — canonical author-surface suffix `"m"`
4639    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4640    /// with a 60s magnitude.
4641    Minute,
4642    /// 1-hour window — canonical author-surface suffix `"h"`
4643    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4644    /// with a 3600s magnitude.
4645    Hour,
4646}
4647
4648impl RateLimitUnit {
4649    /// Exhaustive iteration surface for every consumer that reads the
4650    /// full canonical-unit set (the byte-parity witness against the
4651    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4652    /// webhook's accepted-suffix listing in its rejection body, any
4653    /// future round-trip fuzz harness). A future variant addition to
4654    /// [`RateLimitUnit`] extends this slice as a single edit and every
4655    /// consumer picks up the new entry by construction — the compiler-
4656    /// checked exhaustiveness on the sibling method `match` arms is the
4657    /// build-time guarantee that no arm forgets to grow.
4658    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4659
4660    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4661    /// string every `<n>/<unit>` rate-limit shape carries after its
4662    /// `/` separator. The single source of truth the codec's parse and
4663    /// render arms both dispatch on: the parse arm matches an incoming
4664    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4665    /// output; the render arm emits the entry's `as_suffix` verbatim
4666    /// after the rate magnitude.
4667    #[must_use]
4668    pub const fn as_suffix(self) -> &'static str {
4669        match self {
4670            Self::Second => "s",
4671            Self::Minute => "m",
4672            Self::Hour => "h",
4673        }
4674    }
4675
4676    /// Canonical `Duration` for this unit — the token-bucket refill
4677    /// period the [`RateLimit::window`] axis carries when the surrounding
4678    /// slot's `:rate-limit` author surface named this unit.
4679    #[must_use]
4680    pub const fn window(self) -> Duration {
4681        Duration::from_secs(match self {
4682            Self::Second => 1,
4683            Self::Minute => 60,
4684            Self::Hour => 3_600,
4685        })
4686    }
4687
4688    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4689    /// `None` when `suffix` is outside the closed-set arm-string set
4690    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4691    /// [`rate_limit_codec::parse`] consumes.
4692    #[must_use]
4693    pub fn from_suffix(suffix: &str) -> Option<Self> {
4694        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4695    }
4696
4697    /// Recognize a canonical rate-limit `Duration` as one of the three
4698    /// arms, or `None` when `window` carries sub-second residue or a
4699    /// second-magnitude outside the closed-set arm-window set
4700    /// [`Self::window`] emits. The single `Duration → Self` projection
4701    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4702    /// both consume.
4703    ///
4704    /// `pub const fn` — the reverse `Duration → Self` projection now
4705    /// carries the same `const`-eval-surface posture the sibling
4706    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4707    /// projection accessors on this closed-set typed enum already
4708    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4709    /// typed-`RateLimit`-projection sibling composes through in `const`
4710    /// context. Routes byte-for-byte through the peer `pub const fn`
4711    /// [`Self::window`] canonical-`Duration` projection so any future
4712    /// arm-magnitude edit on the sibling accessor reaches this reverse
4713    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4714    /// per-arm probes each dispatch through one `pub const fn` on the
4715    /// substrate primitive rather than a hand-authored per-arm second-
4716    /// magnitude literal that would silently drift on any future
4717    /// [`Self::window`] arm-magnitude edit.
4718    ///
4719    /// Prior to the `const` lift the body dispatched through
4720    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4721    /// iterator-driven linear scan whose iterator methods
4722    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4723    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4724    /// Rust 1.94, so any downstream substrate-side `const`-context
4725    /// consumer of the reverse resolver (a module-scope
4726    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4727    /// invariant pin on a typed fixture, a future M4
4728    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4729    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4730    /// typed [`RateLimit`] scalar, any future `const fn`
4731    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4732    /// the substrate primitive that wants to fan on the canonical unit
4733    /// at compile time) surfaced as a downstream E0015 far from the
4734    /// resolver's own declaration. The `pub const fn` posture closes
4735    /// the drift structurally at caixa-core build time.
4736    ///
4737    /// Pinned load-bearing at the substrate-primitive level by
4738    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4739    /// eval-surface pin via `const fn` wrapper) and
4740    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4741    /// (composition-witness pin against the peer `Self::window` scalar
4742    /// dispatch).
4743    #[must_use]
4744    pub const fn from_window(window: Duration) -> Option<Self> {
4745        if window.subsec_nanos() != 0 {
4746            return None;
4747        }
4748        // Route through the peer `pub const fn` [`Self::window`]
4749        // canonical-`Duration` projection so any future arm-magnitude
4750        // edit on the sibling accessor reaches this reverse resolver by
4751        // construction — the per-arm `secs` comparison keys off
4752        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4753        // per-arm second-magnitude literal that would silently drift.
4754        let secs = window.as_secs();
4755        if secs == Self::Second.window().as_secs() {
4756            Some(Self::Second)
4757        } else if secs == Self::Minute.window().as_secs() {
4758            Some(Self::Minute)
4759        } else if secs == Self::Hour.window().as_secs() {
4760            Some(Self::Hour)
4761        } else {
4762            None
4763        }
4764    }
4765
4766    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4767    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4768    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4769    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4770    /// consumes.
4771    ///
4772    /// The peer `Duration → &'static str` axis folded onto the substrate
4773    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4774    /// production consumers ([`rate_limit_codec::render`] and
4775    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4776    /// migrated (61421a6): the free helper's `Duration → &str` projection
4777    /// is now the two-step composition
4778    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4779    /// reads through the typed accessor. This lift closes the peer
4780    /// `&str → Duration` axis by folding the vestigial module-private
4781    /// `rate_limit_window_from_unit` delegate onto this associated method
4782    /// — the codec's parse arm and every future wire-side consumer of the
4783    /// `&str → Duration` projection (a future admission-webhook that
4784    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4785    /// before it's promoted to a validated typed slot, a future
4786    /// `feira lint` shape-probe that reads the author-surface bytes
4787    /// verbatim) now reach for exactly one typed dispatch on the
4788    /// substrate primitive.
4789    ///
4790    /// Same "closed-set typed-enum discriminator with canonical
4791    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4792    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4793    /// methods carry — this associated method closes the fifth (and last
4794    /// unlifted) projection axis on the arm-table, so the closed-set enum
4795    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4796    /// consumer of the `:politicas :rate-limit :window` axis reaches
4797    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4798    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4799    /// `"ms"` sub-second window once high-throughput per-edge policies
4800    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4801    /// variant plus one arm per method — the compiler enforces
4802    /// exhaustiveness on every consumer's `match self` arms and picks
4803    /// the new unit up by construction across all five projections.
4804    #[must_use]
4805    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4806        Self::from_suffix(suffix).map(Self::window)
4807    }
4808}
4809
4810/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4811/// every consumer that formats a canonical rate-limit unit as user-
4812/// facing text (future M4 admission-webhook rejection bodies naming
4813/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4814/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4815/// codec's parse arm accepts and the render arm emits. Same
4816/// as_str-through-Display convergence discipline the sibling
4817/// [`PlacementStrategy`], [`crate::CaixaKind`],
4818/// [`crate::supervisor::RestartStrategy`], and
4819/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4820impl std::fmt::Display for RateLimitUnit {
4821    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4822        f.write_str(self.as_suffix())
4823    }
4824}
4825
4826/// Substrate-canonical [`AsRef<str>`] projection on the M3
4827/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
4828/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
4829/// scalar accessor the paired [`std::fmt::Display`] impl already
4830/// delegates through, so any future consumer that binds a
4831/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
4832/// bound (a [`std::process::Command::arg`] shell-out that composes the
4833/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
4834/// `--rate-limit-unit <s|m|h>` arg on the future
4835/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
4836/// names, a `tracing::field::Value::Str`-arm structured-log recorder
4837/// on the future `app-operator`'s per-`:politicas :rate-limit`
4838/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
4839/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
4840/// future per-unit token-bucket-refill dispatch table the future M4
4841/// admission-webhook rejection body composes) reaches the paired
4842/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
4843/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
4844/// every wire-up.
4845///
4846/// Deliberately routes through the canonical suffix axis, not the
4847/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
4848/// [`fmt::Display`] land on the same author-surface-canonical byte-
4849/// string the codec's parse and render arms both dispatch on, while
4850/// the token-bucket-refill period stays reachable only through the
4851/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
4852/// paths.
4853///
4854/// Same "route the trait impl through the substrate-primitive
4855/// accessor" discipline the sibling [`crate::CaixaVersion`]
4856/// [`AsRef<str>`] impl (16d5c7e), the paired M2
4857/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
4858/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
4859/// [`AsRef<str>`] impl (419ea81), the M3
4860/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
4861/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
4862/// — closes the substrate primitive's [`AsRef<str>`] projection axis
4863/// onto the last remaining closed-set typed enum with a
4864/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
4865/// on the caixa surface (top-level `:kind`, both M2
4866/// `:supervisor`-slot per-child and sibling-restart typed enums, the
4867/// M3 `:placement :estrategia` typed enum, the M3
4868/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
4869/// typed newtype) now carries the paired [`AsRef<str>`] +
4870/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
4871///
4872/// Pinned load-bearing by
4873/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
4874/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
4875/// three-arm closed set) and
4876/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
4877/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
4878/// all resolve to the same byte-string per arm) — any future silent
4879/// detour that routes the impl through a divergent projection (a
4880/// per-arm inline `match self { … }` re-inlining that opens a compile-
4881/// time link to the un-lifted arm-literal, a swap onto the
4882/// second-magnitude [`RateLimitUnit::window`] axis that would collide
4883/// the canonical-suffix / token-bucket-refill two-axis split) trips at
4884/// caixa-core test time under `assert_eq!` rather than at a downstream
4885/// `impl AsRef<str>`-bound consumer's silent split.
4886impl AsRef<str> for RateLimitUnit {
4887    fn as_ref(&self) -> &str {
4888        self.as_suffix()
4889    }
4890}
4891
4892/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4893/// validated [`MeshPolicy::timeout`] past
4894/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4895/// (inclusive on both ends, integer-millisecond magnitudes by the
4896/// canonical-form gate immediately preceding).
4897///
4898/// The typed field is `Option<Duration>` (the zero-floor arm
4899/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4900/// `Duration::ZERO`, and the canonical-form arm
4901/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4902/// sub-millisecond residue), so a programmatic struct literal
4903/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4904/// 24h) and the equivalent author-surface form
4905/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4906/// integer-hour magnitude) both round-trip cleanly through serde — a
4907/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4908/// above the documented production-playbook band (Envoy default `15s`,
4909/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4910/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4911/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4912/// at `~3600s`) silently degenerates the mesh-policy contract: the
4913/// per-call deadline is structurally so long that no realistic
4914/// synchronous-`:contratos` traversal can reach it, so the typed slot
4915/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4916/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4917/// blocking" degenerates to a nominal-only contract on the
4918/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4919/// the sibling `:politicas :retries` axis and the
4920/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4921/// `:politicas :circuit-breaker :max-failures` axis — all three close
4922/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4923/// footgun the prior zero-floor-and-canonical-form-only checks left
4924/// open.
4925///
4926/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4927/// shared duration codec emits (`"<n>h"` for any integer-hour
4928/// magnitude) — every value in the canonical authoring form's
4929/// `<integer><unit>` grammar at or below this cap renders to a clean
4930/// canonical string. The cap sits an order of magnitude above every
4931/// documented production-playbook recommendation band (Envoy default
4932/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4933/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4934/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4935/// below the clearly-pathological "effectively no timeout" floor
4936/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4937/// want for a long-running synchronous workflow, but a hard wall above
4938/// which the mesh-level deadline is structurally a non-deadline.
4939/// Lifted as a typed `pub const` so the bound has exactly one source
4940/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4941/// materializer's admission webhook and the caixa-mesh-side
4942/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4943/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4944/// other typed upper bound in this crate carries
4945/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4946/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4947/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4948/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4949pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4950
4951/// Upper-bound ceiling on the `:politicas :retries` axis — every
4952/// validated [`MeshPolicy::retries`] past
4953/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4954///
4955/// The typed slot is `Option<u32>` (`None` = no retries on transient
4956/// failure; `Some(0)` already rejected by the
4957/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4958/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4959/// .. }`) and the equivalent author-surface form
4960/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4961/// serde / the codec — a structurally unbounded `u32` ceiling. The
4962/// runtime substrate that consumes the value (Envoy's
4963/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4964/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4965/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4966/// admission cap is 10) translates a four-billion-retry policy into a
4967/// thundering-herd amplification vector on transient failure — the
4968/// caller's one request fans out to `retries` server-side calls per
4969/// edge per traversal, multiplying load by `(retries+1)^depth` across
4970/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4971/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4972/// invariant on the retry axis; both belong at the typed-slot layer.
4973///
4974/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4975/// upstream mesh-policy schema that documents one) and sits above the
4976/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4977/// every documented production playbook): a value the author can
4978/// plausibly want, but a hard wall above which the policy is
4979/// structurally a footgun. Lifted as a typed `pub const` so the bound
4980/// has exactly one source of truth — a future axis reaching for the
4981/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4982/// materializer's admission webhook, the caixa-mesh-side
4983/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4984/// one place. Same shape every other typed upper bound in this crate
4985/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4986/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4987/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4988/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4989pub const POLICY_RETRIES_MAX: u32 = 10;
4990
4991/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4992/// axis — every validated [`CircuitBreaker::max_failures`] past
4993/// [`AplicacaoSpec::validate_politicas`] lies in
4994/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4995///
4996/// The typed field is `u32` (the zero-floor arm
4997/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4998/// `0` — a breaker that trips on the first call), so a programmatic
4999/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
5000/// and the equivalent author-surface form
5001/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
5002/// cleanly through serde — a structurally unbounded `u32` ceiling. A
5003/// `max_failures` value far above the documented production-playbook
5004/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
5005/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
5006/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
5007/// typical 5–50) silently disables the breaker's protection role:
5008/// the threshold is structurally so high that no realistic
5009/// failures-per-`:window` traffic shape can reach it, so the breaker
5010/// never trips and the typed slot becomes a no-op carried on every
5011/// emitted Envoy / Cilium L7 overlay. Pairs with the
5012/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
5013/// axis — both close the "structurally unbounded `u32` ceiling on a
5014/// typed policy axis" footgun the prior zero-floor-only checks left
5015/// open.
5016///
5017/// The `1000` ceiling sits an order of magnitude above every
5018/// documented upstream production-playbook recommendation band (the
5019/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
5020/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
5021/// the clearly-pathological "effectively no protection"
5022/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
5023/// plausibly want at hyperscale, but a hard wall above which the
5024/// policy is structurally a no-op. Lifted as a typed `pub const` so
5025/// the bound has exactly one source of truth — the future M4
5026/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5027/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5028/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5029/// one place. Same shape every other typed upper bound in this crate
5030/// carries ([`POLICY_RETRIES_MAX`],
5031/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5032/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5033/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5034pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
5035
5036/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
5037/// every validated [`CircuitBreaker::window`] past
5038/// [`AplicacaoSpec::validate_politicas`] lies in
5039/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
5040/// integer-millisecond magnitudes by the canonical-form gate
5041/// immediately preceding).
5042///
5043/// The typed field is `Duration` (the zero-floor arm
5044/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
5045/// `Duration::ZERO`, and the canonical-form arm
5046/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
5047/// sub-millisecond residue), so a programmatic struct literal
5048/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
5049/// and the equivalent author-surface form
5050/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
5051/// integer-hour magnitude) both round-trip cleanly through serde — a
5052/// structurally unbounded `Duration` ceiling. A `:window` value far
5053/// above the documented production-playbook band (Hystrix
5054/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
5055/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
5056/// Istio `outlierDetection.interval` default `10s`, Envoy
5057/// `outlier_detection.interval` default `10s`, AWS App Mesh
5058/// circuit-breaker time-window typical `30s..=300s`) degenerates the
5059/// breaker's role: a rolling-window failure counter whose window is
5060/// hours long is operationally a lifetime counter, the breaker's
5061/// "recent failures" memory is structurally so long that transient
5062/// failures are never forgotten, and the typed slot becomes a no-op
5063/// trigger that trips once and stays tripped for the lifetime of the
5064/// component carried on every emitted Envoy / Cilium L7 overlay.
5065///
5066/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
5067/// shared duration codec emits (`"<n>h"` for any integer-hour
5068/// magnitude) — every value in the canonical authoring form's
5069/// `<integer><unit>` grammar at or below this cap renders to a clean
5070/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
5071/// cap on the first typed-`Duration` `:politicas` axis: the two
5072/// duration-typed `:politicas` axes now share a single uniform top
5073/// edge so the next typed-slot wiring (the future caixa-mesh
5074/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
5075/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
5076/// admission webhook) reaches for either field knowing the value is
5077/// in `1ms..=1h` without re-validating at the renderer layer. The cap
5078/// sits two orders of magnitude above every documented upstream
5079/// production-playbook recommendation band (Hystrix / resilience4j /
5080/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
5081/// and below the clearly-pathological "rolling window degenerates to
5082/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
5083/// author can plausibly want for a very-low-traffic long-tail
5084/// failure-detection window, but a hard wall above which the breaker's
5085/// rolling-window contract is structurally a lifetime-counter contract.
5086/// Lifted as a typed `pub const` so the bound has exactly one source
5087/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5088/// materializer's admission webhook and the caixa-mesh-side
5089/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5090/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
5091/// other typed upper bound in this crate carries
5092/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5093/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
5094/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5095/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5096/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5097pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
5098
5099/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
5100/// every validated [`RateLimit::rate`] past
5101/// [`AplicacaoSpec::validate_politicas`] lies in
5102/// `1..=POLICY_RATE_LIMIT_MAX`.
5103///
5104/// The typed field is `u32` (the zero-floor arm
5105/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
5106/// zero-rate limit denies every request, the canonical "I forgot
5107/// that 0 means deny-everything" footgun), so a programmatic struct
5108/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
5109/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
5110/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
5111/// round-trip cleanly through serde — a structurally unbounded `u32`
5112/// ceiling. The runtime substrate consuming the value (Envoy's
5113/// `local_rate_limit.token_bucket.max_tokens`, the future
5114/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5115/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
5116/// rate-limit into a no-op rate-limiter: the bucket capacity is
5117/// structurally so high no realistic per-edge traffic shape can
5118/// drain it, the limiter never trips, and the typed slot becomes a
5119/// "rate-limit declared, no enforcement" footgun — the canonical
5120/// declared-but-inert shape every other `:politicas` cap arm
5121/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
5122/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
5123///
5124/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
5125/// above every documented upstream production-playbook recommendation
5126/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
5127/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
5128/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
5129/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
5130/// `limit_req_zone` typical `1..=1_000` RPS) and below the
5131/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
5132/// `u32::MAX`): a value the author can plausibly want at hyperscale
5133/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
5134/// /h-window arm), but a hard wall above which the policy is
5135/// structurally a no-op carried verbatim on every emitted Envoy /
5136/// Cilium L7 overlay. The cap brackets all three canonical windows
5137/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
5138/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
5139/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
5140/// per-endpoint API band). Lifted as a typed `pub const` so the bound
5141/// has exactly one source of truth — the future M4
5142/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5143/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5144/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5145/// one place. Same shape every other typed upper bound in this crate
5146/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5147/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5148/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5149/// [`crate::LIMITS_WALL_CLOCK_MAX`],
5150/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5151/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5152pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
5153
5154// `:entrada :host` total-length and per-label cap axes route through
5155// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
5156// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
5157// pair of aplicacao-private aliases the previous `validate_entrada_host`
5158// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
5159// = 63`) were structurally the same K8s Gateway API v1 Hostname
5160// admission-schema bounds — the total-length cap on the OpenAPI
5161// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
5162// same regex — that the peer axes at the caixa-core::render level pin,
5163// so hoisting both readers onto the shared lifted constants closes the
5164// third-occurrence duplication threshold structurally: the M4
5165// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
5166// label validator, the future per-`Certificate` SAN emitter, and every
5167// other per-Gateway-API-Hostname landing site reach the same one place
5168// as the `:entrada :host` gate does — no per-axis alias drift surface
5169// between them, by construction.
5170
5171/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
5172/// extractor expression — the upper bound `validate_placement_shard_key`
5173/// enforces on every well-shaped shard-key past validate. The realistic
5174/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
5175/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
5176/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
5177/// `:placement :affinity` / `:placement :clusters` identifier-shaped
5178/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
5179/// in `:shard-key`" footgun at validate time rather than at the future
5180/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
5181const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
5182
5183/// Reject `:membros :caixa` values the K8s apiserver would refuse at
5184/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5185/// that maps the shared parser-shaped reason into the
5186/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
5187/// is self-locating (the offending `caixa:` is named verbatim) and
5188/// the author can grep their caixa.lisp for `:caixa "<name>"` and
5189/// fix it in one edit. Same diagnostic shape as
5190/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
5191/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
5192fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
5193    // Empty is already gated by `MembroCaixaEmpty` at the call site;
5194    // re-checking here keeps the predicate usable from any future
5195    // call site (the M4 CR materializer) without an empty-check
5196    // footgun. The shared
5197    // [`crate::render::require_valid_dns_1123_label`] helper brackets
5198    // the empty-first + shape cascade every peer name axis
5199    // (`:placement :clusters`, `:placement :affinity`, `:contratos
5200    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
5201    // `:upgrade-from :module`) routes through, so drift between the
5202    // eight axes' accepted DNS-1123-label sets is structurally
5203    // impossible.
5204    crate::render::require_valid_dns_1123_label(
5205        caixa,
5206        || AplicacaoError::MembroCaixaEmpty,
5207        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
5208    )
5209}
5210
5211/// Reject `:placement :clusters` entries the K8s apiserver would refuse
5212/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5213/// that maps the shared parser-shaped reason into the
5214/// [`AplicacaoError::PlacementClusterInvalid`] variant.
5215///
5216/// Cluster names land in DNS-1123-label territory across every consumer:
5217/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
5218/// the `lareira-fleet-programs` aggregator applies to scope programs to
5219/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
5220/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
5221/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
5222/// cluster identity the M4 CR materializer round-trips. Each apiserver-
5223/// side schema enforces the DNS-1123 label rule on admission; a
5224/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
5225/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
5226/// mistaken-identity slug) silently passes the prior empty-/duplicate-
5227/// only gate and the failure surfaces as a no-match at filter time —
5228/// the workload doesn't land in the named cluster, with no diagnostic
5229/// naming the offending `:clusters` entry. Lifting the gate to caixa-
5230/// build time mirrors the `:membros :caixa` value-shape trajectory
5231/// (3f9d7a0) on the peer name axis.
5232///
5233/// The diagnostic carries the offending `cluster:` verbatim plus a
5234/// parser-shaped `reason:` naming the specific violation, so the
5235/// author can grep their caixa.lisp for `:clusters` and fix it in
5236/// one edit. Same diagnostic shape as
5237/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
5238fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
5239    // Empty is already gated by `PlacementClusterEmpty` at the call
5240    // site; re-checking here keeps the predicate usable from any
5241    // future call site (the M4 CR materializer's per-cluster validator)
5242    // without an empty-check footgun. Routes through the shared
5243    // [`crate::render::require_valid_dns_1123_label`] gate the peer
5244    // name axes each land on.
5245    crate::render::require_valid_dns_1123_label(
5246        cluster,
5247        || AplicacaoError::PlacementClusterEmpty,
5248        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
5249    )
5250}
5251
5252/// Reject `:placement :affinity` hints whose shape can never legitimately
5253/// land in any downstream selector or label-keyed routing axis. Thin
5254/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5255/// shared parser-shaped reason into the
5256/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
5257/// diagnostic is self-locating (the offending `:affinity` is named
5258/// verbatim) and the author can grep their caixa.lisp for
5259/// `:affinity "<hint>"` and fix it in one edit.
5260///
5261/// The `:affinity` slot carries a placement-engine hint — canonical
5262/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
5263/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
5264/// compression overlay and the future M4 placement-engine's per-hint
5265/// routing axis. Each downstream consumer (caixa-mesh's
5266/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
5267/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5268/// `spec.placement.affinity` admission rule, the future M4 per-hint
5269/// node-affinity / pod-affinity rule generator keying off the same
5270/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
5271/// selector) requires the value to be a DNS-1123 label — K8s label
5272/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
5273/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
5274/// admission rule the apiserver enforces.
5275///
5276/// Until this gate landed an `:affinity "DataLocality"` (the canonical
5277/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
5278/// Python-module-name leak), `:affinity "data.locality"` (the
5279/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
5280/// `:affinity "data-locality-"` (boundary-hyphen violation),
5281/// `:affinity "data locality"` (paste-from-doc whitespace),
5282/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
5283/// 64-byte over-cap slug silently passed the empty-only check and the
5284/// failure surfaced as a no-match at the M3 Adaptive compression
5285/// overlay's filter time (`placement.affinity` carried a malformed
5286/// value, no node matched, the workload landed on the default
5287/// heuristic) — the canonical "declared-but-inert" footgun mirroring
5288/// the empty-:affinity / empty-shard-key / zero-:politicas /
5289/// empty-:contratos-target gates already close on every other
5290/// declare-but-no-opinion axis. Lifting the rejection to a build-time
5291/// gate closes the fifth typed slot on the Aplicacao surface to land
5292/// on the canonical DNS-1123 label floor (after the four Servico-name
5293/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
5294/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
5295/// b0e8748).
5296///
5297/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
5298/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
5299/// validated values are guaranteed-accepted by the apiserver without
5300/// re-validation at any downstream renderer or admission layer.
5301fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
5302    // Empty is gated separately at the call site for a self-locating
5303    // diagnostic; re-checking here keeps the predicate usable from any
5304    // future call site (the M4 CR materializer's per-affinity
5305    // validator) without an empty-check footgun. Routes through the
5306    // shared [`crate::render::require_valid_dns_1123_label`] gate the
5307    // peer name axes each land on.
5308    crate::render::require_valid_dns_1123_label(
5309        affinity,
5310        || AplicacaoError::PlacementAffinityEmpty,
5311        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
5312    )
5313}
5314
5315/// Reject `:placement :shard-key` extractor expressions whose shape can
5316/// never legitimately drive the future M4 Akka-style cluster-sharding
5317/// reconciler's hash-extractor pass. Maps the per-byte / length checks
5318/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
5319/// diagnostic is self-locating (the offending `:shard-key` value is
5320/// named verbatim alongside the parser-shaped reason) and the author can
5321/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
5322/// edit.
5323///
5324/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
5325/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
5326/// expression naming the message property to hash on. The realistic
5327/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
5328/// property name; `$tenantId` — Akka entity-id placeholder;
5329/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
5330/// `${tenant}` — interpolation-style template) all sit in the printable
5331/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
5332/// multi-line blob landing in `:shard-key`, an embedded space from a
5333/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
5334/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
5335/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
5336/// check and the failure surfaces at the future M4 reconciler's hash
5337/// pass as a runtime extractor-evaluation error far from the source
5338/// `caixa.lisp`, with no field naming which member's `:shard-key`
5339/// carried the offending value.
5340///
5341/// The contract — the printable ASCII single-token intersection-floor
5342/// every Akka-style entity-id extractor implementation admits:
5343///
5344///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
5345///     peer DNS-1123-label-shaped `:placement :affinity` /
5346///     `:placement :clusters` identifier axes; realistic shard-keys sit
5347///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
5348///     blob footguns at validate time;
5349///   - every byte in the printable ASCII range `0x21..=0x7E` —
5350///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
5351///     `"$tenantId\n"` from paste-from-aligned-doc /
5352///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
5353///     `\x7F` — the canonical "embedded null from a copy-paste-binary
5354///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
5355///     un-Punycode-encoded IDN that round-trips inconsistently across
5356///     NFC/NFD normalization).
5357///
5358/// The accepted set is broader than the DNS-1123 label floor the peer
5359/// `:placement :clusters` / `:placement :affinity` axes use because the
5360/// `:shard-key` value is not a K8s `metadata.name` / label-selector
5361/// landing site; it's an extractor expression the future Akka-style
5362/// reconciler reads as a property reference. The realistic forms
5363/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
5364/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
5365/// but every Akka-style entity-id extractor parses. The
5366/// printable-ASCII-token floor accepts every shape any such extractor
5367/// would accept while rejecting the cross-implementation footguns
5368/// (whitespace breaks token boundaries; non-ASCII round-trips
5369/// inconsistently across YAML emitters and NFC/NFD normalization;
5370/// control characters silently corrupt the next read).
5371///
5372/// Until this gate landed `validate_placement` only refused the
5373/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
5374/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
5375/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
5376/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
5377/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
5378/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
5379/// control character from paste-from-binary, the 64-byte over-cap
5380/// paste-from-doc multi-line slug) silently passed validate. The future
5381/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
5382/// would then surface the malformed value either as a runtime
5383/// extractor-evaluation error (whitespace breaks the extractor's token
5384/// boundary, no match) or as a silently-different shard assignment
5385/// across YAML emitters (non-ASCII normalizes differently between the
5386/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
5387/// parser, the same entity ID maps to two distinct shards on a
5388/// re-render). Lifting the shape gate to caixa-build time makes the
5389/// extractor-floor invariant a structural property of every validated
5390/// `Placement`: every `Sharded` placement past `validate_placement` has
5391/// a `:shard-key` the future M4 reconciler can hash without
5392/// re-validating at the runtime layer.
5393///
5394/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
5395/// [`AplicacaoError::ContratoSubjectInvalid`] /
5396/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
5397/// on the peer `:contratos` payload axes — each lifts the
5398/// runtime-side parser's intersection-floor to a caixa-build-time gate,
5399/// closing the canonical "this passed validate but the runtime parser
5400/// rejected it" surprise.
5401fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
5402    // Empty is gated separately at the call site via the more
5403    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
5404    // re-checking here keeps the predicate usable from any future call
5405    // site (the M4 CR materializer's per-shard-key validator) without
5406    // an empty-check footgun.
5407    if key.is_empty() {
5408        return Err(AplicacaoError::ShardedKeyEmpty);
5409    }
5410    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
5411        return Err(AplicacaoError::shard_key_invalid(
5412            key,
5413            format!(
5414                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
5415                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
5416                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
5417                 well under 32 bytes, this length suggests a paste-from-doc \
5418                 multi-line blob landed in `:shard-key` instead of a single-token \
5419                 extractor expression)",
5420                key.len()
5421            ),
5422        ));
5423    }
5424    for &b in key.as_bytes() {
5425        if (0x21..=0x7E).contains(&b) {
5426            continue;
5427        }
5428        let reason = if b == b' ' {
5429            "contains a space (Akka-style entity-id extractor expressions are \
5430             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
5431             whitespace breaks the extractor's token boundary at the runtime layer, \
5432             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
5433             a multi-token blob in one `:shard-key` slot)"
5434                .to_string()
5435        } else if b == b'\t' {
5436            "contains a tab character (paste-from-aligned-doc footgun; the \
5437             Akka-style entity-id extractor reads `:shard-key` as a single-token \
5438             reference, embedded whitespace breaks the token boundary at the \
5439             runtime hash-extractor pass)"
5440                .to_string()
5441        } else if b == b'\n' || b == b'\r' {
5442            format!(
5443                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
5444                 paste-from-multiline-doc footgun; the Akka-style entity-id \
5445                 extractor reads `:shard-key` as a single-token reference, embedded \
5446                 newlines either truncate the value at the YAML emitter layer or \
5447                 break the token boundary at the runtime hash-extractor pass)"
5448            )
5449        } else if b < 0x20 || b == 0x7F {
5450            format!(
5451                "contains control character 0x{b:02x} (the canonical \
5452                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
5453                 control characters silently corrupt round-trip serialization \
5454                 across YAML emitters and break the runtime hash-extractor's \
5455                 single-token parser)"
5456            )
5457        } else {
5458            format!(
5459                "contains non-ASCII byte 0x{b:02x} (the canonical \
5460                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
5461                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
5462                 across YAML emitter implementations — the same entity ID can \
5463                 silently map to two distinct shards on a re-render. Use a \
5464                 printable-ASCII extractor expression like `tenantId`, \
5465                 `$tenantId`, or `metadata.tenantId`)"
5466            )
5467        };
5468        return Err(AplicacaoError::shard_key_invalid(key, reason));
5469    }
5470    Ok(())
5471}
5472
5473/// Reject `:contratos :de` / `:contratos :para` values whose shape
5474/// can never legitimately match a validated `:membros :caixa`. Thin
5475/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5476/// shared parser-shaped reason into the
5477/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
5478/// diagnostic is self-locating (which slot — `:de` or `:para` — and
5479/// the offending value verbatim) and the author can grep their
5480/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
5481/// one edit.
5482///
5483/// Until this gate landed an empty or DNS-1123-malformed `:de` /
5484/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
5485/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
5486/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
5487/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
5488/// un-Punycode-encoded IDN) silently passed the per-axis check and
5489/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
5490/// membership lookup — diagnostic-framed as "this caixa is not in
5491/// `:membros`" when the root cause is "this `:de` value is not a
5492/// well-shaped Servico-name identifier and could never legitimately
5493/// match any validated member". Because every `:membros :caixa` is
5494/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
5495/// `names` HashSet structurally never contains an empty / malformed
5496/// string, so the membership lookup arm misframes every empty /
5497/// malformed input. Lifting the shape arm ahead of the lookup
5498/// preserves the legitimate `ContratoMemberMissing` arm (a
5499/// well-shaped `:de` that simply isn't in `:membros` — a phantom
5500/// reference) while routing every structurally-impossible-to-match
5501/// input through the narrower self-locating shape diagnostic.
5502///
5503/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5504/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
5505/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
5506/// to land on the canonical [`crate::render::is_dns_1123_label`]
5507/// floor. The `slot: &'static str` field carries the kebab-case
5508/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
5509/// per-callback-slot diagnostic shape and the
5510/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
5511/// (85f102c) cross-list-tag pattern.
5512fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
5513    // Routes through the shared
5514    // [`crate::render::require_valid_dns_1123_label`] gate the peer
5515    // name axes each land on. The `slot: &'static str` field flows
5516    // through both error variants so the diagnostic names which
5517    // per-edge axis (`:de` vs `:para`) the offending value came from.
5518    crate::render::require_valid_dns_1123_label(
5519        caixa,
5520        || AplicacaoError::contrato_caixa_empty(slot),
5521        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
5522    )
5523}
5524
5525/// Reject `:entrada :para` values whose shape can never legitimately
5526/// match a validated `:membros :caixa`. Thin wrapper around
5527/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
5528/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
5529/// variant, so the diagnostic is self-locating (the offending
5530/// `:entrada :para` value is named verbatim) and the author can grep
5531/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
5532///
5533/// Until this gate landed an empty or DNS-1123-malformed `:entrada
5534/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
5535/// ADR typo, `:para "my_cart"` the Python-module-name leak,
5536/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
5537/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
5538/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
5539/// silently passed the per-axis check and surfaced as
5540/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
5541/// — diagnostic-framed as "this caixa is not in `:membros`" when the
5542/// root cause is "this `:entrada :para` value is not a well-shaped
5543/// Servico-name identifier and could never legitimately match any
5544/// validated member". Because every `:membros :caixa` is shape-
5545/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
5546/// `HashSet` structurally never contains an empty / malformed string,
5547/// so the membership lookup arm misframes every empty / malformed
5548/// input. Lifting the shape arm ahead of the lookup preserves the
5549/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
5550/// simply isn't in `:membros` — a phantom reference) while routing
5551/// every structurally-impossible-to-match input through the narrower
5552/// self-locating shape diagnostic.
5553///
5554/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5555/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
5556/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
5557/// fourth and last Aplicacao-level Servico-name reference axis to
5558/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
5559/// No `slot: &'static str` field because there is only one axis
5560/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
5561/// the simpler shape mirrors [`validate_membro_caixa`] and
5562/// [`validate_placement_cluster`].
5563fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
5564    // Empty is gated separately at the call site for a self-locating
5565    // diagnostic; re-checking here keeps the predicate usable from any
5566    // future call site (the M4 CR materializer's per-`:entrada`
5567    // validator) without an empty-check footgun. Routes through the
5568    // shared [`crate::render::require_valid_dns_1123_label`] gate the
5569    // peer name axes each land on.
5570    crate::render::require_valid_dns_1123_label(
5571        para,
5572        || AplicacaoError::EntradaParaEmpty,
5573        |reason| AplicacaoError::entrada_para_invalid(para, reason),
5574    )
5575}
5576
5577/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
5578/// would refuse at admission time. The contract — exactly the regex
5579/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5580/// and `HTTPRoute.spec.hostnames[]`,
5581/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5582/// (max length 253; per-label max length 63):
5583///
5584///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5585///     uppercase, no underscore, no Unicode/IDN — IDN must be
5586///     pre-encoded as Punycode `xn--…` by the author);
5587///   - exactly one optional leading wildcard label (`*.`); a wildcard
5588///     in any non-leading label position is rejected;
5589///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5590///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5591///   - total length 1..=253 bytes;
5592///   - no IPv4 literal (Gateway API forbids IP literals);
5593///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5594///     whitespace, no path (`/`).
5595///
5596/// Lifted as a typed gate (rather than an inline cascade in
5597/// `validate()`) so the contract lives in one place — every future
5598/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5599/// materializer's host validator, the future per-`:entrada` SAN
5600/// emission for cert-manager Certificates, the multi-`:entrada`
5601/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5602/// for the same predicate, not its own. Same compounding shape as
5603/// `is_canonical_rate_limit_window` (808017c) and
5604/// [`WitTarget::label`] (previously the free `contrato_target_label`
5605/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5606/// per-variant label match is compiler-checked-exhaustive).
5607///
5608/// The diagnostic carries the offending `host:` verbatim plus a
5609/// parser-shaped `reason:` naming the specific violation, so the
5610/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5611/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5612/// (9888b13).
5613fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5614    // Empty is already gated by `EmptyEntradaHost` at the call site;
5615    // re-checking here keeps the predicate usable from any future
5616    // call site (M4 CR materializer) without an empty-check footgun.
5617    if host.is_empty() {
5618        return Err(AplicacaoError::EmptyEntradaHost);
5619    }
5620    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5621        return Err(AplicacaoError::entrada_host_invalid(
5622            host,
5623            format!(
5624                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5625                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5626                host.len(),
5627                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5628            ),
5629        ));
5630    }
5631    if host.contains("://") {
5632        return Err(AplicacaoError::entrada_host_invalid(
5633            host,
5634            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5635             Gateway API takes the bare hostname)",
5636        ));
5637    }
5638    if host.contains('/') {
5639        return Err(AplicacaoError::entrada_host_invalid(
5640            host,
5641            "must not carry a path (drop the `/…` suffix; Gateway API path \
5642             matching is in `:entrada :paths`)",
5643        ));
5644    }
5645    // After the `://` scheme-prefix and `/` path arms have ruled out the
5646    // two `:`-bearing shapes the Gateway API actively rejects with
5647    // location-shaped diagnostics, any remaining `:` in the host body is
5648    // either the canonical "I put the port in the `:host` slot"
5649    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5650    // slot lives one axis away on the same `:entrada` block) or an
5651    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5652    // Hostname forbids identically to the IPv4-literal arm below. Both
5653    // shapes silently fell through the `://` and `/` arms before this
5654    // lift and surfaced as a deep `label "<rest>:<port>" contains
5655    // invalid character ':'` diagnostic from the per-byte loop near the
5656    // bottom of this predicate, which named the offending byte but not
5657    // the canonical authoring fix — for the port case the author has to
5658    // know the `:entrada` block carries a separate `:port u16` slot
5659    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5660    // move the value over; for the IPv6 case the author has to know
5661    // Gateway API v1 forbids IP literals across the board. The contract
5662    // doc-comment above already promises "no port (`:8080`)" verbatim
5663    // in the rejected-shape enumeration but the predicate's
5664    // implementation refused the `:` only as a side-effect of the
5665    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5666    // implementation in line with the documented contract by surfacing
5667    // the canonical fix at the top-level shape gate, peer with how the
5668    // `://` arm names the scheme prefix and the `/` arm names the
5669    // `:entrada :paths` axis. Same compounding trajectory the recent
5670    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5671    // — the typed slot's rejected set matches the apiserver's rejected
5672    // set, structurally, with a self-locating diagnostic at the
5673    // offending axis instead of a deep parser-shape leak.
5674    if host.contains(':') {
5675        return Err(AplicacaoError::entrada_host_invalid(
5676            host,
5677            "must not contain `:` (the port belongs in the `:entrada :port` \
5678             slot — a separate `u16` axis on the same `:entrada` block, \
5679             defaulting to 8080 — not in the host body; drop the `:<port>` \
5680             suffix and author the bare hostname. If you intended an IPv6 \
5681             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5682             Hostname forbids IP literals identically to the IPv4-literal \
5683             arm — use a DNS name)",
5684        ));
5685    }
5686    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5687    // predicate — the same single source of truth every peer
5688    // ASCII-whitespace scan in caixa-core flows through: the four
5689    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5690    // `:limits :memory`, `limits::parse_duration` backing `:limits
5691    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5692    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5693    // :rate-limit`) and the shared duration codec
5694    // (`supervisor::duration_codec::parse`) backing `:supervisor
5695    // :restart-window` / `:politicas :timeout` / `:politicas
5696    // :circuit-breaker :window`. This landing closes the last string-typed
5697    // slot in caixa-core still calling `.bytes().any(|b|
5698    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5699    // across every typed slot now shares one predicate, so a future
5700    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5701    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5702    // deliberately excluded from the peer non-ASCII predicate) can
5703    // extend at this shared site in one edit rather than seven
5704    // independent scans diverging over time. Naming the offending byte
5705    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5706    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5707    // the offending byte verbatim" discipline every peer codec site
5708    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5709    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5710    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5711        return Err(AplicacaoError::entrada_host_invalid(
5712            host,
5713            format!(
5714                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5715                 Hostname is a single-token DNS name — leading, trailing, \
5716                 or embedded whitespace breaks the K8s apiserver's Hostname \
5717                 regex at admission time; the paste-from-aligned-doc / \
5718                 paste-from-shell-history / paste-from-CSV footgun silently \
5719                 lands a multi-token blob in `:entrada :host`. Strip every \
5720                 whitespace byte and author the bare hostname — space \
5721                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5722                 refuse identically)"
5723            ),
5724        ));
5725    }
5726    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5727    // subset of Unicode `White_Space` through the shared
5728    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5729    // single source of truth every peer non-ASCII-whitespace scan in
5730    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5731    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5732    // `limits::parse_millicores` (`:limits :cpu`),
5733    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5734    // and `supervisor::duration_codec::parse` (`:supervisor
5735    // :restart-window` / `:politicas :timeout` / `:politicas
5736    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5737    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5738    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5739    // paste-from-web-doc), or an EM-SPACE-split host
5740    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5741    // survived this predicate's ASCII byte-scan (none of the UTF-8
5742    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5743    // `u8::is_ascii_whitespace`), then landed on the per-label
5744    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5745    // predicate with the generic `label "…" must start and end with an
5746    // alphanumeric` diagnostic — a "far from source at build-time"
5747    // leak that names the label-shape violation but not the
5748    // paste-from-typography origin the author actually needs to fix.
5749    // Peer with the four codec sites the 1b75b38 landing pinned: the
5750    // typed slot's diagnostic axis names the offending codepoint
5751    // (`U+XXXX`) verbatim rather than laundering the value through a
5752    // downstream label-shape arm, so the author can grep their
5753    // caixa.lisp for the invisible codepoint at the surfaced position
5754    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5755    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5756    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5757    // drift between any two typed-slot sites' non-ASCII-whitespace
5758    // rejection set becomes a single-edit fix at the shared predicate
5759    // rather than N independent inline scans diverging over time, and
5760    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5761    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5762    // `char::is_whitespace`" class the peer non-ASCII predicate's
5763    // doc-comment names as the follow-up trajectory) extends at the
5764    // shared predicate in one edit rather than seven.
5765    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5766        return Err(AplicacaoError::entrada_host_invalid(
5767            host,
5768            format!(
5769                "contains non-ASCII Unicode whitespace character {ch:?} \
5770                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5771                 single-token DNS name limited to `[a-z0-9-]` labels; \
5772                 the paste-from-typography footgun silently lands an \
5773                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5774                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5775                 `U+3000`, and every other member of the Unicode \
5776                 `White_Space` property outside the ASCII byte range) \
5777                 in `:entrada :host`, which the K8s apiserver's \
5778                 Hostname regex refuses at admission time far from the \
5779                 caixa.lisp source line. Strip every non-ASCII \
5780                 whitespace character and author the bare hostname \
5781                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5782                 verbatim)",
5783                codepoint = ch as u32,
5784            ),
5785        ));
5786    }
5787
5788    // Strip the optional single leading wildcard label *before* the
5789    // trailing-dot check so the bare `"*."` form surfaces the more
5790    // self-locating "wildcard without domain" diagnostic instead of
5791    // the generic "trailing dot" one.
5792    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5793        Some(r) => (true, r),
5794        None => (false, host),
5795    };
5796    if had_wildcard && rest.is_empty() {
5797        return Err(AplicacaoError::entrada_host_invalid(
5798            host,
5799            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5800        ));
5801    }
5802    if rest.contains('*') {
5803        return Err(AplicacaoError::entrada_host_invalid(
5804            host,
5805            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5806             no inner or trailing `*` labels",
5807        ));
5808    }
5809    if rest.ends_with('.') {
5810        return Err(AplicacaoError::entrada_host_invalid(
5811            host,
5812            "must not have a trailing `.` (Gateway API hostnames are not \
5813             fully-qualified with a root dot; the apiserver regex rejects \
5814             trailing dots)",
5815        ));
5816    }
5817
5818    // Reject pure IPv4 literals: four dot-separated labels, every
5819    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5820    // literals as Hostnames.
5821    let labels: Vec<&str> = rest.split('.').collect();
5822    if labels.len() == 4
5823        && labels
5824            .iter()
5825            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5826    {
5827        return Err(AplicacaoError::entrada_host_invalid(
5828            host,
5829            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5830             literals; use a DNS name)",
5831        ));
5832    }
5833
5834    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5835    // hyphen, with non-hyphen at both boundaries.
5836    for label in &labels {
5837        if label.is_empty() {
5838            return Err(AplicacaoError::entrada_host_invalid(
5839                host,
5840                "has an empty label (consecutive `..` or a leading `.`)",
5841            ));
5842        }
5843        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5844            return Err(AplicacaoError::entrada_host_invalid(
5845                host,
5846                format!(
5847                    "label {label:?} exceeds DNS-1123 label max length of \
5848                     {cap} bytes (got {} bytes)",
5849                    label.len(),
5850                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5851                ),
5852            ));
5853        }
5854        let bytes = label.as_bytes();
5855        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5856            return Err(AplicacaoError::entrada_host_invalid(
5857                host,
5858                format!(
5859                    "label {label:?} must start and end with an alphanumeric \
5860                     (no leading or trailing `-`)"
5861                ),
5862            ));
5863        }
5864        for &b in bytes {
5865            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5866            if !valid {
5867                let msg = if b.is_ascii_uppercase() {
5868                    format!(
5869                        "label {label:?} contains uppercase character {ch:?} \
5870                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5871                        ch = b as char,
5872                        lower = label.to_ascii_lowercase()
5873                    )
5874                } else if b == b'_' {
5875                    format!(
5876                        "label {label:?} contains `_` (Gateway API hostnames \
5877                         allow only `[a-z0-9-]`; use `-` instead)"
5878                    )
5879                } else {
5880                    format!(
5881                        "label {label:?} contains invalid character {ch:?} \
5882                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5883                        ch = b as char
5884                    )
5885                };
5886                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5887            }
5888        }
5889    }
5890    Ok(())
5891}
5892
5893/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5894/// would refuse at admission time. Thin wrapper around
5895/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5896/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5897/// variant, preserving the more self-locating
5898/// [`AplicacaoError::EntradaPathEmpty`] /
5899/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5900/// path fails those narrower invariants first.
5901///
5902/// The contract is the canonical HTTP-path grammar — `1..=
5903/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5904/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5905/// whitespace/control/non-ASCII bytes — shared with the
5906/// `:contratos :endpoint` axis through the lifted predicate so drift
5907/// between either landing site and the K8s apiserver-side
5908/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5909/// the predicate, not a per-renderer "this passed validate but failed
5910/// admission" surprise. The diagnostic carries the offending `path:`
5911/// verbatim plus a parser-shaped `reason:` naming the specific
5912/// violation, so the author can grep their caixa.lisp for `:paths`
5913/// and fix it in one edit. Same diagnostic shape as
5914/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5915/// axis.
5916fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5917    // Empty and missing-leading-`/` are already gated at the call
5918    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5919    // checking here keeps the per-axis narrower diagnostics in force
5920    // when the predicate is reached directly (and `is_gateway_api_http_path`
5921    // itself defends against `bytes[0]`-style indexing on empty
5922    // input).
5923    if path.is_empty() {
5924        return Err(AplicacaoError::EntradaPathEmpty);
5925    }
5926    if !path.starts_with('/') {
5927        return Err(AplicacaoError::entrada_path_not_absolute(path));
5928    }
5929    crate::render::is_gateway_api_http_path(path)
5930        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5931}
5932
5933mod rate_limit_codec {
5934    // `Duration` is no longer named here — the codec routes through
5935    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5936    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5937    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5938    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5939    // closed-set enum's arm-table rather than through vestigial free-helper
5940    // delegates.
5941    use super::{RateLimit, RateLimitUnit};
5942    use serde::{Deserializer, Serializer};
5943
5944    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5945        // Route through the canonical [`crate::render::serialize_option_via_str`]
5946        // — the substrate-side single-owner primitive for the forward
5947        // arm of the typed-magnitude codec family. See its docstring
5948        // for the full sibling roster.
5949        crate::render::serialize_option_via_str(v, s, render)
5950    }
5951
5952    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5953        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5954        // — the substrate-side single-owner primitive for the reverse
5955        // arm of the typed-magnitude codec family. See its docstring
5956        // for the full sibling roster.
5957        crate::render::deserialize_option_via_str(d, parse)
5958    }
5959
5960    fn parse(s: &str) -> Result<RateLimit, String> {
5961        // Paired whitespace-rejection arm — same canonical-form
5962        // render-determinism discipline as the peer
5963        // `limits::parse_byte_size` / `limits::parse_duration` /
5964        // `limits::parse_millicores` /
5965        // `supervisor::duration_codec::parse` sites: the ASCII
5966        // byte-scan closes the WhatWG-conformant whitespace bytes
5967        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5968        // `char::is_whitespace` scan closes the strictly-complementary
5969        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5970        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5971        // codepoints) that `str::trim` at parse entry silently strips.
5972        // Either drift class would round-trip through `render` to a
5973        // *different* canonical form on next emit — breaking the
5974        // THEORY.md Part V render-determinism contract on
5975        // `:politicas :rate-limit`.
5976        //
5977        // Routed through the lifted [`crate::render::reject_whitespace`]
5978        // primitive — the substrate-side single-owner paired-arm gate
5979        // every typed-magnitude codec in caixa-core shares.
5980        crate::render::reject_whitespace::<String, _, _>(
5981            s,
5982            |b| {
5983                format!(
5984                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5985                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5986                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5987                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5988                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5989                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5990                 on first serialize — breaking the THEORY.md Part V render-determinism \
5991                 contract every typed slot carries. Strip every whitespace byte (write \
5992                 `\"100/s\"` verbatim)"
5993                )
5994            },
5995            |ch| {
5996                format!(
5997                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5998                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5999                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
6000                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
6001                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
6002                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
6003                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
6004                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
6005                 silently strips it at parse entry, and the value round-trips through \
6006                 `render` to a *different* canonical form (`\"100/s\"`) on first \
6007                 serialize — breaking the THEORY.md Part V render-determinism contract \
6008                 every typed slot carries. Strip every non-ASCII whitespace character \
6009                 (write `\"100/s\"` verbatim with only ASCII bytes)",
6010                    cp = ch as u32
6011                )
6012            },
6013        )?;
6014        let s = s.trim();
6015        let (rate_str, unit) = s
6016            .split_once('/')
6017            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
6018        let rate_trim = rate_str.trim();
6019        // The canonical authoring form for `:politicas :rate-limit` is
6020        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
6021        // non-negative integer with no decimal point and no leading
6022        // sign, so the parser's accepted set must match for
6023        // serialize/deserialize to round-trip without canonical-form
6024        // drift. Until this gate landed the parser accepted any
6025        // `u32::from_str`-shaped magnitude — and current Rust
6026        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
6027        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
6028        // serde silently round-tripped to `"100/s"` on the next emit
6029        // (a *different* canonical string) — breaking the THEORY.md
6030        // Part V render-determinism contract on the fifth typed-codec
6031        // surface in caixa-core (peer with the four duration codecs the
6032        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
6033        // already covered: `supervisor::duration_codec` backing three
6034        // typed-duration slots, `limits::parse_duration` backing
6035        // `:limits :wall-clock`, `limits::parse_byte_size` backing
6036        // `:limits :memory`). The fractional / decimal-shaped sibling
6037        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
6038        // existing rejection arm, but the diagnostic is value-laundered
6039        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
6040        // doesn't name the canonical-form remediation or the round-trip
6041        // drift the next emit would produce); this gate lifts the
6042        // fractional arm onto the same canonical-form diagnostic the
6043        // peer codecs carry.
6044        //
6045        // Strict canonical form: every byte of the magnitude is an
6046        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
6047        // inputs the gate distinguishes "non-canonical-but-numeric"
6048        // (parses as f64 or i64 — surfaced with a self-locating
6049        // diagnostic naming the canonical authoring form and the
6050        // round-trip drift the rejected shape would produce on first
6051        // serialize) from "garbage" (parses as neither — surfaced with
6052        // the existing narrower `"not a u32"` wording so its
6053        // diagnostic shape remains stable for the parser-shape footgun
6054        // case).
6055        //
6056        // Routed through the lifted
6057        // [`crate::render::is_digit_only_magnitude`] predicate — the
6058        // same source of truth the four peer typed-magnitude codec
6059        // sites share.
6060        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
6061        if !digit_only {
6062            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
6063            if numeric {
6064                return Err(format!(
6065                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
6066                     canonical authoring form for `:politicas :rate-limit` is \
6067                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6068                     with no decimal point and no leading `+` / `-` sign. A fractional / \
6069                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
6070                     through `render` to a *different* canonical form (`\"1/s\"`, \
6071                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
6072                     THEORY.md Part V render-determinism contract every typed slot \
6073                     carries. Pick an integer rate that fits the desired window \
6074                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
6075                ));
6076            }
6077            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
6078        }
6079        // Leading-zero arm — peer with the prior `"+100/s"` arm above
6080        // (4eeae98's predecessor) on the same canonical-form
6081        // render-determinism axis. The digit-only gate accepts
6082        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
6083        // them losslessly (= 100, 0, 7), but `render` emits the
6084        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
6085        // a *different* canonical string on the next emit, breaking
6086        // the THEORY.md Part V render-determinism contract the same
6087        // way `"+100/s"` did before the leading-`+` arm landed. The
6088        // single-byte magnitude `"0"` itself round-trips losslessly
6089        // through `render` (`render(0)` emits `"0/s"`) — the
6090        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
6091        // what refuses rate-zero authoring, so `"0/s"` stays in the
6092        // accepted set at this codec layer and the diagnostic
6093        // partitioning between canonical-form drift (this arm) and
6094        // semantic-zero (the downstream gate) remains stable.
6095        // Peer with the future leading-zero arms on the three peer
6096        // typed-magnitude codecs the trajectory acknowledges:
6097        // `supervisor::duration_codec`, `limits::parse_duration`,
6098        // `limits::parse_byte_size` — each carries the same
6099        // canonical-form-drift class today; this gate lands the
6100        // discipline on the fourth typed-magnitude codec in
6101        // caixa-core first because the peer `"+100/s"` arm above is
6102        // the closest predecessor on the trajectory.
6103        //
6104        // Routed through the lifted
6105        // [`crate::render::is_leading_zero_padded_magnitude`]
6106        // predicate — the same source of truth the four peer
6107        // typed-magnitude codec sites share.
6108        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
6109            return Err(format!(
6110                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
6111                 canonical authoring form for `:politicas :rate-limit` is \
6112                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6113                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
6114                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
6115                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
6116                 first serialize — breaking the THEORY.md Part V render-determinism \
6117                 contract every typed slot carries. Strip the leading zeros (write \
6118                 `\"100/s\"` instead of `\"0100/s\"`)"
6119            ));
6120        }
6121        // The digit-only gate guarantees every byte is `[0-9]`, and
6122        // the leading-zero arm above guarantees the magnitude is
6123        // either the single byte `"0"` or starts with `[1-9]`, so
6124        // the only way `u32::from_str` can fail here is overflow
6125        // (the magnitude exceeds `u32::MAX`). Surface that with an
6126        // overflow-shaped wording so the diagnostic names the
6127        // offending magnitude verbatim rather than collapsing onto
6128        // the non-canonical arm. Same shape
6129        // `supervisor::duration_codec` (1c55a2a) carries on the peer
6130        // duration-codec axis.
6131        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
6132            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
6133        })?;
6134        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
6135        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
6136        // arm reads the `&str → Duration` projection through the
6137        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
6138        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
6139        // with [`super::RateLimitUnit::window`]) rather than the vestigial
6140        // module-private `rate_limit_window_from_unit` free helper the
6141        // predecessor 61421a6 left as the last unlifted delegate on this
6142        // axis. One typed dispatch on the substrate primitive instead of
6143        // one runtime call through the free-helper delegate; the sole
6144        // production consumer of the `&str → Duration` axis (this parse
6145        // arm) now reaches for exactly one typed method on the closed-set
6146        // enum, sibling to the codec's render arm's
6147        // [`super::RateLimit::canonical_unit`] dispatch on the paired
6148        // `Duration → RateLimitUnit` axis and to the validate gate's
6149        // [`super::RateLimit::canonical_unit`] shape-probe on the
6150        // canonical-window axis. A future rate-limit-unit addition (a
6151        // `"d"` day suffix once Envoy's `rate_limit_action` grows
6152        // daily-bucket support, a `"ms"` sub-second window once
6153        // high-throughput per-edge policies come into scope per
6154        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
6155        // on the closed-set enum, and the compiler enforces exhaustiveness
6156        // on every consumer's `match self` arms — this parse arm's
6157        // accepted-suffix set, the render arm's emitted-suffix set, the
6158        // validate gate's canonical-window set, and every future
6159        // per-`:contratos`-edge rate-limit-override overlay all pick it up
6160        // by construction.
6161        let unit = unit.trim();
6162        let window = RateLimitUnit::window_from_suffix(unit)
6163            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
6164        Ok(RateLimit { rate, window })
6165    }
6166
6167    fn render(rl: RateLimit) -> String {
6168        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
6169        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
6170        // this render arm reads the `Duration → RateLimitUnit` projection
6171        // through the substrate primitive [`super::RateLimit::canonical_unit`]
6172        // (returns `None` on every non-canonical window — the sub-second /
6173        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
6174        // formats the returned typed enum through its
6175        // [`std::fmt::Display`] impl (which routes through
6176        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
6177        // the substrate primitive instead of one runtime `find_map`
6178        // walk through the free-helper delegate chain
6179        // [`super::rate_limit_window_unit`] (the vestigial free helper's
6180        // sole production consumer was this arm; every other consumer of
6181        // the `Duration → unit` axis — the validate gate below and the
6182        // future M4 per-Aplicacao Envoy config reconciler — now reads
6183        // the same typed method).
6184        //
6185        // A future rate-limit-unit addition (a `"d"` day suffix once
6186        // Envoy's `rate_limit_action` grows daily-bucket support) is
6187        // one variant + one arm per method on the closed-set enum, and
6188        // the compiler enforces exhaustiveness on every consumer's
6189        // `match self` arms — the codec's `parse` accepted-suffix set,
6190        // this render arm's emitted-suffix set, the validate gate's
6191        // canonical-window set, and every future per-`:contratos`-edge
6192        // rate-limit-override overlay all pick it up by construction.
6193        if let Some(unit) = rl.canonical_unit() {
6194            format!("{}/{unit}", rl.rate())
6195        } else {
6196            // Defensive fallback for non-canonical windows. Note:
6197            // [`AplicacaoSpec::validate_politicas`] rejects any
6198            // non-canonical `:rate-limit :window` via
6199            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
6200            // a validated `RateLimit` never reaches this branch. The
6201            // emitted `<n>/<k>s` form is *not* round-trippable through
6202            // [`parse`] (which accepts only the closed-set
6203            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
6204            // explicit count) — the validate gate is what makes the
6205            // round-trip a structural property; this branch exists only
6206            // so a programmatic non-validated serialize doesn't panic.
6207            format!("{}/{}s", rl.rate(), rl.window().as_secs())
6208        }
6209    }
6210}
6211
6212// ── placement strategy ───────────────────────────────────────────────
6213
6214/// How the Aplicacao distributes across clusters. Three options:
6215///
6216/// - `SingleNode` — one cluster runs the app at a time; takeover on
6217///   death (Erlang/OTP distributed-app semantics).
6218/// - `Replicated` — every named cluster runs an instance (active-active).
6219/// - `Sharded` — entities distribute by hash key across clusters
6220///   (Akka cluster sharding).
6221#[derive(
6222    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
6223)]
6224pub enum PlacementStrategy {
6225    SingleNode,
6226    Replicated,
6227    Sharded,
6228}
6229
6230/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
6231/// distribution-strategy default for the `:placement :estrategia` axis —
6232/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
6233/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
6234/// so every substrate-side consumer that resolves "what
6235/// [`PlacementStrategy`] variant does an author-omitted `:placement
6236/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
6237/// primitive [`PlacementStrategy`].
6238///
6239/// The `:placement :estrategia` default axis has three production
6240/// consumers on the substrate side today: the [`Default for
6241/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
6242/// impl's struct-literal `estrategia` field, and the serde-side
6243/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
6244/// author-omitted `:placement :estrategia` scalar through the [`Default
6245/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
6246/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
6247/// impl and implicit `PlacementStrategy::default()` routes at the sibling
6248/// consumers, with no compile-time link back to the paired
6249/// [`crate::manifest::Caixa::aplicacao_view`] fold's
6250/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
6251/// production consumer that resolves an author-omitted `:placement` slot
6252/// (entirely omitted, not just the `:estrategia` scalar within a declared
6253/// `:placement` block) through [`Placement::default`] which then routes
6254/// through this same discriminator. A future coherent rebrand of the
6255/// `:placement :estrategia` default (a widening to `Sharded` once the
6256/// substrate discovers hash-keyed distribution as the more common
6257/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
6258/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
6259/// names, a per-cluster overlay the operator pins through a future
6260/// `:placement-overrides` slot) would have had to migrate a lifted
6261/// discriminator on one path and open-coded discriminators on the peers
6262/// in lockstep or the four consumers would silently drift out of
6263/// pairing. Lifting the resolution rule to a typed `pub const` on the
6264/// substrate primitive means the M3-mesh-canonical `:placement
6265/// :estrategia` default migrates as one unit on any future axis change.
6266///
6267/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
6268/// §II.2's active-active-across-every-named-cluster arm — the closest
6269/// canonical M3 production reference the substrate carries, matching the
6270/// caixa-mesh default axis every M3 renderer already keys off (a
6271/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
6272/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
6273/// under the substrate's fleet-programs aggregator without an explicit
6274/// `:placement :estrategia` override). The two alternatives the closed
6275/// [`PlacementStrategy::ALL`] accept-set carries
6276/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
6277/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
6278/// Akka-style hash-keyed distribution across clusters,
6279/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
6280/// postures an author declares explicitly, never a posture an omitted
6281/// slot should silently assume.
6282///
6283/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
6284/// exactly one source of truth on the `:placement :estrategia` axis, on
6285/// the same substrate-primitive lift discipline the sibling M2
6286/// per-supervisor default set carries
6287/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
6288/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
6289/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
6290/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
6291/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
6292/// ([`crate::render::DEFAULT_NAMESPACE`],
6293/// [`crate::render::DEFAULT_LIBRARY_NAME`],
6294/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
6295/// the M3 mesh-primitive-defining slot family to converge onto the
6296/// substrate-primitive-lift discipline the M2 supervisor-slot family
6297/// already carries end-to-end.
6298pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
6299
6300impl Default for PlacementStrategy {
6301    fn default() -> Self {
6302        // Route the [`Default for PlacementStrategy`] impl through the
6303        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
6304        // `pub const` rather than a raw `Self::Replicated` arm — one
6305        // source of truth for the M3-mesh-canonical active-active-
6306        // across-every-named-cluster `:placement :estrategia` default
6307        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
6308        // lift discipline the sibling M2 per-supervisor default set
6309        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
6310        // paired halves) carries end-to-end. Pinned by
6311        // `placement_strategy_default_routes_through_lifted_default`.
6312        PLACEMENT_ESTRATEGIA_DEFAULT
6313    }
6314}
6315
6316impl PlacementStrategy {
6317    /// Exhaustive iteration surface for every consumer that reads the
6318    /// full closed-set (the future M4 admission-webhook's accepted-
6319    /// strategy listing in its rejection body, a future `feira app
6320    /// placement --list` CLI-side surfacing of the accepted arm-set,
6321    /// any future round-trip fuzz harness). A future variant addition
6322    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
6323    /// names as a trajectory item) extends this slice as a single edit
6324    /// and every consumer picks up the new entry by construction — the
6325    /// compiler-checked exhaustiveness on the sibling method `match`
6326    /// arms is the build-time guarantee that no arm forgets to grow.
6327    /// Same shape as the sibling closed-set typed enums'
6328    /// [`RateLimitUnit::ALL`] (6bce03d) and
6329    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6330    /// surfaces — the third closed-set typed enum on the caixa surface
6331    /// to converge onto the same discipline.
6332    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
6333
6334    /// Canonical camelCase-schema discriminator scalar this variant
6335    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
6336    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
6337    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6338    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
6339    /// every substrate consumer that dispatches on the strategy (the
6340    /// `lareira-fleet-programs` aggregator, the future `app-operator`
6341    /// reconciler, the M3 Adaptive compression pass) reads the same
6342    /// byte-string the `Serialize` derive emits — the pin test in
6343    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
6344    /// asserts the two paths agree.
6345    #[must_use]
6346    pub const fn as_str(self) -> &'static str {
6347        match self {
6348            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
6349            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
6350            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
6351        }
6352    }
6353
6354    /// Substrate-canonical reverse projection on the `:placement
6355    /// :estrategia` closed-set axis — parses the camelCase-schema
6356    /// discriminator scalar back to the typed variant, or `None` when
6357    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
6358    /// emits. Dispatches on the same lifted
6359    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6360    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6361    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
6362    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
6363    /// the round-trip migrate through one caixa-core edit on any future
6364    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
6365    /// §II.5 hint names as a trajectory item lands one variant + one
6366    /// arm per method and the compiler enforces exhaustiveness on every
6367    /// consumer's `match self` arms).
6368    ///
6369    /// Prior to this lift the substrate carried only the forward
6370    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
6371    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
6372    /// derive that emits the same byte-string under
6373    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
6374    /// consumer that wanted to parse a wire-form strategy scalar had to
6375    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
6376    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
6377    /// compile-time link back to the typed variant's canonical lifted
6378    /// constant. A future variant rename or a per-arm serde-attribute
6379    /// drift would silently split the wire byte-string one non-serde
6380    /// consumer parsed from the one the emitter wrote, with the
6381    /// failure surfacing at parse time far from the rebrand commit.
6382    ///
6383    /// Same closed-set-reverse-projection discipline the sibling
6384    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
6385    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
6386    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
6387    /// defining `:placement :estrategia` closed-set axis, the third
6388    /// substrate-side closed-set typed enum to converge on the two-way
6389    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
6390    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
6391    /// and side-step the [`std::str::FromStr`]-collision clippy
6392    /// (`clippy::should_implement_trait`) the plain `from_str` name
6393    /// carries; a future explicit [`std::str::FromStr`] impl can layer
6394    /// on top by delegating to this canonical arm-dispatch method.
6395    ///
6396    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
6397    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
6398    /// picks the diagnostic form appropriate for its use site — a
6399    /// future `feira app placement --set` CLI-side arg-parse that wants
6400    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
6401    /// Sharded)"` diagnostic builds one on top by iterating
6402    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
6403    /// path folds `None` onto its per-CR structured refusal body.
6404    #[must_use]
6405    pub fn from_wire(s: &str) -> Option<Self> {
6406        match s {
6407            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
6408            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
6409            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
6410            _ => None,
6411        }
6412    }
6413
6414    /// Substrate-canonical per-arm predicate naming the cross-slot
6415    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
6416    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
6417    /// consumes the paired [`Placement::shard_key`] axis (and therefore
6418    /// requires — and is the only strategy that permits — a non-empty
6419    /// `:shard-key` on the paired slot). Today the accept-set is the
6420    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
6421    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
6422    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
6423    /// distributed-app takeover — §II.1) and `Replicated` (active-active
6424    /// across every named cluster) have no hash-keyed routing axis to
6425    /// consume the slot and refuse a declared-but-inert `:shard-key`
6426    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
6427    ///
6428    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
6429    /// satisfies `placement.shard_key().is_some() ==
6430    /// placement.estrategia().requires_shard_key()` by construction — the
6431    /// cross-slot partition the pin
6432    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
6433    /// locks load-bearing, so every downstream consumer that reaches for
6434    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6435    /// CR materializer's per-CR shard-key resolver, the future
6436    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
6437    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
6438    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
6439    /// shard-key requirement probe, a future author-facing tatara-lisp
6440    /// linter that flags `(:placement (:estrategia Replicated :shard-key
6441    /// "tenantId"))` shapes before `feira lint` reaches
6442    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
6443    /// the substrate primitive — the predicate names *the cross-slot
6444    /// invariant*, not the arm identity.
6445    ///
6446    /// Prior to this lift the "does this strategy consume `:shard-key`"
6447    /// classification lived under the `gen_platform::IsVariant`-derived
6448    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
6449    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
6450    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
6451    /// } else { None }` cascade, the
6452    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
6453    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
6454    /// "tenantId".to_string())` cascade, and the
6455    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
6456    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
6457    /// cascade). Each site conflated two semantically distinct questions:
6458    /// "is the variant `Sharded`?" (arm-identity, what
6459    /// [`Self::is_sharded`] answers) and "does the variant consume
6460    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
6461    /// The two questions land on the same three-way answer under today's
6462    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
6463    /// future arm addition that consumed `:shard-key` under a different
6464    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
6465    /// §II.5 roadmap-hint names that hash-partitions across the cluster
6466    /// pool by client-IP hash rather than an author-declared extractor
6467    /// expression, a hypothetical `WeightedShard` variant that carries a
6468    /// shard-key + per-cluster weight table under a promoted M5
6469    /// adaptive-placement engine) or an addition that did *not* consume
6470    /// `:shard-key` on a semantically Sharded-shaped arm would silently
6471    /// split the two questions. Any consumer that read
6472    /// `.is_sharded().then(…)` for the shard-key requirement gate would
6473    /// silently misclassify the new arm as non-consuming — a fixture
6474    /// builder would omit `:shard-key` where the new arm required one and
6475    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
6476    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
6477    /// commit, a future M4 CR materializer would fall through the
6478    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
6479    /// silently emit an empty extractor at the Akka reconciler layer.
6480    ///
6481    /// Lifting the classification as a substrate-primitive method on the
6482    /// closed-set typed enum names the cross-slot invariant on the
6483    /// primitive that owns the partition: every future arm addition
6484    /// declares its `:shard-key` consumption in one place (this predicate's
6485    /// `match self` arm-set), and every downstream consumer that reaches
6486    /// for the paired shape reads through one typed dispatch. Same
6487    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
6488    /// per-arm predicate on the pre-projection WIT-shape axis and the
6489    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
6490    /// paired predicate on the post-projection typed-view axis — a
6491    /// per-arm semantic-classification predicate paired with the
6492    /// arm-identity predicate the derive already emits, closing the drift
6493    /// footgun on the cross-slot invariant axis.
6494    ///
6495    /// Method-named `requires_shard_key` (not `has_shard_key`, not
6496    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
6497    /// invariant reads as "this strategy *requires* the paired
6498    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
6499    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
6500    /// merely omit it. The `has_*` framing would read as an accessor
6501    /// (returning the presence of an already-carried value) rather than a
6502    /// requirement (naming the invariant the paired slot must satisfy).
6503    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
6504    /// shape as the sibling [`WitContract::is_capability`] /
6505    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
6506    /// arm-family, so every consumer reaches for `.requires_shard_key()`
6507    /// as a drop-in replacement for the `.is_sharded()` conflated read
6508    /// without a return-shape migration.
6509    #[must_use]
6510    pub const fn requires_shard_key(self) -> bool {
6511        match self {
6512            Self::Sharded => true,
6513            Self::SingleNode | Self::Replicated => false,
6514        }
6515    }
6516}
6517
6518// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
6519// cross-slot-invariant per-arm predicate: the module-scope const-eval
6520// assertions below trip at caixa-core build time (not test time) if a
6521// future edit rewires the predicate's arm-set away from the singleton
6522// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
6523// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
6524// runtime pin covers the same truth-table with a more descriptive
6525// diagnostic on failure; these const-eval items add a build-time failure
6526// surface strictly stronger than the runtime pin (a downstream renderer's
6527// `const`-context reader that composed against a rebound predicate would
6528// still surface here before the test suite even ran) and side-step the
6529// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
6530// would otherwise accumulate on the caixa-core module baseline.
6531const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
6532const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
6533const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
6534
6535/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
6536/// the pretty-printed byte-string every consumer that formats the strategy
6537/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
6538/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
6539/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
6540/// per-Aplicacao strategy line, the future M4 CR materializer's per-
6541/// admission-webhook rejection body) reaches for the same lifted
6542/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6543/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6544/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
6545/// `Serialize` derive already emits under
6546/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
6547/// [`PlacementStrategy::as_str`] helper already returns.
6548///
6549/// Until this lift landed the sibling OTP-shape typed enums —
6550/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
6551/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
6552/// so [`std::fmt::Display`] routes through the same discriminant string
6553/// the wire format emits) — carried a stable [`std::fmt::Display`]
6554/// surface but [`PlacementStrategy`] did not; every consumer reaching
6555/// for a strategy byte-string past the wire format had to pick between
6556/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
6557/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
6558/// derive), any two of which a future variant rename or
6559/// `#[serde(rename_all = "kebab-case")]` attribute would silently
6560/// desynchronize — with the failure surfacing as a downstream renderer /
6561/// operator's per-strategy dispatch reading one spelling while the wire
6562/// format emitted another, far from the source rebrand commit and with
6563/// no field naming the drift. Routing `Display` through
6564/// [`PlacementStrategy::as_str`] makes the three paths
6565/// (`Debug` for structural inspection, `Display` for user-facing text,
6566/// `Serialize` for the wire format) converge on the same lifted
6567/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
6568/// the diagnostic byte-string, and the pretty-printed byte-string move
6569/// as a single unit through one canonical declaration each, by
6570/// construction. Same trajectory as [`PlacementStrategy::as_str`]
6571/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
6572/// closes the third path.
6573///
6574/// Pin tests
6575/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
6576/// and
6577/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
6578/// assert the three paths agree byte-for-byte on every variant, so a
6579/// future variant rename or per-arm serde attribute drift is a build
6580/// error visible at caixa-core test time, not a silent per-consumer
6581/// dispatch miss at apply / reconcile time.
6582impl std::fmt::Display for PlacementStrategy {
6583    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6584        f.write_str(self.as_str())
6585    }
6586}
6587
6588/// Substrate-canonical [`AsRef<str>`] projection on the M3
6589/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
6590/// typed enum — routes through the same [`PlacementStrategy::as_str`]
6591/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
6592/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
6593/// any future consumer that binds a [`PlacementStrategy`] through the
6594/// standard-library `impl AsRef<str>` bound (a future `feira app
6595/// placement --set <arm>` verb that composes the emitted
6596/// `PascalCase`/camelCase wire scalar into a
6597/// [`std::process::Command::arg`] shell-out of the future
6598/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
6599/// per-Aplicacao structured-log recorder on the future `app-operator`'s
6600/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
6601/// at the `tracing::field::Value` `Str`-arm, a
6602/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
6603/// through `map.get::<str>(strategy.as_ref())` on a future
6604/// per-strategy dispatch table the M5 adaptive-placement engine
6605/// composes) reaches the paired
6606/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6607/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6608/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
6609/// through one substrate-primitive dispatch rather than an open-coded
6610/// `.as_str()` projection at every wire-up.
6611///
6612/// Peer of the sibling [`std::fmt::Display`] impl on the same
6613/// primitive — both delegate to the shared
6614/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
6615/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
6616/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
6617/// instance by construction. A future variant rename or `#[serde(rename_all
6618/// = "kebab-case")]` attribute-drift on the enum reaches every one of
6619/// the three paths (plus the wire-format `Serialize` derive that
6620/// already routes through the same lifted const) through exactly one
6621/// caixa-core edit.
6622///
6623/// Same "route the trait impl through the substrate-primitive
6624/// accessor" discipline the sibling [`crate::CaixaVersion`]
6625/// [`AsRef<str>`] impl (16d5c7e), the paired M2
6626/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
6627/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
6628/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
6629/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
6630/// projection axis onto the last remaining M3 mesh-primitive-defining
6631/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
6632/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
6633/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
6634/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
6635/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
6636/// caller who has one has both; before this lift,
6637/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
6638/// [`AsRef<str>`] impl the convention names.
6639///
6640/// Pinned load-bearing by
6641/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
6642/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
6643/// three-arm closed set) and
6644/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
6645/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
6646/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
6647/// arm) — any future silent detour that routes the impl through a
6648/// divergent projection (a per-arm inline `match self { … }`
6649/// re-inlining that opens a compile-time link to the un-lifted
6650/// arm-literal, a swap onto the kebab-case
6651/// [`gen_platform::Discriminant`] catalog identity that would collide
6652/// the wire axis with the dispatcher-catalog axis) trips at
6653/// caixa-core test time under `assert_eq!` rather than at a downstream
6654/// `impl AsRef<str>`-bound consumer's silent split.
6655impl AsRef<str> for PlacementStrategy {
6656    fn as_ref(&self) -> &str {
6657        self.as_str()
6658    }
6659}
6660
6661/// Where the Aplicacao runs.
6662#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6663#[serde(rename_all = "camelCase")]
6664pub struct Placement {
6665    /// Distribution strategy.
6666    #[serde(default)]
6667    pub estrategia: PlacementStrategy,
6668
6669    /// Named clusters that host this Aplicacao. Required for
6670    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6671    /// shard pool.
6672    #[serde(default)]
6673    pub clusters: Vec<String>,
6674
6675    /// Optional hint to the placement engine: `"data-locality"`,
6676    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6677    #[serde(default, skip_serializing_if = "Option::is_none")]
6678    pub affinity: Option<String>,
6679
6680    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6681    #[serde(default, skip_serializing_if = "Option::is_none")]
6682    pub shard_key: Option<String>,
6683}
6684
6685impl Placement {
6686    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6687    /// `:shard-key` extractor-expression scalar accessor every consumer
6688    /// of the Aplicacao's hash-keyed distribution routing keys off —
6689    /// returns the author-declared `:placement :shard-key` byte-string
6690    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6691    /// own `Option<String>` storage; `None` when the slot is absent
6692    /// (the canonical shape under `:estrategia Replicated` /
6693    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6694    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6695    /// partition — `validate` refuses any `Placement` past this call
6696    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6697    /// `Sharded`).
6698    ///
6699    /// The `:placement :shard-key` slot carries the Akka-style
6700    /// cluster-sharding entity-id extractor expression
6701    /// (MESH-COMPOSITION §II.4) — validated by
6702    /// [`validate_placement_shard_key`] to be a non-empty printable-
6703    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6704    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6705    /// future M4 Akka-style cluster-sharding reconciler hashes without
6706    /// re-validating at the runtime layer), and every downstream
6707    /// consumer that reads the key keys off this scalar (the
6708    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6709    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6710    /// declared-but-inert refusal diagnostic, the caixa-mesh
6711    /// per-Aplicacao `placement.shardKey` emit path the substrate
6712    /// operator's per-entity hash-routing reader consumes, the future
6713    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6714    /// per-shard-key resolver).
6715    ///
6716    /// Prior to this lift the `.shard_key` field was accessed inline at
6717    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6718    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6719    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6720    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6721    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6722    /// — two open-coded field-accesses that expressed no compile-time
6723    /// link back to the typed slot. A future extension of the
6724    /// `:placement :shard-key` axis to a richer author surface — a
6725    /// per-cluster override the operator pins through a future
6726    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6727    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6728    /// alias table the M4 CR materializer resolves per-CR, a
6729    /// per-Aplicacao dynamic `:shard-key` derivation the future
6730    /// adaptive placement engine computes from `:affinity` weights —
6731    /// would have had to be threaded through both open-coded copies in
6732    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6733    /// arm refusal would silently disagree on which extractor
6734    /// expression a given Placement resolves to. Lifting the resolution
6735    /// rule to a typed method on the substrate primitive means every
6736    /// downstream consumer of the Aplicacao's per-`:placement`
6737    /// hash-key surface reaches for exactly one typed dispatch — the
6738    /// resolver's accept-set migrates as a unit on any future axis
6739    /// addition.
6740    ///
6741    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6742    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6743    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6744    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6745    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6746    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6747    /// typed dispatch on the substrate primitive, thin projections at
6748    /// each consumer" discipline extended onto the per-`:placement`
6749    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6750    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6751    /// — opens the "optional per-slot scalar" projection pattern the
6752    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6753    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6754    /// match the storage field's name; the accessor's identity name
6755    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6756    /// slot's docstring already carries.
6757    #[must_use]
6758    pub const fn shard_key(&self) -> Option<&str> {
6759        match &self.shard_key {
6760            Some(s) => Some(s.as_str()),
6761            None => None,
6762        }
6763    }
6764
6765    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6766    /// compression-hint scalar accessor every weighting-consumer of the
6767    /// Aplicacao's per-hint routing surface keys off — returns the
6768    /// author-declared `:placement :affinity` byte-string verbatim as
6769    /// an `Option<&str>`, borrowed from the typed slot's own
6770    /// `Option<String>` storage; `None` when the slot is absent (the
6771    /// canonical shape of an Aplicacao that leaves the compression
6772    /// weighting up to the placement engine's cluster-default arm — no
6773    /// author-authored `data-locality` / `low-latency` / etc. hint
6774    /// biases the routing).
6775    ///
6776    /// The `:placement :affinity` slot carries the M3 Adaptive-
6777    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6778    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6779    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6780    /// K8s-conformant label-selector shape every apiserver-side pod-
6781    /// affinity / node-affinity materializer already gates on
6782    /// admission), and every downstream consumer that reads the hint
6783    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6784    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6785    /// `placement.affinity` overlay emit path the substrate operator's
6786    /// per-hint weighting-consumer reads, the future M4
6787    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6788    /// pod-affinity / node-affinity selector resolver).
6789    ///
6790    /// Prior to this lift the `.affinity` field was accessed inline at
6791    /// the sole caixa-core site — the
6792    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6793    /// `if let Some(a) = &self.placement.affinity { …
6794    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6795    /// field-access that expressed no compile-time link back to the
6796    /// typed slot. A future extension of the `:placement :affinity`
6797    /// axis to a richer author surface — a per-cluster override the
6798    /// operator pins through a future `:placement :affinity-overrides`
6799    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6800    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6801    /// a per-Aplicacao dynamic `:affinity` derivation the future
6802    /// adaptive placement engine computes from `:clusters` topology —
6803    /// would have had to be threaded through the open-coded copy in
6804    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6805    /// materializer reader that landed on the axis, or the per-hint
6806    /// value-shape gate and its downstream weighting consumers would
6807    /// silently disagree on which hint a given Placement resolves to.
6808    /// Lifting the resolution rule to a typed method on the substrate
6809    /// primitive means every downstream consumer of the Aplicacao's
6810    /// per-`:placement` compression-hint surface reaches for exactly
6811    /// one typed dispatch — the resolver's accept-set migrates as a
6812    /// unit on any future axis addition.
6813    ///
6814    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6815    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6816    /// optional-scalar axis — same "one typed dispatch on the substrate
6817    /// primitive, thin projections at each consumer" discipline extended
6818    /// onto the per-`:placement` M3-Adaptive-compression-hint
6819    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6820    /// return accessor on the M3 mesh-slot family; closes the last
6821    /// un-lifted per-`:placement` `Option<String>` axis. Named
6822    /// `affinity()` to match the storage field's name; the accessor's
6823    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6824    /// vocabulary the slot's docstring already carries.
6825    #[must_use]
6826    pub const fn affinity(&self) -> Option<&str> {
6827        match &self.affinity {
6828            Some(s) => Some(s.as_str()),
6829            None => None,
6830        }
6831    }
6832
6833    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6834    /// strategy scalar accessor every consumer that dispatches on the
6835    /// Aplicacao's per-cluster distribution shape keys off — returns the
6836    /// author-declared `:placement :estrategia` variant verbatim as a
6837    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6838    /// `PlacementStrategy` storage.
6839    ///
6840    /// The `:placement :estrategia` slot carries the closed-set
6841    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6842    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6843    /// `Replicated` — active-active across every named cluster; `Sharded`
6844    /// — Akka-style hash-keyed entity distribution across the cluster pool
6845    /// per §II.4) that every downstream consumer of the Aplicacao's
6846    /// per-cluster fan-out shape keys off. Validated by
6847    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6848    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6849    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6850    /// [`Placement::shard_key`] accessor's docstring pins), and every
6851    /// downstream consumer that reads the strategy keys off this scalar
6852    /// (the [`AplicacaoSpec::validate_placement`]
6853    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6854    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6855    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6856    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6857    /// declared-but-inert refusal's
6858    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6859    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6860    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6861    /// emit path the substrate operator's per-strategy fan-out reader
6862    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6863    /// materializer's per-strategy admission-webhook resolver).
6864    ///
6865    /// Prior to this lift the `.estrategia` field was accessed inline at
6866    /// four sites — the [`AplicacaoSpec::validate_placement`]
6867    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6868    /// `estrategia: self.placement.estrategia`, the same method's
6869    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6870    /// partition dispatch, the non-`Sharded`-arm
6871    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6872    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6873    /// per-Aplicacao strategy print line at
6874    /// `println!("… {} …", spec.placement.estrategia, …)`
6875    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6876    /// expressed no compile-time link back to the typed slot. A future
6877    /// extension of the `:placement :estrategia` axis to a richer author
6878    /// surface (a per-cluster override the operator pins through a future
6879    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6880    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6881    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6882    /// derivation the future adaptive placement engine computes from
6883    /// `:affinity` + `:clusters` topology) would have had to be threaded
6884    /// through every open-coded copy in lockstep — one consumer reading
6885    /// the raw variant while a peer read the operator-resolved variant
6886    /// would silently split the `PlacementWithoutClusters` /
6887    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6888    /// partition-dispatch input, a two-consumer split at the validator
6889    /// far from the source `caixa.lisp` with no field naming the
6890    /// strategy-drift root cause. Lifting the resolution rule to a typed
6891    /// method on the substrate primitive means every downstream consumer
6892    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6893    /// reaches for exactly one typed dispatch — the resolver's accept-set
6894    /// migrates as a unit on any future axis addition.
6895    ///
6896    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6897    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6898    /// same "one typed dispatch on the substrate primitive, thin
6899    /// projections at each consumer" discipline extended onto the
6900    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6901    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6902    /// family; first `Copy`-return accessor on the M3 mesh-slot
6903    /// `Placement` type — companion to the sibling per-`:placement`
6904    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6905    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6906    /// optional-scalar axes, closing the last unlifted per-`:placement`
6907    /// scalar-value axis (the closed-set `PlacementStrategy`
6908    /// distribution-strategy discriminator) so every downstream
6909    /// per-`:placement` reader now routes through a typed dispatch on
6910    /// the substrate primitive. Named `estrategia()` to match the storage
6911    /// field's name; the accessor's identity name maps onto the
6912    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6913    /// already carries. Declared `pub const fn` (matching the peer M3
6914    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6915    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6916    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6917    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6918    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6919    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6920    /// [`RateLimit`] — every one a `pub const fn`) so every future
6921    /// substrate-side `const`-context consumer of the resolved
6922    /// distribution-strategy variant (a `const _: () = assert!(…)`
6923    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6924    /// a future M4 admission-webhook `const fn` resolver over a typed
6925    /// [`Placement`], any `const fn` composer that fans on the strategy
6926    /// at compile time) reaches through the same typed dispatch on the
6927    /// substrate primitive at const-eval time as at runtime. Pinned by
6928    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6929    /// const-eval posture at module scope via `const _:() = …` items so
6930    /// any future accidental downgrade to non-`const` trips at caixa-core
6931    /// build time.
6932    #[must_use]
6933    pub const fn estrategia(&self) -> PlacementStrategy {
6934        self.estrategia
6935    }
6936
6937    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6938    /// per-cluster distribution-target slice accessor every consumer that
6939    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6940    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6941    /// `&[String]` slice-view, borrowed from the typed slot's own
6942    /// `Vec<String>` storage (a zero-copy slice-view over the same
6943    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6944    /// through). Non-optional: the empty slice is the load-bearing
6945    /// pre-validation sentinel every downstream consumer of the paired
6946    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6947    /// off — every strategy in the closed
6948    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6949    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6950    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6951    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6952    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6953    /// `.is_empty()` probe is the shared pre-condition every
6954    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6955    ///
6956    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6957    /// 1123-label per-cluster distribution-target list — the same
6958    /// set-not-multiset shape the sibling `:membros :caixa` /
6959    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6960    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6961    /// pins the shape). Every downstream consumer that fans on the list
6962    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6963    /// pre-flight `.is_empty()` probe that trips
6964    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6965    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6966    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6967    /// that materializes the list verbatim onto every
6968    /// programs.yaml entry the substrate operator's per-cluster
6969    /// `placement.clusters | contains .Values.cluster` filter reads,
6970    /// the `feira app graph` per-Aplicacao cluster print line, the
6971    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6972    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6973    /// placement engine's cluster-topology reader).
6974    ///
6975    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6976    /// inline at three production sites — the
6977    /// [`AplicacaoSpec::validate_placement`] pre-flight
6978    /// `self.placement.clusters.is_empty()` refusal probe, the same
6979    /// method's per-cluster validate loop's
6980    /// `for c in &self.placement.clusters` traversal head, and the
6981    /// `feira app graph` per-Aplicacao print line's
6982    /// `spec.placement.clusters` `{:?}` formatter argument
6983    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6984    /// that expressed no compile-time link back to the typed slot. A
6985    /// future extension of the `:placement :clusters` axis to a richer
6986    /// author surface (a per-tenant cluster-pool overlay the operator
6987    /// pins through a future `:placement :clusters-overrides` slot the
6988    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6989    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6990    /// the future M5 adaptive-placement engine computes from
6991    /// `:affinity` weights + live cluster-topology probes, a promotion
6992    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6993    /// partition once the substrate operator's cluster-membership
6994    /// reconciler comes into typed scope) would have had to be threaded
6995    /// through all three open-coded copies in lockstep or one consumer
6996    /// would silently disagree with the peers on which cluster-pool a
6997    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6998    /// reading the raw slot while the peer per-cluster validate loop
6999    /// read an operator-resolved slot would silently split the paired
7000    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
7001    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
7002    /// input from the pre-flight input, a three-consumer split at the
7003    /// validator and formatter far from the source `caixa.lisp` with
7004    /// no field naming the cluster-pool-drift root cause. Lifting the
7005    /// resolution rule to a typed method on the substrate primitive
7006    /// means every downstream consumer of the Aplicacao's
7007    /// per-`:placement` cluster-pool surface reaches for exactly one
7008    /// typed dispatch — the resolver's accept-set migrates as a unit
7009    /// on any future axis addition.
7010    ///
7011    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
7012    /// slot — sibling to the seed M2
7013    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
7014    /// slice-return accessor on the peer per-`:supervisor` static-
7015    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
7016    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
7017    /// primitive, thin projections at each consumer" discipline. The
7018    /// three peer `Vec`-carry axes still unlifted at the time of this
7019    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
7020    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
7021    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
7022    /// [`crate::UpgradeFromEntry::instructions`]
7023    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7024    /// — inherit this accessor's discipline as future compounding runs
7025    /// migrate their consumers onto the shared slice-return shape.
7026    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
7027    /// type, sibling to the two `Option<&str>`-return
7028    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
7029    /// (74ec2d3) accessors and the `Copy`-return
7030    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
7031    /// unlifted per-`:placement` field axis (the `Vec<String>`
7032    /// distribution-target-list carrier) so every downstream
7033    /// per-`:placement` reader now routes through a typed dispatch on
7034    /// the substrate primitive. Named `clusters()` to match the storage
7035    /// field's name verbatim and the tatara-lisp author-surface term
7036    /// (`:clusters`) the field's own docstring already carries; the
7037    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7038    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
7039    /// for. Returns `&[String]` (not `&Vec<String>`) because every
7040    /// downstream consumer of the cluster list treats it as a read-only
7041    /// sequence — the slice-view is the narrowest borrow that supports
7042    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
7043    /// `.len()`) without leaking the backing `Vec`'s
7044    /// grow/push/reserve surface that no consumer of the typed view
7045    /// reaches for (the storage-side `Vec` remains reachable through
7046    /// the `pub clusters` field for the mutation-carrying serde
7047    /// round-trip and per-test fixture-mutation paths).
7048    #[must_use]
7049    pub const fn clusters(&self) -> &[String] {
7050        self.clusters.as_slice()
7051    }
7052}
7053
7054impl Default for Placement {
7055    fn default() -> Self {
7056        Self {
7057            // Route the struct-literal `estrategia` default arm through
7058            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
7059            // typed `pub const` rather than the transitively-derived
7060            // [`PlacementStrategy::default`] route — one source of truth
7061            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
7062            // active-active-across-every-named-cluster arm
7063            // (MESH-COMPOSITION §II.2) that both this struct-literal
7064            // altitude and the sibling [`Default for PlacementStrategy`]
7065            // impl already key off through the same substrate primitive.
7066            // Pinned by
7067            // `placement_default_estrategia_routes_through_lifted_default`.
7068            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
7069            clusters: Vec::new(),
7070            affinity: None,
7071            shard_key: None,
7072        }
7073    }
7074}
7075
7076// ── external entry point ─────────────────────────────────────────────
7077
7078/// External entry point — what an outside caller sees. Renders to a
7079/// Gateway / Ingress + a route to the named member Servico.
7080#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7081#[serde(rename_all = "camelCase")]
7082pub struct Entrada {
7083    /// Public hostname (e.g. `"checkout.quero.cloud"`).
7084    pub host: String,
7085
7086    /// Member Servico the gateway routes to. Must be in `:membros`.
7087    pub para: String,
7088
7089    /// Optional path filter — if set, only matching paths route to
7090    /// this Aplicacao (the rest fall through to other route rules).
7091    #[serde(default)]
7092    pub paths: Vec<String>,
7093
7094    /// Default port on the destination Servico (the trigger.service.port).
7095    #[serde(default = "default_port")]
7096    pub port: u16,
7097}
7098
7099impl Entrada {
7100    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
7101    /// every HTTPRoute-aware renderer keys off — returns the author-
7102    /// declared `:entrada :paths` list verbatim when non-empty, and the
7103    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
7104    /// all fallback otherwise (so an Aplicacao author who declares an
7105    /// external `:entrada` block but no per-path rule surface still
7106    /// gets a route whose sole `HTTPPathMatch` matches every incoming
7107    /// request under the paired
7108    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
7109    ///
7110    /// Prior to this lift the "if `:entrada :paths` is empty use the
7111    /// substrate catch-all; else return each declared path verbatim"
7112    /// cascade lived inline at
7113    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
7114    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
7115    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
7116    /// substrate ships today, with no typed method on the substrate
7117    /// primitive that named the rule. A future path-resolution axis
7118    /// addition — a per-cluster `:entrada :default-path` override the
7119    /// operator pins through a future `:placement`-scoped slot, an
7120    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7121    /// admission-webhook floor that materializes the catch-all before
7122    /// the CR lands, a future per-`:entrada :paths` overlay from a
7123    /// per-cluster policy the future `feira app deploy` pipeline
7124    /// consumes — would have to be threaded through every renderer's
7125    /// inline copy of the cascade in lockstep or one consumer would
7126    /// silently disagree with the peers on which path list a given
7127    /// `:entrada` block resolves to. Lifting the rule to a typed
7128    /// method on the substrate primitive means every downstream
7129    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
7130    /// per-cluster overlay resolver, every future per-Aplicacao
7131    /// snapshot renderer) reaches for exactly one typed dispatch —
7132    /// the resolver's accept-set moves as a unit on any future axis
7133    /// addition.
7134    ///
7135    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
7136    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
7137    /// per-`:entrada` scalar-value axes — extends the "one typed
7138    /// dispatch on the substrate primitive, thin projections at each
7139    /// consumer" discipline onto the per-`:entrada` path-list
7140    /// resolution axis every HTTPRoute-aware renderer consumes. Same
7141    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
7142    /// sibling `:politicas` primitive — one typed method on the
7143    /// substrate primitive that names the cascade every renderer
7144    /// otherwise re-inlines.
7145    #[must_use]
7146    pub fn resolved_paths(&self) -> Vec<&str> {
7147        // Route the internal cascade-head + per-entry projection reads
7148        // through the lifted [`Self::paths`] slice accessor rather than
7149        // the raw `self.paths` field access — the substrate-primitive
7150        // per-`:entrada` path-list resolver's two internal reads now
7151        // key off the canonical raw-slot surface every downstream
7152        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
7153        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
7154        // entrada summary line's `{:?}` Debug print) routes through, so
7155        // any future rebrand on the typed slot's raw-slot reader lands
7156        // at exactly one place. Same two-consumer coherence discipline
7157        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
7158        // the peer M3 mesh-slot `Vec<String>`-carry axis.
7159        if self.paths().is_empty() {
7160            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
7161        } else {
7162            self.paths().iter().map(String::as_str).collect()
7163        }
7164    }
7165
7166    /// Substrate-canonical per-`:entrada` DNS-hostname singular
7167    /// accessor every Gateway-API `Listener.hostname` reader keys off
7168    /// — returns the author-declared `:entrada :host` byte-string
7169    /// verbatim as a `&str`, borrowed from the typed slot's own
7170    /// [`String`] storage.
7171    ///
7172    /// Named the "singular" half of the DNS-hostname resolver pair on
7173    /// the substrate primitive: the parent-Gateway per-listener
7174    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
7175    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
7176    /// hostname per listener), and this accessor is the typed dispatch
7177    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
7178    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
7179    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
7180    /// per-Aplicacao ingress-hostname surface projects onto.
7181    ///
7182    /// Prior to this lift the `entrada.host.clone()` byte-string was
7183    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
7184    /// per-listener singular `hostname:` axis
7185    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
7186    /// per-HTTPRoute plural `spec.hostnames[]` axis
7187    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
7188    /// consumers read the same `entrada.host` field but the two-site
7189    /// duplication expressed no compile-time contract that the singular
7190    /// Gateway-listener filter and the plural `HTTPRoute` filter list
7191    /// stay in lockstep on future extensions of the `:entrada` slot to
7192    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
7193    /// overlay, a per-cluster SNI fan-out the operator pins through a
7194    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
7195    /// Aplicacao` CR materializer's per-listener virtual-host filter
7196    /// admission-webhook overlay). Any such extension would have to be
7197    /// threaded through every renderer's inline copy of the resolution
7198    /// in lockstep or the Gateway listener's `hostname:` filter would
7199    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
7200    /// — a Gateway-API-conformance divergence whose apply-time symptom
7201    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
7202    /// `NoMatchingParent` — the API server rejects the route because
7203    /// its `hostnames[]` filter doesn't intersect the parent listener's
7204    /// `hostname` filter) is far from the source `caixa.lisp` and never
7205    /// surfaces in the emitted YAML. Lifting the singular and plural
7206    /// resolvers to typed methods on the substrate primitive means
7207    /// every consumer of the Aplicacao's ingress-hostname surface
7208    /// reaches for exactly one typed dispatch, and the pair-invariant
7209    /// `hostnames() == vec![hostname()]` pinned by the sibling
7210    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
7211    /// keeps the two axes in lockstep by construction.
7212    ///
7213    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
7214    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
7215    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
7216    /// the substrate primitive, thin projections at each consumer"
7217    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
7218    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
7219    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
7220    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
7221    /// `:entrada` scalar-value + list-value axes.
7222    #[must_use]
7223    pub const fn hostname(&self) -> &str {
7224        self.host.as_str()
7225    }
7226
7227    /// Substrate-canonical per-`:entrada` DNS-hostname plural
7228    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
7229    /// keys off — returns the singleton `[hostname()]` list under
7230    /// today's single-hostname-per-Aplicacao author surface, and the
7231    /// authoritative multi-hostname list under a future
7232    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
7233    ///
7234    /// Plural half of the DNS-hostname resolver pair — see the
7235    /// companion [`Entrada::hostname`] docstring for the two-consumer
7236    /// lift + pair-invariant discipline (`hostnames() ==
7237    /// vec![hostname()]`, pinned load-bearing by the sibling
7238    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
7239    /// test).
7240    ///
7241    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
7242    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
7243    /// per-rule path-list axis — same `Vec<&str>` shape, same
7244    /// substrate-primitive-owns-the-resolver discipline extended to
7245    /// the per-HTTPRoute virtual-host filter-list axis.
7246    #[must_use]
7247    pub fn hostnames(&self) -> Vec<&str> {
7248        vec![self.hostname()]
7249    }
7250
7251    /// Substrate-canonical per-`:entrada` destination-Servico scalar
7252    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
7253    /// the author-declared `:entrada :para` byte-string verbatim as a
7254    /// `&str`, borrowed from the typed slot's own [`String`] storage.
7255    ///
7256    /// The `:entrada :para` slot names the single member Servico the
7257    /// external Gateway routes to (validated by
7258    /// [`AplicacaoSpec::validate`] to be a
7259    /// [`Membro::caixa`] the Aplicacao declares — a stray
7260    /// `:para` that doesn't name a member is
7261    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
7262    /// backend-attachment miss at cluster-apply time). Under today's
7263    /// single-destination author surface `:entrada :para` is the ingress
7264    /// apex Servico's canonical identity; under a hypothetical
7265    /// future multi-backend author surface (a `:entrada
7266    /// :split :backends` weighted-fan-out overlay for canary /
7267    /// blue-green traffic-split rollouts, per-path override for
7268    /// path-based per-Servico routing beyond the single-apex model,
7269    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7270    /// per-CR admission-webhook that promotes the scalar to a
7271    /// weighted list) this accessor is the substrate primitive's typed
7272    /// dispatch every downstream `HTTPRoute`-aware consumer routes
7273    /// through, so the resolution shape migrates as a unit on one
7274    /// caixa-core edit rather than a coordinated rewrite across every
7275    /// renderer's inline field-access.
7276    ///
7277    /// Prior to this lift the `entrada.para` byte-string was accessed
7278    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
7279    /// `metadata.name` composer's per-destination discriminator arg
7280    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
7281    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
7282    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
7283    /// (`entrada.para.clone()`,
7284    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
7285    /// consumers read the same `entrada.para` field but the two-site
7286    /// duplication expressed no compile-time contract that the HTTPRoute
7287    /// name-discriminator and the per-rule backend name stay in
7288    /// lockstep on future extensions of the `:entrada` slot to a
7289    /// multi-destination author surface. Any such extension would have
7290    /// to be threaded through every renderer's inline copy of the
7291    /// destination projection in lockstep or the HTTPRoute
7292    /// `metadata.name` would silently reference a different destination
7293    /// than its own `backendRefs[]` — an operator-side
7294    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
7295    /// grep-by-name lookup would land on a route whose `backendRefs[]`
7296    /// silently point at a peer Servico, dropping every external
7297    /// `:entrada` flow at the gateway with the destination-drift root
7298    /// cause invisible in the emitted YAML.
7299    ///
7300    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
7301    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
7302    /// the per-listener singular / per-HTTPRoute plural filter axes and
7303    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
7304    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
7305    /// typed dispatch on the substrate primitive, thin projections at
7306    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
7307    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
7308    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
7309    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
7310    /// sibling per-`:entrada` scalar-value + list-value axes — this
7311    /// accessor closes the last unlifted per-`:entrada` scalar axis
7312    /// (the destination-Servico byte-string) so every downstream
7313    /// per-`:entrada` reader now routes through a typed dispatch on
7314    /// the substrate primitive.
7315    #[must_use]
7316    pub const fn destination(&self) -> &str {
7317        self.para.as_str()
7318    }
7319
7320    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
7321    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
7322    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
7323    /// reader keys off — returns the author-declared `:entrada :port`
7324    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
7325    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
7326    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
7327    /// [`AplicacaoError::EntradaPortZero`], not a silent
7328    /// admission-webhook rejection at cluster-apply time).
7329    ///
7330    /// The `:entrada :port` slot carries the destination Servico's
7331    /// canonical in-cluster L4 listener port (`trigger.service.port` on
7332    /// the `pleme-computeunit` library chart), and every downstream
7333    /// consumer that reads the port keys off this scalar (the
7334    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
7335    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
7336    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
7337    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7338    /// CR materializer's per-Aplicacao gateway port resolver).
7339    ///
7340    /// Prior to this lift the `.port` field was accessed inline at two
7341    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
7342    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
7343    /// the [`AplicacaoSpec::port_for_destination`] resolver's
7344    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
7345    /// open-coded field-accesses that expressed no compile-time link
7346    /// back to the typed slot. A future extension of the `:entrada :port`
7347    /// axis to a richer author surface — a per-cluster override the
7348    /// operator pins through a future `:placement :default-port` slot the
7349    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
7350    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
7351    /// heterogeneous listener ports, an M4
7352    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7353    /// admission-webhook floor that promotes the scalar to a
7354    /// per-destination map — would have had to be threaded through both
7355    /// open-coded copies in lockstep or the structural-floor validator
7356    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
7357    /// silently disagree on which port a given [`Entrada`] resolves to.
7358    /// Lifting the resolution rule to a typed method on the substrate
7359    /// primitive means every downstream consumer of the Aplicacao's
7360    /// per-`:entrada` L4-port surface reaches for exactly one typed
7361    /// dispatch — the resolver's accept-set migrates as a unit on any
7362    /// future axis addition.
7363    ///
7364    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
7365    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
7366    /// accessors on the per-`:entrada` scalar-value axis — same "one
7367    /// typed dispatch on the substrate primitive, thin projections at
7368    /// each consumer" discipline extended onto the per-`:entrada`
7369    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
7370    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
7371    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
7372    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
7373    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
7374    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
7375    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
7376    /// storage field's name; the accessor's identity name maps onto the
7377    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
7378    /// already carries. Declared `pub const fn` (matching the peer M3
7379    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
7380    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
7381    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
7382    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
7383    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
7384    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
7385    /// [`RateLimit`], and the sibling per-`:placement`
7386    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
7387    /// enum scalar axis — every one a `pub const fn`) so every future
7388    /// substrate-side `const`-context consumer of the resolved
7389    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
7390    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
7391    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
7392    /// admission-webhook `const fn` per-CR gateway-port floor over a
7393    /// typed [`Entrada`], any `const fn` composer that fans on the port
7394    /// at compile time) reaches through the same typed dispatch on the
7395    /// substrate primitive at const-eval time as at runtime. Pinned by
7396    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
7397    /// const-eval posture at module scope via `const _:() = …` items so
7398    /// any future accidental downgrade to non-`const` trips at caixa-core
7399    /// build time.
7400    #[must_use]
7401    pub const fn port(&self) -> u16 {
7402        self.port
7403    }
7404
7405    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
7406    /// slice accessor every HTTPRoute-aware renderer keys off when it
7407    /// wants the raw author-declared path-list (not the fallback-
7408    /// applied projection [`Self::resolved_paths`] returns) — returns
7409    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
7410    /// borrowed from the typed slot's own [`Vec<String>`] storage.
7411    ///
7412    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
7413    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
7414    /// (1449891) closes the fallback-applying arm every per-Aplicacao
7415    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
7416    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
7417    /// catch-all; non-empty slot → per-entry verbatim projection); this
7418    /// accessor closes the raw-slot arm every consumer that must see the
7419    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
7420    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
7421    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
7422    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
7423    /// external-gateway summary line's `{:?}` Debug print — which must
7424    /// name the author's declaration, not the substrate's fallback, so
7425    /// an author reading their graph output can grep their caixa.lisp
7426    /// for the exact list they authored) routes through.
7427    ///
7428    /// Prior to this lift the `.paths` field was accessed inline at four
7429    /// production sites: the two internal reads in [`Self::resolved_paths`]
7430    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
7431    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
7432    /// value-shape gate's `for p in &e.paths` traversal head, and the
7433    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
7434    /// Debug print — four open-coded field-accesses that expressed no
7435    /// compile-time link back to the typed slot. A future extension of
7436    /// the `:entrada :paths` axis to a richer author surface — a
7437    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
7438    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
7439    /// spec supports through `matches[].method`), a per-path per-header
7440    /// filter overlay (`matches[].headers[]`), a per-cluster override
7441    /// the operator pins through a future `:placement :path-overlay`
7442    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7443    /// per-CR admission-webhook that normalized the list at admission
7444    /// time — would have had to be threaded through every open-coded
7445    /// copy in lockstep or the validator's per-entry gate would silently
7446    /// disagree with the renderer's per-entry emit on which list a given
7447    /// `:entrada` block resolves to. Lifting the resolution to a typed
7448    /// method on the substrate primitive means every downstream consumer
7449    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
7450    /// exactly one typed dispatch — the resolver's accept-set migrates
7451    /// as a unit on any future axis addition.
7452    ///
7453    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
7454    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
7455    /// carry axis — same "one typed dispatch on the substrate primitive,
7456    /// thin projections at each consumer" discipline extended onto the
7457    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
7458    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
7459    /// carrier) so every downstream per-`:entrada` reader now routes
7460    /// through a typed dispatch on the substrate primitive. Returns
7461    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
7462    /// treats the list as a read-only sequence — the slice-view is the
7463    /// narrowest borrow that supports every present + roadmapped consumer
7464    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
7465    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
7466    /// view reaches for (the storage-side `Vec` remains reachable through
7467    /// the `pub paths` field for the mutation-carrying serde round-trip
7468    /// and per-test fixture-mutation paths).
7469    #[must_use]
7470    pub const fn paths(&self) -> &[String] {
7471        self.paths.as_slice()
7472    }
7473}
7474
7475/// Canonical default L4 port every typed Servico exposes on its
7476/// in-cluster K8s Service (the `trigger.service.port` axis the
7477/// `pleme-computeunit` library chart emits, the `:entrada :port` author
7478/// surface defaults to when the author omits the slot, and the
7479/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
7480/// `:entrada` block matches the per-`:contratos` destination Servico).
7481/// The single source of truth all three typed-port consumers reach for:
7482///
7483///   - [`Entrada::port`]'s serde default (via the
7484///     [`default_port`] helper this constant feeds); the author surface
7485///     `(:entrada (:host … :para …))` without an explicit `:port` slot
7486///     reads back as a typed [`Entrada`] carrying this exact value;
7487///   - the
7488///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
7489///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
7490///     fallback, fired when the typed `:entrada` block doesn't name
7491///     the per-`:contratos` destination Servico — the typed
7492///     `:contratos` graph carries no per-destination port axis (the
7493///     destination port is the destination Servico's
7494///     `lareira-<nome>` chart's `trigger.service.port`, which the
7495///     Aplicacao-level renderer has no visibility into without a
7496///     resolver round-trip), so the renderer falls back to the
7497///     substrate's canonical Servico-port assumption — by
7498///     construction the same value the destination's own
7499///     `pleme-computeunit` chart emits, the same value the
7500///     destination's own typed `:entrada :port` slot defaults to;
7501///   - every future per-Servico renderer the absorption-roadmap
7502///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7503///     CR materializer's per-edge port resolver, the future
7504///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
7505///     emitter's per-route bucket key, the future caixa-otel
7506///     collector-pipeline emitter's per-Servico scrape port).
7507///
7508/// Until this lift landed the value `8080` lived at two production-code
7509/// call-sites: the [`default_port`] helper at
7510/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
7511/// and the `.unwrap_or(8080)` literal at
7512/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
7513/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
7514/// resolver). A future Servico-port rebrand — the substrate moving the
7515/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
7516/// gateway grows direct `:80` listeners, to `8443` once the substrate
7517/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
7518/// override the operator pins through a future
7519/// `:placement :default-port` slot — without a coordinated edit on
7520/// both sides would silently emit Servicos listening on one port and
7521/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
7522/// The CNP's apply-time symptom (the policy is admitted but every L4
7523/// flow on the destination Servico's actual port silently drops because
7524/// it doesn't match the whitelisted port) is far from the rebrand
7525/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
7526/// in hubble traces, not in `kubectl describe`. Lifting the literal to
7527/// a shared constant closes the drift footgun structurally — both
7528/// consumers read from the same `u16`, so any rebrand reaches both
7529/// sites by construction.
7530///
7531/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
7532/// per-renderer canonical-K8s-axis constant — the namespace string
7533/// and the canonical Servico port both lived as duplicated literals
7534/// across caixa-core / caixa-mesh / caixa-flux before their respective
7535/// lifts. Same "the typed constant lives in one place" discipline the
7536/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
7537/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
7538/// shared-string axes.
7539///
7540/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
7541pub const DEFAULT_SERVICO_PORT: u16 = 8080;
7542
7543/// Structural floor for the typed `:entrada :port` axis — every
7544/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
7545/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
7546///
7547/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
7548/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
7549/// interprets as "let the kernel pick a free port at bind time", not a
7550/// well-defined destination the substrate's per-`:entrada` Gateway API
7551/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
7552/// carrying `port: 0` degenerates to a nominal-only routing target: the
7553/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
7554/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
7555/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
7556/// at build time rather than at `kubectl apply` time), and the
7557/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
7558/// (caixa-mesh/src/lib.rs:2657 through
7559/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
7560/// [`Entrada::port`] typed value — silently emits a policy whose
7561/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
7562/// actual listener, dropping every L4 flow at the eBPF data plane far
7563/// from the source caixa.lisp with no field naming the port-zero-drift
7564/// root cause.
7565///
7566/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
7567/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
7568/// on the top edge (unlike the peer capped-`u32` `:politicas` /
7569/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
7570/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
7571/// well below `u32::MAX` and therefore need explicit typed caps).
7572///
7573/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
7574/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
7575/// scalar every `(:entrada (:host … :para …))` slot without an explicit
7576/// `:port` inherits through the serde default hook; this constant names
7577/// the accept-set floor every declared port must satisfy. The pair is
7578/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
7579/// substrate's default must satisfy its own accept-set floor by
7580/// construction) — a future rebrand that accidentally moved
7581/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
7582/// negative-cast typo, a per-cluster override the operator pins through
7583/// a future `:placement :default-port` slot that lands out-of-range)
7584/// would silently invalidate the serde-default emission at every
7585/// author-side `(:entrada (:host … :para …))` slot — the compile-time
7586/// invariant pin
7587/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
7588/// closes the drift footgun at caixa-core build time.
7589///
7590/// Lifted as a typed `pub const` (rather than an inline `0` literal at
7591/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
7592/// has exactly one source of truth — the future M4
7593/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
7594/// gateway resolver, the future per-Servico
7595/// `computeunit.trigger.service.port` renderer's per-CR port-value
7596/// validator, and every downstream test-fixture navigator asserting
7597/// the accept-set floor all read from one place. Same shape every
7598/// other typed bracket-floor / bracket-ceiling in this crate carries
7599/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
7600/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
7601/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
7602/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
7603/// [`POLICY_RATE_LIMIT_MAX`]).
7604pub const SERVICO_PORT_MIN: u16 = 1;
7605
7606const fn default_port() -> u16 {
7607    DEFAULT_SERVICO_PORT
7608}
7609
7610// ── the typed view ───────────────────────────────────────────────────
7611
7612/// Typed composition view of the flat Aplicacao slots on
7613/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
7614/// validation + downstream renderer consumption.
7615#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7616#[serde(rename_all = "camelCase")]
7617pub struct AplicacaoSpec {
7618    pub membros: Vec<Membro>,
7619    pub contratos: Vec<WitContract>,
7620    pub politicas: MeshPolicy,
7621    pub placement: Placement,
7622    pub entrada: Option<Entrada>,
7623}
7624
7625impl AplicacaoSpec {
7626    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
7627    /// per-Aplicacao member-list slice-return accessor every
7628    /// per-Aplicacao member-list reader keys off — returns the author-
7629    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
7630    /// over the same backing buffer the raw `self.membros.as_slice()`
7631    /// field access borrows from.
7632    ///
7633    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
7634    /// member list — the load-bearing identity of the application graph
7635    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
7636    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
7637    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
7638    /// accessor) with a `:versao` semver-requirement string (through
7639    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
7640    /// and every downstream consumer that fans on the member-set keys
7641    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
7642    /// membership-lookup `HashSet<&str>` seed's collect input, the
7643    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
7644    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
7645    /// per-member DNS-1123 / semver-requirement / duplicate-detection
7646    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
7647    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
7648    /// programs.yaml per-`:membros` fan-out emitter's per-entry
7649    /// mapping-composition loop, the `feira app graph` per-Aplicacao
7650    /// member-count print line and per-member tree traversal,
7651    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
7652    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
7653    /// placement engine's per-member weight-topology reader).
7654    ///
7655    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
7656    /// inline at six production sites — the [`AplicacaoSpec::validate`]
7657    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7658    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7659    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7660    /// probe, the same method's per-member `for m in &self.membros`
7661    /// validate-loop traversal head, the
7662    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7663    /// `for m in &self.membros` adjacency-list seed, the
7664    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7665    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7666    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7667    /// loop, and the `feira app graph` per-Aplicacao print line's
7668    /// `spec.membros.len()` count formatter argument paired with the
7669    /// peer `for m in &spec.membros` per-member tree traversal — six
7670    /// open-coded field-accesses that expressed no compile-time link
7671    /// back to the typed slot. A future extension of the `:membros`
7672    /// axis to a richer author surface (a per-cluster member-set
7673    /// overlay the operator pins through a future
7674    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7675    /// roadmap acknowledges, a per-tenant member-alias table the M4
7676    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7677    /// CR at admission time, a per-Aplicacao dynamic member-set
7678    /// derivation the future adaptive-placement engine computes from
7679    /// weighted membership topology, a promotion of the plain
7680    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7681    /// Orleans-style virtual-actor dynamic-membership comes into typed
7682    /// scope) would have had to be threaded through all six open-coded
7683    /// copies in lockstep or one consumer would silently disagree with
7684    /// the peers on which member-set a given Aplicacao resolves to —
7685    /// the `HashSet<&str>` name-set seed reading the raw slot while
7686    /// the peer `.is_empty()` refusal probe read an operator-resolved
7687    /// slot would silently split the `:contratos` membership-lookup
7688    /// input from the pre-flight-refusal input, a six-consumer split
7689    /// at the validator + programs.yaml emitter + graph printer far
7690    /// from the source `caixa.lisp` with no field naming the member-
7691    /// set-drift root cause. Lifting the resolution rule to a typed
7692    /// method on the substrate primitive means every downstream
7693    /// consumer of the Aplicacao's per-`:membros` member-list surface
7694    /// reaches for exactly one typed dispatch — the resolver's accept-
7695    /// set migrates as a unit on any future axis addition.
7696    ///
7697    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7698    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7699    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7700    /// static-child-list `Vec`-carry axis, and to the M3
7701    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7702    /// on the peer per-`:placement` distribution-target-list `Vec`-
7703    /// carry axis. Same "one typed dispatch on the substrate primitive,
7704    /// thin projections at each consumer" discipline. The two peer
7705    /// `Vec`-carry axes still unlifted at the time of this lift —
7706    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7707    /// WIT-typed edge list) and
7708    /// [`crate::UpgradeFromEntry::instructions`]
7709    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7710    /// — inherit this accessor's discipline as future compounding runs
7711    /// migrate their consumers onto the shared slice-return shape.
7712    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7713    /// `AplicacaoSpec` type itself, extending the discipline beyond
7714    /// the inner per-slot types ([`crate::Placement`],
7715    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7716    /// view every renderer consumes. Named `membros()` to match the
7717    /// storage field's name verbatim and the tatara-lisp author-
7718    /// surface term (`:membros`) the field's own docstring already
7719    /// carries; the accessor's identity maps onto the canonical
7720    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7721    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7722    /// every downstream consumer of the member list treats it as a
7723    /// read-only sequence — the slice-view is the narrowest borrow
7724    /// that supports every present + roadmapped consumer
7725    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7726    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7727    /// the typed view reaches for (the storage-side `Vec` remains
7728    /// reachable through the `pub membros` field for the mutation-
7729    /// carrying serde round-trip and per-test fixture-mutation paths).
7730    #[must_use]
7731    pub const fn membros(&self) -> &[Membro] {
7732        self.membros.as_slice()
7733    }
7734
7735    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7736    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7737    /// accessor every per-Aplicacao contract-list reader keys off —
7738    /// returns the author-declared `:contratos` list verbatim as a
7739    /// `&[WitContract]` slice-view over the same backing buffer the raw
7740    /// `self.contratos.as_slice()` field access borrows from.
7741    ///
7742    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7743    /// WIT-typed edge list — the load-bearing set of directed edges
7744    /// on the application graph whose nodes are the `:membros` entries
7745    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7746    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7747    /// six-tuple is the edge identity every downstream duplicate gate
7748    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7749    /// Servico caller name + a `:para` destination-Servico callee name
7750    /// (through the lifted [`WitContract::source`] +
7751    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7752    /// caller/callee-Servico axis) with a `:wit` world-reference
7753    /// (through the lifted [`WitContract::world_ref`] (0804823)
7754    /// accessor) and the target-shape-appropriate payload-carrier
7755    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7756    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7757    /// (ed22b66) accessor on the per-target-shape payload-carrier
7758    /// axis). Every downstream consumer that fans on the edge-set
7759    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7760    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7761    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7762    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7763    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7764    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7765    /// count print line and per-contract tree traversal, every future
7766    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7767    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7768    /// mesh-policy overlay resolver's per-contract typed-edge weight
7769    /// reader).
7770    ///
7771    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7772    /// accessed inline at four production sites — the
7773    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7774    /// per-edge validate-loop traversal head (which drives every
7775    /// per-edge name-set membership lookup, self-edge check,
7776    /// target-shape dispatch, and dedup `HashSet` insert), the
7777    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7778    /// `for c in &self.contratos` adjacency-list seed head (which
7779    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7780    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7781    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7782    /// `BTreeMap` grouping loop head (which drives every per-CNP
7783    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7784    /// line's `spec.contratos.len()` count formatter argument paired
7785    /// with the peer `for c in &spec.contratos` per-contract tree
7786    /// traversal — four open-coded field-accesses that expressed no
7787    /// compile-time link back to the typed slot. A future extension
7788    /// of the `:contratos` axis to a richer author surface (a
7789    /// per-cluster contract overlay the operator pins through a
7790    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7791    /// federation roadmap acknowledges, a per-tenant edge-policy
7792    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7793    /// materializer resolves per-CR at admission time, a per-edge
7794    /// weight scalar the future adaptive-placement engine reads to
7795    /// bias sync-subgraph routing, a promotion of the plain
7796    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7797    /// once virtual-actor-style dynamic-edge composition comes into
7798    /// typed scope) would have had to be threaded through all four
7799    /// open-coded copies in lockstep or one consumer would silently
7800    /// disagree with the peers on which edge-set a given Aplicacao
7801    /// resolves to — the validator's per-edge dedup `HashSet` seed
7802    /// reading the raw slot while the peer sync-cycle adjacency-list
7803    /// seed read an operator-resolved slot would silently split the
7804    /// build-time edge-set gate from the runtime deadlock-detection
7805    /// gate, a four-consumer split at the validator, the cycle
7806    /// detector, the CNP emitter, and the graph printer far from
7807    /// the source `caixa.lisp` with no field naming the edge-set-
7808    /// drift root cause. Lifting the resolution rule to a typed method on the
7809    /// substrate primitive means every downstream consumer of the
7810    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7811    /// exactly one typed dispatch — the resolver's accept-set
7812    /// migrates as a unit on any future axis addition.
7813    ///
7814    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7815    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7816    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7817    /// static-child-list `Vec`-carry axis, to the M3
7818    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7819    /// on the peer per-`:placement` distribution-target-list `Vec`-
7820    /// carry axis, and to the immediately-adjacent sibling M3
7821    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7822    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7823    /// per-`:contratos` edge-list accessor is the natural pair of
7824    /// the per-`:membros` node-list accessor (graph edges over graph
7825    /// nodes; every graph-shaped consumer reads both). Same "one
7826    /// typed dispatch on the substrate primitive, thin projections
7827    /// at each consumer" discipline. The last remaining `Vec`-carry
7828    /// axis still unlifted at the time of this lift —
7829    /// [`crate::UpgradeFromEntry::instructions`]
7830    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7831    /// list) — inherits this accessor's discipline as future
7832    /// compounding runs migrate its consumers onto the shared slice-
7833    /// return shape. Second `&[T]`-return accessor on the top-level
7834    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7835    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7836    /// `:contratos` are the two `Vec` fields on the outer typed
7837    /// composition view — `:politicas`, `:placement`, `:entrada` are
7838    /// scalar/option-shaped and already route through their per-slot
7839    /// accessor families). Named `contratos()` to match the storage
7840    /// field's name verbatim and the tatara-lisp author-surface term
7841    /// (`:contratos`) the field's own docstring already carries; the
7842    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7843    /// §III.1 vocabulary the slot's docstring already reaches for.
7844    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7845    /// every downstream consumer of the contract list treats it as a
7846    /// read-only sequence — the slice-view is the narrowest borrow
7847    /// that supports every present + roadmapped consumer
7848    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7849    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7850    /// the typed view reaches for (the storage-side `Vec` remains
7851    /// reachable through the `pub contratos` field for the mutation-
7852    /// carrying serde round-trip and per-test fixture-mutation paths).
7853    #[must_use]
7854    pub const fn contratos(&self) -> &[WitContract] {
7855        self.contratos.as_slice()
7856    }
7857
7858    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7859    /// per-Aplicacao mesh-policy composite-reference accessor every
7860    /// per-Aplicacao policy-block reader keys off — returns the author-
7861    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7862    /// reference over the same backing storage the raw `&self.politicas`
7863    /// field access borrows from.
7864    ///
7865    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7866    /// mesh-policy composite — the load-bearing container of every
7867    /// mesh-level operational-policy axis every downstream mesh-artifact
7868    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7869    /// mesh-policy overlay is the single typed surface a
7870    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7871    /// from). Every per-`:politicas` axis threads through a lifted
7872    /// per-slot accessor on the [`MeshPolicy`] type: the
7873    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7874    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7875    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7876    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7877    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7878    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7879    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7880    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7881    /// accessor. Every downstream consumer that reaches for a policy
7882    /// axis first passes through this outer accessor onto the composite
7883    /// and then dispatches onto the per-axis accessor — the two-level
7884    /// dispatch means every per-`:politicas` reader now routes through
7885    /// a typed dispatch on the substrate primitive at both altitudes.
7886    ///
7887    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7888    /// accessed inline at four production sites — the
7889    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7890    /// &self.politicas;` traversal seed (which drives every per-axis
7891    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7892    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7893    /// `p.rate_limit()` on the axis-level lifted accessors), the
7894    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7895    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7896    /// chain (which drives every per-`(:de, :para)` CNP
7897    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7898    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7899    /// timeout + retry overlay emitter's paired
7900    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7901    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7902    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7903    /// open-coded outer-field accesses that expressed no compile-time
7904    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7905    /// future extension of the `:politicas` outer axis to a richer
7906    /// author surface (a per-cluster policy overlay the operator pins
7907    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7908    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7909    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7910    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7911    /// policy-composite derivation the future adaptive-placement engine
7912    /// computes from a per-cluster load-topology reader, a promotion of
7913    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7914    /// partition once virtual-actor-style dynamic-mesh-policy
7915    /// composition comes into typed scope) would have had to be threaded
7916    /// through all four open-coded copies in lockstep or one consumer
7917    /// would silently disagree with the peers on which mesh-policy
7918    /// composite a given Aplicacao resolves to — the validator's
7919    /// per-axis bracket-dispatch seed reading the raw slot while the
7920    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7921    /// would silently split the build-time policy-shape gate from the
7922    /// runtime CNP-emission gate, a four-consumer split at the
7923    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7924    /// the source `caixa.lisp` with no field naming the policy-drift
7925    /// root cause. Lifting the resolution rule to a typed method on the
7926    /// substrate primitive means every downstream consumer of the
7927    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7928    /// reaches for exactly one typed dispatch — the resolver's accept-
7929    /// set migrates as a unit on any future axis addition.
7930    ///
7931    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7932    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7933    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7934    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7935    /// close the two `Vec`-carry axes on the outer typed composition
7936    /// view; the outer `:politicas` composite-reference axis is the
7937    /// natural pair to the paired outer `Vec`-carry accessors on the
7938    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7939    /// emitter reads all four axes as one unit (graph nodes + graph
7940    /// edges + mesh policy + placement pool). Peer to the same
7941    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7942    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7943    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7944    /// `restart_window`, `children`) already routes through the M2
7945    /// `SupervisorSpec` accessor family — this lift extends the same
7946    /// "one typed dispatch on the substrate primitive at the outer
7947    /// composition altitude" discipline to the M3 mesh-slot
7948    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7949    /// remaining peer outer-composite axes still unlifted at the time
7950    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7951    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7952    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7953    /// inherit this accessor's discipline as future compounding runs
7954    /// migrate their consumers onto the shared reference-return shape.
7955    /// Named `politicas()` to match the storage field's name verbatim
7956    /// and the tatara-lisp author-surface term (`:politicas`) the
7957    /// field's own docstring already carries; the accessor's identity
7958    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7959    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7960    /// (not the owning composite by copy or clone) because every
7961    /// downstream consumer of the mesh-policy composite treats it as a
7962    /// read-only per-axis dispatch source — the reference-view is the
7963    /// narrowest borrow that supports every present + roadmapped
7964    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7965    /// emptiness probe) without cloning the composite through every
7966    /// consumer's fast path.
7967    #[must_use]
7968    pub const fn politicas(&self) -> &MeshPolicy {
7969        &self.politicas
7970    }
7971
7972    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7973    /// per-Aplicacao distribution-composite composite-reference accessor
7974    /// every per-Aplicacao placement-block reader keys off — returns the
7975    /// author-declared `:placement` composite verbatim as a `&Placement`
7976    /// reference over the same backing storage the raw `&self.placement`
7977    /// field access borrows from.
7978    ///
7979    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7980    /// distribution composite — the load-bearing container of every
7981    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7982    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7983    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7984    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7985    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7986    /// `:affinity` hint). Every per-`:placement` axis threads through a
7987    /// lifted per-slot accessor on the [`Placement`] type: the
7988    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7989    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7990    /// per-cluster distribution-target slice-return accessor, the
7991    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7992    /// optional-scalar accessor, and the [`Placement::shard_key`]
7993    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7994    /// downstream consumer that reaches for a placement axis first passes
7995    /// through this outer accessor onto the composite and then dispatches
7996    /// onto the per-axis accessor — the two-level dispatch means every
7997    /// per-`:placement` reader now routes through a typed dispatch on the
7998    /// substrate primitive at both altitudes.
7999    ///
8000    /// Prior to this lift the `.placement` `Placement` composite was
8001    /// accessed inline at three production sites — the
8002    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
8003    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
8004    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
8005    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
8006    /// cluster `.clusters()` validate-loop traversal head, the per-
8007    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
8008    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
8009    /// paired with the shape-gate cascade's `.shard_key()` /
8010    /// `.estrategia()` diagnostic-carry pair), the
8011    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
8012    /// per-entry placement-block emitter's outer
8013    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
8014    /// seed (which fans onto every per-cluster `programs[]` entry as a
8015    /// self-describing distribution overlay the aggregator filters by),
8016    /// and the `feira app graph` per-Aplicacao print line's paired
8017    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
8018    /// then-inner-accessor chains (which drive the human-readable
8019    /// distribution summary of the typed Aplicacao view) — three open-
8020    /// coded outer-field accesses that expressed no compile-time link
8021    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
8022    /// extension of the `:placement` outer axis to a richer author surface
8023    /// (a per-cluster placement overlay the operator pins through a
8024    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
8025    /// federation roadmap acknowledges, a per-tenant placement-alias
8026    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
8027    /// resolves per-CR at admission time, a per-Aplicacao dynamic
8028    /// placement-composite derivation the future M5 adaptive-placement
8029    /// engine computes from a per-cluster load-topology reader, a
8030    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
8031    /// partition once Orleans-style virtual-actor dynamic-placement comes
8032    /// into typed scope) would have had to be threaded through all three
8033    /// open-coded copies in lockstep or one consumer would silently
8034    /// disagree with the peers on which placement composite a given
8035    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
8036    /// seed reading the raw slot while the peer
8037    /// `programs_for_aplicacao` emitter read an operator-resolved slot
8038    /// would silently split the build-time distribution-shape gate from
8039    /// the runtime programs.yaml distribution-annotation gate, a three-
8040    /// consumer split at the validator, the programs.yaml emitter, and
8041    /// the `feira app graph` printer far from the source `caixa.lisp`
8042    /// with no field naming the placement-drift root cause. Lifting the
8043    /// resolution rule to a typed method on the substrate primitive
8044    /// means every downstream consumer of the Aplicacao's per-
8045    /// `:placement` distribution composite surface reaches for exactly
8046    /// one typed dispatch — the resolver's accept-set migrates as a unit
8047    /// on any future axis addition.
8048    ///
8049    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
8050    /// `AplicacaoSpec` type itself — sibling to the seed
8051    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
8052    /// composite-reference accessor on the peer per-`:politicas` outer-
8053    /// composite axis, and to the paired slice-return accessors
8054    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
8055    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
8056    /// the two `Vec`-carry axes on the outer typed composition view; the
8057    /// outer `:placement` composite-reference axis is the natural pair
8058    /// to the peer `:politicas` composite-reference axis on the two
8059    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
8060    /// how-to-run policy overlay, `:placement` carries the where-to-run
8061    /// distribution composite — every whole-Aplicacao mesh-artifact
8062    /// emitter reads both as one unit). Same "one typed dispatch on the
8063    /// substrate primitive, thin projections at each consumer"
8064    /// discipline the peer per-`:politicas` composite-reference axis
8065    /// already routes through. The one remaining outer-composite axis
8066    /// still unlifted at the time of this lift —
8067    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
8068    /// external-gateway composite) — inherits this accessor's discipline
8069    /// as the next compounding run migrates its consumers onto the shared
8070    /// reference-return shape, closing the outer-composite altitude on
8071    /// every M3 mesh-slot axis. Named `placement()` to match the storage
8072    /// field's name verbatim and the tatara-lisp author-surface term
8073    /// (`:placement`) the field's own docstring already carries; the
8074    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
8075    /// vocabulary the slot's docstring already reaches for. Returns
8076    /// `&Placement` (not the owning composite by copy or clone) because
8077    /// every downstream consumer of the placement composite treats it as
8078    /// a read-only per-axis dispatch source — the reference-view is the
8079    /// narrowest borrow that supports every present + roadmapped consumer
8080    /// (per-axis accessor dispatch, serde composite-serialization) without
8081    /// cloning the composite through every consumer's fast path.
8082    #[must_use]
8083    pub const fn placement(&self) -> &Placement {
8084        &self.placement
8085    }
8086
8087    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
8088    /// per-Aplicacao external-gateway composite optional-composite-
8089    /// reference accessor every per-Aplicacao gateway-block reader
8090    /// keys off — returns the author-declared `:entrada` composite
8091    /// verbatim as an `Option<&Entrada>` reference over the same
8092    /// backing storage the raw `self.entrada.as_ref()` field access
8093    /// borrows from, with `None` naming the internal-only mesh shape
8094    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
8095    /// gateway_routes emitter treats as "emit nothing" and the peer
8096    /// `feira app graph` printer treats as "internal-only mesh").
8097    ///
8098    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
8099    /// external-gateway composite — the load-bearing container of
8100    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
8101    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
8102    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
8103    /// hostname axis, §III.4 for the `:para` destination-Servico
8104    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
8105    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
8106    /// axis threads through a lifted per-slot accessor on the
8107    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
8108    /// Gateway-API `Listener.hostname` scalar accessor, the paired
8109    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
8110    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
8111    /// backendRefs destination-Servico scalar accessor, the
8112    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
8113    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
8114    /// scalar accessor. Every downstream consumer that reaches for
8115    /// an entrada axis first passes through this outer accessor onto
8116    /// the composite and then dispatches onto the per-axis accessor
8117    /// — the two-level dispatch means every per-`:entrada` reader
8118    /// now routes through a typed dispatch on the substrate primitive
8119    /// at both altitudes.
8120    ///
8121    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
8122    /// was accessed inline at four production sites — the
8123    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
8124    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
8125    /// (which drives every per-axis refusal on the composite: the
8126    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
8127    /// `EntradaMemberMissing` membership lookup against the
8128    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
8129    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
8130    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
8131    /// per-path shape gate on each entry of `e.paths`), the
8132    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
8133    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
8134    /// composite-projection seed (which drives the destination-
8135    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
8136    /// backendRefs port emitter fans on), the
8137    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
8138    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
8139    /// early-return seed (which drives the "no `:entrada` ⇒ no
8140    /// external artifacts" partition on the whole-Aplicacao Gateway-
8141    /// API emitter's fan-out), and the `feira app graph` per-
8142    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
8143    /// external-gateway summary emitter (which drives the human-
8144    /// readable `entrada: host → para (paths=…, port=…)` /
8145    /// `entrada: (internal-only mesh)` partition on the typed
8146    /// Aplicacao view) — four open-coded outer-field accesses that
8147    /// expressed no compile-time link back to the typed slot at the
8148    /// [`AplicacaoSpec`] altitude. A future extension of the
8149    /// `:entrada` outer axis to a richer author surface (a
8150    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
8151    /// at admission time so an Aplicacao can expose a public-web +
8152    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
8153    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
8154    /// operator can pin a per-cluster hostname override without
8155    /// re-authoring the `caixa.lisp`, a promotion of the plain
8156    /// `Option<Entrada>` to a richer `{single, multi}` partition once
8157    /// the multi-`:entrada` roadmap lands) would have had to be
8158    /// threaded through all four open-coded copies in lockstep or one
8159    /// consumer would silently disagree with the peers on which
8160    /// entrada composite a given Aplicacao resolves to — the
8161    /// validator's per-axis bracket-dispatch seed reading the raw
8162    /// slot while the peer `gateway_routes` emitter read an
8163    /// operator-resolved slot would silently split the build-time
8164    /// gateway-shape gate from the runtime Gateway + HTTPRoute
8165    /// emission gate, a four-consumer split at the validator, the
8166    /// `port_for_destination` L4-port resolver, the `gateway_routes`
8167    /// emitter, and the `feira app graph` printer far from the
8168    /// source `caixa.lisp` with no field naming the entrada-drift
8169    /// root cause. Lifting the resolution rule to a typed method on
8170    /// the substrate primitive means every downstream consumer of
8171    /// the Aplicacao's per-`:entrada` external-gateway composite
8172    /// surface reaches for exactly one typed dispatch — the
8173    /// resolver's accept-set migrates as a unit on any future axis
8174    /// addition.
8175    ///
8176    /// Third and final `&Composite`-return accessor on the top-level
8177    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
8178    /// unlifted outer-composite axis on the outer typed composition
8179    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
8180    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
8181    /// accessor on the per-`:politicas` outer-composite axis and to
8182    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
8183    /// distribution-composite composite-reference accessor on the
8184    /// per-`:placement` outer-composite axis; extends the outer-
8185    /// composite reference-return discipline the two peers already
8186    /// route through onto the last unlifted per-`AplicacaoSpec`
8187    /// outer-composite axis. The `:entrada` outer-composite axis is
8188    /// the natural pair to the two peer outer-composite axes on the
8189    /// three operationally-symmetric M3 mesh-slot outer composites
8190    /// (`:politicas` carries the how-to-run policy overlay,
8191    /// `:placement` carries the where-to-run distribution composite,
8192    /// `:entrada` carries the who-can-reach-it external-gateway
8193    /// composite — every whole-Aplicacao mesh-artifact emitter reads
8194    /// all three as one unit). Same "one typed dispatch on the
8195    /// substrate primitive, thin projections at each consumer"
8196    /// discipline the peer outer-composite axes already route through.
8197    /// Named `entrada()` to match the storage field's name verbatim
8198    /// and the tatara-lisp author-surface term (`:entrada`) the
8199    /// field's own docstring already carries; the accessor's
8200    /// identity maps onto the canonical MESH-COMPOSITION §III.4
8201    /// vocabulary the slot's docstring already reaches for. Returns
8202    /// `Option<&Entrada>` (not the owning composite by copy or
8203    /// clone) because every downstream consumer of the entrada
8204    /// composite treats it as a read-only per-axis dispatch source
8205    /// — the reference-view is the narrowest borrow that supports
8206    /// every present + roadmapped consumer (per-axis accessor
8207    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
8208    /// port-fallback projection, early-return partition on the
8209    /// `None` arm) without cloning the composite through every
8210    /// consumer's fast path. The `Option` half of the return-type
8211    /// preserves the load-bearing "author-omitted `:entrada` ⇒
8212    /// internal-only mesh" partition (not a default composite the
8213    /// downstream must reject on emptiness) — the accessor projects
8214    /// the raw `Option<Entrada>` slot's presence bit through the
8215    /// reference-return unchanged.
8216    #[must_use]
8217    pub const fn entrada(&self) -> Option<&Entrada> {
8218        self.entrada.as_ref()
8219    }
8220
8221    /// Validate the typed shape:
8222    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
8223    ///     and a non-empty `:versao`; no two entries share the same
8224    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
8225    ///     not a multiset)
8226    ///   - every `:contratos` :de + :para must be in `:membros`
8227    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
8228    ///     contract is an inter-Servico edge, so a Servico contracting
8229    ///     with itself is a build error under every WIT shape
8230    ///     (MESH-COMPOSITION §III.1)
8231    ///   - no two `:contratos` entries agree on
8232    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
8233    ///     edges are a set, not a multiset (peer of the `:membros` /
8234    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
8235    ///   - `:entrada :para` must be in `:membros`
8236    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
8237    ///     `:placement Replicated`/`SingleNode` must NOT declare
8238    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
8239    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
8240    ///     between strategy and shard-key is symmetric: every validated
8241    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
8242    ///     Sharded`
8243    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
8244    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
8245    ///     the shard pool (MESH-COMPOSITION §III.1)
8246    ///   - every `:clusters` entry is non-empty and unique
8247    ///   - `:placement :affinity`, when set, is non-empty
8248    ///   - the synchronous-`:contratos` subgraph is acyclic
8249    ///     (MESH-COMPOSITION §III.3)
8250    ///   - every declared `:politicas` value is operationally meaningful
8251    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
8252    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
8253    ///     omit the field instead to express "no policy on this axis")
8254    pub fn validate(&self) -> Result<(), AplicacaoError> {
8255        self.validate_membros()?;
8256
8257        // `:contratos` per-slot gate — folds both structural axes on the
8258        // slot into one substrate primitive: the per-entry cascade (shape
8259        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
8260        // target + whole-edge dedup) and the cross-edge sync-cycle axis
8261        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
8262        // — pub-sub edges excluded, "acyclic by construction"). Same
8263        // fold-per-axis-plus-cross-axis discipline the sibling
8264        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
8265        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
8266        // onto `:contratos` so every future consumer of the slot (the M4
8267        // admission webhook re-checking `:contratos` after a per-edge
8268        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
8269        // acknowledges) reaches *both* structural axes through one call.
8270        self.validate_contratos()?;
8271
8272        self.validate_entrada()?;
8273
8274        self.validate_placement()?;
8275
8276        self.validate_politicas()?;
8277
8278        Ok(())
8279    }
8280
8281    /// The `:membros` graph-node name set — the membership oracle every
8282    /// per-Aplicacao name-reference axis resolves against.
8283    ///
8284    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
8285    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
8286    /// :para`, and `:entrada :para`. Each must resolve to a declared
8287    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
8288    /// the external gateway both address graph nodes, so a reference to
8289    /// a node the graph does not contain is a build error). All three
8290    /// resolve against *this* set, so the set's construction is the one
8291    /// shared substrate primitive underneath the whole reference-
8292    /// resolution surface.
8293    ///
8294    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
8295    /// `self.membros().iter().map(Membro::nome).collect()` builder so
8296    /// the two per-slot gates that consume it — the per-`:contratos`
8297    /// membership arms still inline at `validate` and the lifted
8298    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
8299    /// oracle through one dispatch rather than each open-coding the
8300    /// projection. Every future consumer on the same axis (the M4
8301    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
8302    /// reference resolver, the per-`:contratos`-edge `:politicas`
8303    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
8304    /// resolves an edge's endpoints against the same membership set
8305    /// before it can key a per-edge policy off them) inherits the
8306    /// projection through the same call, so a future rebrand of the
8307    /// node-identity axis (a namespace-qualified member name the CR
8308    /// materializer applies per-CR, the `:membros :nome-suffix`
8309    /// overlay §III.2 acknowledges) lands at exactly one place rather
8310    /// than at every reference-resolution site in lockstep. Peer of
8311    /// the sibling per-slot substrate primitives
8312    /// [`MeshPolicy::validate`] (f03a154) and
8313    /// [`WitContract::identity`] on their own axes.
8314    fn membro_names(&self) -> std::collections::HashSet<&str> {
8315        self.membros().iter().map(Membro::nome).collect()
8316    }
8317
8318    /// Reject `:contratos` entries whose endpoints are malformed,
8319    /// reference a Servico outside the graph, self-loop, carry an
8320    /// empty `:wit` shape, duplicate a prior entry on the six-axis
8321    /// identity key, or close a synchronous-edge cycle in the
8322    /// resulting typed graph.
8323    ///
8324    /// The `:contratos` slot is the typed inter-Servico edge set
8325    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
8326    /// edge whose `:de` / `:para` reference two distinct members and
8327    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
8328    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
8329    /// per-HTTP `HTTPRoute`) fans out on.
8330    ///
8331    /// Two structural axes on the slot are folded into this per-slot
8332    /// gate: the per-entry axis (six per-edge arms, listed below) and
8333    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
8334    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
8335    /// per-entry cascade). Same
8336    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
8337    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
8338    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
8339    /// `:politicas` slot, extended here onto `:contratos`.
8340    ///
8341    /// Six per-entry axes are gated first, in the canonical
8342    /// edge-direction order the paired diagnostics already encode
8343    /// (per-arm value shape before graph-membership lookup; structural
8344    /// self-edge before payload-shape target dispatch; whole-edge dedup
8345    /// last):
8346    ///
8347    ///   - per-arm `:de` / `:para` value shape via
8348    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
8349    ///     `:de` before `:para`;
8350    ///   - per-edge graph-membership against the
8351    ///     [`AplicacaoSpec::membro_names`] oracle via
8352    ///     [`WitContract::require_endpoints_in`] (folds the twin
8353    ///     `:de` / `:para` arms onto one substrate-primitive
8354    ///     dispatch), `:de` before `:para`;
8355    ///   - structural self-edge via [`WitContract::is_self_loop`]
8356    ///     (caller-equals-callee under any WIT shape);
8357    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
8358    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
8359    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
8360    ///     `Capability` — each carry their own required payload field);
8361    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
8362    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
8363    ///     slot)` tuple).
8364    ///
8365    /// One cross-edge axis is gated last, after the per-entry cascade
8366    /// completes cleanly:
8367    ///
8368    ///   - synchronous-edge cycle detection via
8369    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
8370    ///     three-coloring over the sync-only subgraph, pub-sub edges
8371    ///     skipped per MESH-COMPOSITION §III.3 —
8372    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
8373    ///     per-entry cascade so a per-entry defect surfaces through its
8374    ///     narrower shape/membership/dedup arm before the cross-edge
8375    ///     cycle diagnostic, matching the pre-fold `validate`-side
8376    ///     dispatch ordering (`validate_contratos()? →
8377    ///     detect_sync_cycles()?`).
8378    ///
8379    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
8380    /// seen_contracts = …; for c in self.contratos() { … }` block onto
8381    /// a named per-slot gate, closing the last unlifted per-slot gate
8382    /// on the M3 mesh-slot family. Every peer slot already carries the
8383    /// shape ([`AplicacaoSpec::validate_membros`],
8384    /// [`AplicacaoSpec::validate_entrada`],
8385    /// [`AplicacaoSpec::validate_placement`],
8386    /// [`AplicacaoSpec::validate_politicas`]).
8387    ///
8388    /// Self-contained on `&self` — it resolves its own membership
8389    /// oracle through [`AplicacaoSpec::membro_names`] rather than
8390    /// borrowing one threaded down from `validate`, and runs its own
8391    /// cross-edge cycle probe rather than deferring the axis to an
8392    /// outer dispatch — so a future consumer that re-validates *one*
8393    /// slot against a mutated spec (the M4 admission webhook
8394    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
8395    /// without re-walking `:membros` / `:entrada` / `:placement` /
8396    /// `:politicas`, or the M4 per-edge policy resolver
8397    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
8398    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
8399    /// own identity closure *and* the sync-cycle invariant before it
8400    /// can key a per-edge override off the endpoint tuple) reaches
8401    /// *both* structural axes on the slot through one call, exactly as
8402    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
8403    /// cross-axis surfaces on `:politicas` through
8404    /// [`MeshPolicy::validate`].
8405    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
8406        let names = self.membro_names();
8407
8408        // Identity key for the typed-edge duplicate gate below: every
8409        // field that distinguishes one contract from another. Two
8410        // entries that agree on all six are *the same edge declared
8411        // twice*, the typed-graph analogue of duplicate `:membros` /
8412        // `:placement :clusters` / `:entrada :paths` entries (which
8413        // are already build errors at this layer). Rejecting it at the
8414        // validate gate closes a renderer-side footgun: caixa-mesh's
8415        // `cilium_network_policies` keys each emitted policy by
8416        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
8417        // (de, para) and identical payload would land as two K8s
8418        // objects with colliding `metadata.name`, rejected at apply
8419        // time far from the source caixa.lisp.
8420        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
8421            std::collections::HashSet::new();
8422        for c in self.contratos() {
8423            // Per-axis value-shape gate on every `:contratos` name
8424            // reference, before any graph-membership lookup. Empty +
8425            // DNS-1123-malformed `:de`/`:para` values silently fell
8426            // through to `ContratoMemberMissing` at the lookup arm
8427            // because every `:membros :caixa` is shape-validated
8428            // (3f9d7a0), so the `names` set structurally cannot contain
8429            // an empty / malformed string and the membership-lookup
8430            // diagnostic always misframed the root cause as
8431            // "this caixa is not in `:membros`". The shape gate runs
8432            // ahead of the lookup so structurally-impossible-to-match
8433            // inputs route through the narrower self-locating
8434            // diagnostic, preserving the legitimate "well-shaped
8435            // phantom reference" arm. `:de` runs before `:para` per
8436            // the canonical edge-direction order the existing
8437            // membership lookup, self-edge check, target dispatch,
8438            // and diagnostic strings already use.
8439            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
8440            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
8441            // Per-edge graph-membership gate on the twin `:de` / `:para`
8442            // arms — folded onto the substrate-primitive dispatch
8443            // [`WitContract::require_endpoints_in`] so every per-edge
8444            // consumer of the endpoint-resolution axis (this per-slot
8445            // gate at build time, the M4 admission webhook re-checking
8446            // one edge after a per-`(:de, :para)` patch, the per-edge
8447            // `:politicas` override MESH-COMPOSITION §III.2 #3
8448            // acknowledges) reaches the axis through one call rather
8449            // than re-inlining the twin `if !names.contains(...)`
8450            // cascade. `:de` fires before `:para` inside the primitive,
8451            // preserving byte-equal diagnostic ordering with the
8452            // pre-lift inline cascade.
8453            c.require_endpoints_in(&names)?;
8454            // A `:contratos` entry is an *inter*-Servico contract
8455            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
8456            // typed edge between two distinct graph nodes. An edge whose
8457            // `:de` equals its `:para` is a Servico contracting with
8458            // itself — a degenerate edge under every WIT shape. Firing
8459            // the gate before the `:wit`/`target()` shape checks means
8460            // the structural "this edge can't exist" error precedes the
8461            // narrower payload-shape diagnostics, and shape-agnostically
8462            // covers all four `WitTarget` arms (HTTP / Store / Capability
8463            // / PubSub) at one point. Peer of the duplicate-`:contratos`
8464            // / duplicate-`:membros` set gates: both reject a structurally
8465            // ill-formed graph at the typed surface, before the renderer
8466            // emits a K8s object that fails or no-ops far from the source
8467            // caixa.lisp.
8468            if c.is_self_loop() {
8469                return Err(AplicacaoError::contrato_self_loop(c));
8470            }
8471            if c.world_ref().is_empty() {
8472                return Err(AplicacaoError::empty_wit(c.edge_pair()));
8473            }
8474            // Shape ↔ target consistency — surfaces "HTTP wit without
8475            // :endpoint", "NATS wit with :endpoint set", etc. as named
8476            // build errors instead of silent renderer drops. Threaded
8477            // through the duplicate-edge diagnostic below (via
8478            // [`WitTarget::label`]) so the "which typed target arm did
8479            // the duplicate carry" question is answered by the typed
8480            // enum's variant discriminator, not by re-probing the raw
8481            // `Option<String>` payload fields.
8482            let target_view = c.target()?;
8483            // Contract identity: (de, para, wit, endpoint, subject, slot).
8484            // Two contracts that match on all six are the same typed edge
8485            // declared twice — author error, not a legitimate variant of
8486            // "same caller-callee pair, different payload" (e.g.
8487            // cart→catalog at /products vs /search), which keeps distinct
8488            // identity keys via the differing endpoint payloads.
8489            let key = c.identity();
8490            crate::render::insert_first_seen(&mut seen_contracts, key, || {
8491                AplicacaoError::contrato_duplicate(c, &target_view)
8492            })?;
8493        }
8494
8495        // Cross-edge cycle axis on the `:contratos` slot — folded into
8496        // the per-slot gate so the two structural axes on `:contratos`
8497        // (per-entry shape + membership + dedup above; cross-edge sync-
8498        // cycle detection here) reach every consumer through one call.
8499        // Same discipline the sibling per-slot compound gate
8500        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
8501        // — one named per-slot gate that folds *both* per-axis and
8502        // cross-axis surfaces on the same slot onto one substrate
8503        // primitive — extended here onto `:contratos`, closing the last
8504        // per-slot-axis-family that lived split across `validate` (the
8505        // per-entry `validate_contratos` half here and the cross-edge
8506        // `detect_sync_cycles` call the sibling below at `validate`
8507        // dispatched separately).
8508        //
8509        // Runs after the per-entry cascade so a per-entry defect (empty
8510        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
8511        // target inconsistency, whole-edge duplicate) surfaces first
8512        // through its narrower [`AplicacaoError`] arm before the cross-
8513        // edge cycle diagnostic. This matches the pre-lift ordering the
8514        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
8515        // → self.detect_sync_cycles()?`) — the cycle detector was
8516        // already the second `:contratos`-axis gate in the dispatch,
8517        // just at the outer altitude; the fold moves it under the same
8518        // named per-slot gate without reshaping the diagnostic order.
8519        self.detect_sync_cycles()?;
8520
8521        Ok(())
8522    }
8523
8524    /// Reject `:entrada` values that are operationally meaningless,
8525    /// structurally malformed, or reference a Servico outside the
8526    /// graph.
8527    ///
8528    /// The `:entrada` slot is the Aplicacao's single external ingress
8529    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
8530    /// Gateway API v1 `Listener`, `:paths` become the paired
8531    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
8532    /// the member the route forwards to. Omitting the slot entirely is
8533    /// the internal-only-mesh partition — an Aplicacao with no external
8534    /// surface — so the `None` arm is a clean pass, not a refusal.
8535    ///
8536    /// Five axes are gated here, in the canonical order the paired
8537    /// diagnostics already encode (reference-resolution before value
8538    /// shape, per-axis emptiness before per-axis grammar):
8539    ///
8540    ///   - `:para` — DNS-1123 value shape, then membership against the
8541    ///     [`AplicacaoSpec::membro_names`] oracle;
8542    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
8543    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
8544    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
8545    ///     path grammar, and set-not-multiset uniqueness.
8546    ///
8547    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
8548    /// Some(e) = self.entrada() { … }` block onto a named per-slot
8549    /// gate, the shape the three peer M3 mesh slots already carry
8550    /// ([`AplicacaoSpec::validate_membros`],
8551    /// [`AplicacaoSpec::validate_placement`],
8552    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
8553    /// `&self` — it resolves its own membership oracle through
8554    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
8555    /// threaded down from `validate` — so a future consumer that
8556    /// re-validates *one* slot against a mutated spec (the M4 admission
8557    /// webhook re-checking `:entrada` after a gateway-host patch
8558    /// without re-walking the whole `:contratos` graph) reaches the
8559    /// axis through one call, exactly as `detect_sync_cycles` is
8560    /// already self-contained for the M4 per-edge policy resolver.
8561    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
8562        let names = self.membro_names();
8563        if let Some(e) = self.entrada() {
8564            // Route the per-`:entrada` composite-reference read
8565            // through the lifted [`AplicacaoSpec::entrada`] accessor
8566            // rather than the raw `&self.entrada` field access — the
8567            // shape-and-membership gate's traversal head is now the
8568            // canonical read-side surface every per-Aplicacao entrada
8569            // consumer routes through, closing the fourth of four
8570            // open-coded outer-field accesses on the per-`:entrada`
8571            // outer-composite axis.
8572            //
8573            // Shape gate on `:entrada :para` runs ahead of the
8574            // membership lookup. Every `:membros :caixa` past
8575            // `validate_membro_caixa` is a valid DNS-1123 label
8576            // (3f9d7a0), so the `names` set structurally cannot
8577            // contain an empty / malformed string and the membership-
8578            // lookup diagnostic always misframed the root cause as
8579            // "this caixa is not in `:membros`". The shape gate
8580            // routes structurally-impossible-to-match inputs through
8581            // the narrower self-locating diagnostic, preserving the
8582            // legitimate "well-shaped phantom reference" arm — the
8583            // same trajectory the peer `:membros :caixa` (3f9d7a0),
8584            // `:placement :clusters` (6c8c00b), and `:contratos :de`
8585            // / `:para` (8d5af6b) axes already follow. This closes
8586            // the fourth and last Aplicacao-level Servico-name
8587            // reference axis on the canonical DNS-1123 floor.
8588            // Route the per-`:entrada :para` byte-string reads through
8589            // the lifted [`Entrada::destination`] accessor rather than
8590            // the raw `e.para` field access — the three
8591            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
8592            // (shape-gate `validate_entrada_para` arg, membership
8593            // lookup, `EntradaMemberMissing` diagnostic carry) now key
8594            // off exactly one typed dispatch on the substrate
8595            // primitive, closing the last unlifted per-`:entrada :para`
8596            // raw-field-access axis on the M3 mesh-slot validator.
8597            // The `.destination().to_string()` at the diagnostic site
8598            // is byte-identical to `.para.clone()` — pinned by the
8599            // sibling `destination_returns_entrada_para_byte_equal` +
8600            // `destination_borrows_from_entrada_para_storage` accessor
8601            // tests — so a future rebrand of the underlying `:para`
8602            // storage (a lift from `String` to a typed
8603            // `ServicoName(String)` newtype, a per-Aplicacao interning
8604            // arena the M4 CR materializer authors, a
8605            // `smol_str::SmolStr` inline-buffer swap) flows through
8606            // the accessor's one body without a coordinated
8607            // per-consumer rewrite across the M3 mesh validator.
8608            validate_entrada_para(e.destination())?;
8609            if !names.contains(e.destination()) {
8610                return Err(AplicacaoError::entrada_member_missing(e));
8611            }
8612            // Route the per-`:entrada :host` byte-string reads through
8613            // the lifted [`Entrada::hostname`] accessor rather than
8614            // the raw `e.host` field access — the emptiness gate and
8615            // the shape-gate `validate_entrada_host` arg now key off
8616            // exactly one typed dispatch on the substrate primitive,
8617            // closing the last unlifted per-`:entrada :host` raw-
8618            // field-access axis on the M3 mesh-slot validator. Peer
8619            // of the sibling per-`:entrada :para` convergence above
8620            // and pinned by the existing
8621            // `hostname_returns_entrada_host_byte_equal` +
8622            // `hostnames_returns_singleton_of_hostname_accessor`
8623            // accessor tests, so any future
8624            // Gateway-API-shaped host renormalization (a wildcard-
8625            // label lift, a trailing-`.` FQDN substitution, an IDNA
8626            // Punycode round-trip the SNI fan-out overlay authors)
8627            // flows through the accessor's one body without a
8628            // coordinated per-consumer rewrite across the M3 mesh
8629            // validator.
8630            if e.hostname().is_empty() {
8631                return Err(AplicacaoError::EmptyEntradaHost);
8632            }
8633            // The `:host` lands verbatim as a K8s Gateway API v1
8634            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
8635            // both apiserver-validated against the same restrictive
8636            // pattern: lowercase RFC 1123 DNS subdomain, optional
8637            // single leading wildcard label (`*.`), max length 253,
8638            // per-label max length 63, no IP literals, no scheme,
8639            // no port. Until this gate landed `validate()` only
8640            // refused the empty string (`EmptyEntradaHost`); a
8641            // structurally invalid hostname (`"https://example.com"`,
8642            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
8643            // `"_underscored.example.com"`, `"FOO.example.com"`,
8644            // `"checkout.quero.cloud."`) silently passed validate
8645            // and the apiserver `field is invalid` error surfaced at
8646            // `kubectl apply` time, far from the source caixa.lisp.
8647            // Lifting the gate to caixa-build time mirrors the
8648            // `:entrada :paths` value-shape trajectory (eb3456d) and
8649            // closes the last unstructured `:entrada` axis.
8650            validate_entrada_host(e.hostname())?;
8651            // Structural-floor gate on `:entrada :port`: every
8652            // validated `Entrada::port` past this gate lies in
8653            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8654            // type-inferred ceiling closes the top edge, so no companion
8655            // upper-cap arm is needed here — unlike the peer capped-
8656            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8657            // `require_positive_bounded_u32` bracket covers both edges).
8658            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8659            // accept-set-floor const rather than the prior inline
8660            // `if e.port == 0` byte-check so a future rebrand of the
8661            // accept-set floor (a hypothetical unprivileged-only
8662            // migration lifting the floor to `1024`, a per-cluster
8663            // scoping the operator pins through a future
8664            // `:placement :port-floor` slot as the M4 typed-slot
8665            // trajectory adds it, the future
8666            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8667            // per-Aplicacao gateway resolver reaching for the same
8668            // floor) is a one-line edit on the canonical
8669            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8670            // rewrite across the emit site + the pin test + every
8671            // future per-target renderer the substrate adds.
8672            if e.port() < SERVICO_PORT_MIN {
8673                return Err(AplicacaoError::EntradaPortZero);
8674            }
8675            // Each `:entrada :paths` entry becomes a K8s Gateway API
8676            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8677            // values that don't start with `/` for `type: PathPrefix`,
8678            // and an empty value is meaningless. Surface those as build
8679            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8680            // failures. Empty `:paths` itself is fine — caixa-mesh
8681            // falls back to a single `/` catch-all.
8682            let mut seen = std::collections::HashSet::new();
8683            // Route the per-entry value-shape gate's traversal head
8684            // through the lifted [`Entrada::paths`] slice accessor
8685            // rather than the raw `&e.paths` field access — the
8686            // per-Aplicacao `:entrada :paths` validate loop now keys
8687            // off the canonical raw-slot surface every downstream
8688            // per-`:entrada` path-list consumer (the sibling
8689            // [`Entrada::resolved_paths`] fallback-applying resolver
8690            // internal reads, `feira app graph`'s per-Aplicacao entrada
8691            // summary line's `{:?}` Debug print) routes through, so any
8692            // future rebrand on the typed slot's raw-slot reader lands
8693            // at exactly one place. Same convergence discipline as the
8694            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8695            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8696            // axis.
8697            for p in e.paths() {
8698                if p.is_empty() {
8699                    return Err(AplicacaoError::EntradaPathEmpty);
8700                }
8701                if !p.starts_with('/') {
8702                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8703                }
8704                // Per-entry value-shape gate: the path lands verbatim
8705                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8706                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8707                // against `maxLength: 1024` + the Gateway API webhook's
8708                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8709                // query/fragment separators, no whitespace, no control
8710                // characters, no non-ASCII bytes). Until this gate
8711                // landed `validate` only refused the empty string and
8712                // missing-leading-slash (eb3456d); a structurally
8713                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8714                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8715                // 1025-byte URL-shaped slug) silently passed validate
8716                // and the failure surfaced at `kubectl apply` time as
8717                // a Gateway API webhook rejection, far from the source
8718                // caixa.lisp, with no field naming the offending
8719                // `:paths` entry. Lifting the gate to caixa-build time
8720                // mirrors the `:entrada :host` value-shape trajectory
8721                // (c7d05ec) on the sibling axis — every author surface
8722                // that emits a Gateway API field now matches the
8723                // apiserver's accepted set at validate time.
8724                validate_entrada_path(p)?;
8725                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8726                    AplicacaoError::entrada_path_duplicate(p)
8727                })?;
8728            }
8729        }
8730
8731        Ok(())
8732    }
8733
8734    /// Reject `:membros` values that are operationally meaningless. The
8735    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8736    /// every entry names a Servico that participates in the Aplicacao,
8737    /// and the rendered programs.yaml fan-out emits one entry per
8738    /// `:membros`. Three authoring footguns are closed here:
8739    ///
8740    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8741    ///     a `programs:` entry whose `name:` is the empty string, which
8742    ///     downstream `lareira-fleet-programs` rejects at template time
8743    ///     with a non-localized error;
8744    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8745    ///     an empty semver constraint, so the failure surfaces far from
8746    ///     the source caixa.lisp;
8747    ///   - duplicate `:caixa` names — two entries with the same name
8748    ///     produce duplicate programs.yaml entries (one silently
8749    ///     overwrites the other in the cluster's HelmRelease values), and
8750    ///     contract membership lookups against `:contratos` collapse the
8751    ///     two onto one node, masking authoring mistakes.
8752    ///
8753    /// Same value-shape discipline as `:placement :clusters` (where empty
8754    /// + duplicate cluster names are rejected) and `:entrada :paths`
8755    /// (where empty + duplicate path entries are rejected). Lifting these
8756    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8757    /// §III.3 promise that the `:membros` set — the load-bearing identity
8758    /// of the application graph — is well-formed by construction.
8759    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8760        if self.membros().is_empty() {
8761            return Err(AplicacaoError::NoMembros);
8762        }
8763        let mut seen = std::collections::HashSet::new();
8764        for m in self.membros() {
8765            // Every emitted cluster artifact's `metadata.name` derives
8766            // from a `:membros :caixa` value verbatim — the rendered
8767            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8768            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8769            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8770            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8771            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8772            // `metadata.name` when the member is the `:entrada :para`
8773            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8774            // schema enforces the DNS-1123 label rule on admission;
8775            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8776            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8777            // mistaken-identity slug) silently passes the prior empty-/
8778            // duplicate-only gate and the failure surfaces at `kubectl
8779            // apply` time as a `metadata.name: Invalid value` rejection,
8780            // far from the source caixa.lisp, with no field naming the
8781            // offending `:membros` entry. Lifting the gate to caixa-build
8782            // time mirrors the `:entrada :host` value-shape trajectory
8783            // (c7d05ec) on the peer axis — every author surface that
8784            // emits a K8s name now matches the apiserver's accepted set
8785            // at validate time.
8786            validate_membro_caixa(m.nome())?;
8787            // The author surface for `:versao` is the same Cargo-shaped
8788            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8789            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8790            // resolves both axes through the same
8791            // [`crate::version::parse_requirement`] entry-point. The
8792            // shared [`crate::render::require_valid_versao_requirement`]
8793            // helper brackets the empty-first + parse cascade both peer
8794            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8795            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8796            // route through, so drift between the three axes' accepted
8797            // requirement sets is structurally impossible and the parse-
8798            // side no-op the empty-first arm closes (semver's empty
8799            // parse yields an implicit `*`) lives in exactly one
8800            // predicate.
8801            crate::render::require_valid_versao_requirement(
8802                m.versao_requirement(),
8803                || AplicacaoError::membro_versao_empty(m.nome()),
8804                |reason| {
8805                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8806                },
8807            )?;
8808            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8809                AplicacaoError::membro_duplicate(m.nome())
8810            })?;
8811        }
8812        Ok(())
8813    }
8814
8815    /// Reject `:placement` values that are operationally meaningless or
8816    /// internally contradictory. Each strategy variant has the same
8817    /// invariants on `:clusters` (non-empty list, non-empty unique
8818    /// entries) — the §III.1 author surface is uniform on this axis,
8819    /// even though the *meaning* of the list differs by strategy
8820    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8821    /// shard pool).
8822    ///
8823    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8824    /// are the same authoring footgun closed for `:politicas` zero
8825    /// values and `:entrada` empty paths: the field is *declared* but
8826    /// carries no meaning, so downstream renderers either skip it
8827    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8828    /// or apply it literally and fail at admission time. Lifting both
8829    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8830    /// violation is a build error" promise.
8831    ///
8832    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8833    /// is required exactly when `:estrategia Sharded` (hash-keyed
8834    /// distribution, Akka cluster-sharding convention, §II.4) and
8835    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8836    /// hash-keyed routing axis consumes it). The partition closes the
8837    /// "I think I configured sharding" footgun where an author writes
8838    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8839    /// the typed slot's value silently vanishes at the renderer layer
8840    /// — every validated `Placement` past this call satisfies
8841    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8842    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8843        // Every strategy needs at least one named cluster: `Replicated`
8844        // and `SingleNode` use the list as hosting/takeover candidates
8845        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8846        // §II.1), while `Sharded` uses it as the shard pool
8847        // (Akka cluster-sharding convention — §II.4). An empty list is
8848        // meaningless under any of the three.
8849        //
8850        // Route the paired pre-flight `.is_empty()` refusal probe and
8851        // the per-cluster validate loop's traversal head through the
8852        // lifted [`Placement::clusters`] slice-return accessor rather
8853        // than the raw `self.placement.clusters` field access — the
8854        // two production consumers of the per-`:placement` cluster-
8855        // pool `Vec`-carry now key off exactly one typed dispatch on
8856        // the substrate primitive, so any future rebrand on the axis
8857        // (a per-tenant cluster-pool overlay the operator pins through
8858        // a future `:placement :clusters-overrides` slot, a per-
8859        // Aplicacao dynamic cluster-pool derivation the future M5
8860        // adaptive-placement engine computes from `:affinity` weights)
8861        // migrates as a single caixa-core edit rather than a
8862        // coordinated rewrite of the paired arms — sibling of the
8863        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8864        // arm migration on the per-`:supervisor` static-child-list
8865        // `Vec`-carry axis.
8866        //
8867        // Route the per-`:placement` outer-composite reference read
8868        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8869        // rather than the raw `&self.placement` field access — the
8870        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8871        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8872        // axis-level lifted accessor family) now routes through the
8873        // substrate-primitive typed dispatch at the outer composition
8874        // altitude, the same shape the peer caixa-mesh
8875        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8876        // and the sibling `feira app graph` per-Aplicacao print line
8877        // now key off after this accessor lift.
8878        let p = self.placement();
8879        if p.clusters().is_empty() {
8880            // Route the per-`:placement` empty-clusters diagnostic
8881            // through the substrate-primitive
8882            // [`AplicacaoError::placement_without_clusters`] ctor rather
8883            // than the pre-lift three-line open-coded
8884            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8885            // p.estrategia() }` struct-literal — folds the sole in-crate
8886            // wire-up on this variant onto one dispatch matching the
8887            // sibling per-`:placement :clusters` dedup /
8888            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8889            // duplicate substrate-primitive-projection ctors on the
8890            // same `AplicacaoError` / `UpgradeError` envelopes.
8891            return Err(AplicacaoError::placement_without_clusters(p));
8892        }
8893        let mut seen = std::collections::HashSet::new();
8894        for c in p.clusters() {
8895            // Per-entry value-shape gate: the cluster name lands in
8896            // every K8s context / `lareira-fleet-programs` aggregator
8897            // filter / future M4 CR materializer's per-cluster axis
8898            // a validated `:clusters` entry passes through, each
8899            // enforcing the DNS-1123 label rule on admission. Same
8900            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8901            // on the peer name axis — both axes' validated values
8902            // are guaranteed-accepted by the apiserver without
8903            // re-validation at any downstream renderer or admission
8904            // layer.
8905            validate_placement_cluster(c)?;
8906            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8907                // Route the per-`:placement :clusters` dedup diagnostic
8908                // through the substrate-primitive
8909                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8910                // rather than the pre-lift three-line open-coded
8911                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8912                // c.clone() }` struct-literal — folds the sole in-crate
8913                // wire-up on this variant onto one dispatch matching the
8914                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8915                // per-`:politicas <scalar>` single-slot ctor families on
8916                // the same [`AplicacaoError`] envelope.
8917                AplicacaoError::placement_cluster_duplicate(c)
8918            })?;
8919        }
8920        // Route the per-`:placement :affinity` per-hint value-shape
8921        // gate through the typed [`Placement::affinity`] accessor rather
8922        // than the raw `&self.placement.affinity` field access — the
8923        // sole open-coded field-access site on the per-`:placement`
8924        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8925        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8926        // the accessor's `Option<&str>` return type;
8927        // [`validate_placement_affinity`]'s `&str` parameter accepts
8928        // the narrower borrow without a re-allocation, so the routing
8929        // change is byte-for-byte in the pass arm and remains
8930        // byte-for-byte in every failure diagnostic
8931        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8932        // String` field is populated inside
8933        // [`validate_placement_affinity`] via the peer `.to_string()`
8934        // path on the same borrowed slice). Peer of the sibling
8935        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8936        // routing through [`Placement::shard_key`] at the caixa-core
8937        // site above — extends the "read `:placement` optional-scalars
8938        // through the typed accessor" discipline to the second
8939        // `Option<String>`-shape slot on the M3 mesh-slot family.
8940        //
8941        // Per-hint value-shape gate: the `:affinity` value lands
8942        // verbatim in the M3 Adaptive compression overlay
8943        // (caixa-mesh's `placement.affinity` emission) and every
8944        // future M4 placement-engine routing axis keying off the
8945        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8946        // selector — each enforces the DNS-1123 label rule on
8947        // admission. Same typed-shape trajectory as `:placement
8948        // :clusters` (6c8c00b) on the sibling slot and the four
8949        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8950        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8951        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8952        // on the Aplicacao surface to land on the canonical
8953        // [`crate::render::is_dns_1123_label`] floor.
8954        if let Some(a) = p.affinity() {
8955            validate_placement_affinity(a)?;
8956        }
8957        match p.estrategia() {
8958            // Route the `Sharded`-arm shape-gate cascade through the
8959            // typed [`Placement::shard_key`] accessor rather than the
8960            // raw `&self.placement.shard_key` field access — one of the
8961            // two open-coded field-access sites on the per-`:placement`
8962            // Akka-cluster-sharding-key axis the accessor lift now
8963            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8964            // `&str` under the accessor's `Option<&str>` return type;
8965            // `str::is_empty` and [`validate_placement_shard_key`]'s
8966            // `&str` parameter both accept the narrower borrow without
8967            // a re-allocation.
8968            PlacementStrategy::Sharded => match p.shard_key() {
8969                None => return Err(AplicacaoError::ShardedWithoutKey),
8970                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8971                // Per-axis value-shape gate on the Akka-cluster-sharding
8972                // `:shard-key` extractor expression. The shape gate runs
8973                // after the more self-locating `ShardedKeyEmpty` arm so
8974                // a `:shard-key ""` surfaces the narrower empty
8975                // diagnostic first; every non-empty `:shard-key` past
8976                // this call is guaranteed to be a printable-ASCII
8977                // single-token reference the future M4 Akka-style
8978                // cluster-sharding reconciler can hash without
8979                // re-validating at the runtime layer. Mirrors the
8980                // payload-axis shape gates on the peer `:contratos`
8981                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8982                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8983                // intersection-floor to a caixa-build-time gate.
8984                Some(k) => validate_placement_shard_key(k)?,
8985            },
8986            // `:shard-key` is the Akka-cluster-sharding axis
8987            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8988            // across the cluster pool. `Replicated` (active-active across
8989            // every named cluster) and `SingleNode` (Erlang/OTP
8990            // distributed-app takeover/failover, §II.1) have no hash-keyed
8991            // routing axis to consume the slot; downstream renderers
8992            // (caixa-mesh's `placement.shardKey` overlay at
8993            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8994            // sharding reconciler) ignore `:shard-key` outside the
8995            // `Sharded` arm by construction. Until this gate landed an
8996            // author who wrote `:placement (:estrategia Replicated
8997            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8998            // copy-paste from a Sharded sibling caixa, the "I think I
8999            // configured sharding" footgun) silently passed validate and
9000            // the typed slot's value vanished at the renderer layer with
9001            // no diagnostic — the canonical "declared-but-inert" footgun
9002            // the empty-:affinity / empty-shard-key / zero-:politicas /
9003            // empty-:contratos-target gates already close on every other
9004            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
9005            // Lifting the rejection to a build-time gate closes the
9006            // Sharded ↔ non-Sharded partition over the typed
9007            // `:placement` slot: every validated `Placement` past this
9008            // call has `shard_key.is_some()` iff `estrategia ==
9009            // Sharded`, structurally — the future Akka reconciler can
9010            // reach for `placement.shard_key` knowing it's `Some` exactly
9011            // when the strategy consumes it, without re-deriving the
9012            // partition from inline strategy probes.
9013            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
9014                // Route the non-`Sharded`-arm declared-but-inert refusal
9015                // through the typed [`Placement::shard_key`] accessor —
9016                // the second of the two open-coded field-access sites the
9017                // accessor lift now owns. The `Some(k)`-bound `k` narrows
9018                // from `&String` to `&str`; the `AplicacaoError::
9019                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
9020                // materializes the owned `String` via `k.to_string()`
9021                // (peer to the sibling per-Membro `String`-carry sites
9022                // 4127bb6 routed through `m.nome().to_string()` /
9023                // `m.versao_requirement().to_string()`), so the whole
9024                // `Sharded` ↔ non-`Sharded` partition on the
9025                // `:shard-key` axis now flows through the same typed
9026                // dispatch as the sibling `Sharded`-arm shape gate.
9027                if let Some(k) = p.shard_key() {
9028                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
9029                }
9030            }
9031        }
9032        Ok(())
9033    }
9034
9035    /// Reject `:politicas` values that are operationally meaningless.
9036    /// Each axis is optional — omitting it expresses "no policy on this
9037    /// axis". Carrying a *zero* value for a declared axis is the bug
9038    /// this function rejects: zero is either
9039    ///
9040    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
9041    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
9042    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
9043    ///     "every Aplicacao declares :politicas :timeout (no infinite
9044    ///     blocking)", or
9045    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
9046    ///     first call; a 0-rate rate-limit denies every request).
9047    ///
9048    /// Lifting these "0 means the opposite of what you think" idioms to
9049    /// the typed Aplicacao surface as build errors mirrors the §III.3
9050    /// promise that contract drift, capability leaks, and cycles are all
9051    /// build errors — not runtime surprises.
9052    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
9053        // Route the whole per-axis + cross-axis `:politicas` cascade
9054        // through the substrate primitive [`MeshPolicy::validate`],
9055        // which folds all six per-axis brackets (`:timeout`,
9056        // `:retries`, `:circuit-breaker :max-failures`,
9057        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
9058        // window-canonical-form) plus the compound cross-axis fold
9059        // [`MeshPolicy::first_cross_axis_violation`] into one
9060        // `Result<(), AplicacaoError>` return. The whole per-axis-
9061        // brackets + cross-axis-fold cascade collapses to one call, and
9062        // every future [`MeshPolicy`] consumer (the future M4
9063        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9064        // admission webhook, the per-`:contratos`-edge `:politicas`
9065        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
9066        // of which resolves an *effective* per-edge [`MeshPolicy`] and
9067        // must emit *the same* diagnostic on the same input as `feira
9068        // build`) reaches through the same substrate-primitive dispatch
9069        // rather than re-inlining the four-per-axis + one-cross-axis
9070        // cascade in lockstep with this validate gate. Same trajectory
9071        // the peer per-kind compound entry gates
9072        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
9073        // [`crate::render::require_supervisor_view`] (8d8a5c3),
9074        // [`crate::render::require_v0_servico_shape`] (per-Caixa
9075        // layout axis) and the sibling compound cross-axis fold
9076        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
9077        // extended here onto the per-slot compound entry gate that
9078        // folds both per-axis + cross-axis surfaces on the M3
9079        // mesh-slot family.
9080        self.politicas().validate()
9081    }
9082
9083    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
9084    /// A synchronous edge is any contract whose typed [`WitTarget`] is
9085    /// `Http`, `Store`, or `Capability` — the caller blocks on the
9086    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
9087    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
9088    /// block on its subscribers, so they can never close a sync loop.
9089    ///
9090    /// Iterative DFS with three-coloring; the reported cycle is the
9091    /// path of caixa names traversed from the back-edge target around
9092    /// to itself, in declaration order. Adjacency lists and DFS roots
9093    /// are visited in `BTreeMap` key order so the diagnostic is
9094    /// deterministic across runs.
9095    ///
9096    /// Now the cross-edge axis of the per-slot compound gate
9097    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
9098    /// the per-entry cascade rather than at the outer
9099    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
9100    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
9101    /// sync-cycle) reach every consumer through one call. Kept
9102    /// standalone (rather than inlined) so consumers that want only the
9103    /// cross-edge axis (the M4 per-edge policy resolver
9104    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
9105    /// mutates one `:contratos` entry and needs to re-probe *just* the
9106    /// cycle invariant against the post-patch adjacency without
9107    /// re-running the per-entry shape/membership/dedup cascade the
9108    /// per-entry-only [M4 admission] fast path already covered) still
9109    /// have a self-contained entry point on the cycle axis.
9110    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
9111        use std::collections::{BTreeMap, BTreeSet};
9112
9113        #[derive(Clone, Copy, PartialEq, Eq)]
9114        enum Mark {
9115            White,
9116            Gray,
9117            Black,
9118        }
9119
9120        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
9121        for m in self.membros() {
9122            adj.entry(m.nome()).or_default();
9123        }
9124        for c in self.contratos() {
9125            // target() was already called by validate(); re-running here
9126            // keeps detect_sync_cycles self-contained for callers that
9127            // reuse it (M4 per-edge policy resolver) without revalidating.
9128            //
9129            // The pub-sub-arm check routes through the lifted
9130            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
9131            // arm-discriminator predicate rather than a raw `matches!(…,
9132            // WitTarget::PubSub { .. })` on the variant so a future
9133            // rebrand on the axis (an M4 per-edge WIT registry split of
9134            // [`WitTarget::PubSub`] into shape-specific peers, a
9135            // per-consumer rename that the accept-set already carries)
9136            // reaches this call site through the derive rather than a
9137            // scattered per-arm `matches!` rewrite — same
9138            // `IsVariant`-derived-arm-discriminator discipline the
9139            // peer closed-set typed enums ([`crate::CaixaKind`] via
9140            // f5bba80, [`PlacementStrategy`] via 766ec63,
9141            // [`crate::supervisor::RestartStrategy`] +
9142            // [`crate::supervisor::RestartPolicy`],
9143            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
9144            // already route through on the substrate's other typed-enum
9145            // arm-discriminator axes.
9146            if c.target()?.is_pubsub() {
9147                continue;
9148            }
9149            adj.entry(c.source()).or_default().insert(c.destination());
9150        }
9151
9152        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
9153        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
9154
9155        // Stable DFS root order — BTreeMap iteration is sorted by key.
9156        let roots: Vec<&str> = adj.keys().copied().collect();
9157
9158        // Frame: (node, sorted-neighbours snapshot, next-edge index).
9159        for root in roots {
9160            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
9161                continue;
9162            }
9163            let root_neighbors: Vec<&str> = adj
9164                .get(root)
9165                .map(|s| s.iter().copied().collect())
9166                .unwrap_or_default();
9167            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
9168            color.insert(root, Mark::Gray);
9169
9170            loop {
9171                // Read+advance the top frame in one borrow scope so we
9172                // can later mutate the stack (push/pop) without holding
9173                // a borrow across.
9174                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
9175                    let node = top.0;
9176                    if top.2 >= top.1.len() {
9177                        (node, None)
9178                    } else {
9179                        let nxt = top.1[top.2];
9180                        top.2 += 1;
9181                        (node, Some(nxt))
9182                    }
9183                });
9184                let Some((node, nxt_opt)) = step else { break };
9185                let Some(nxt) = nxt_opt else {
9186                    color.insert(node, Mark::Black);
9187                    stack.pop();
9188                    continue;
9189                };
9190                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
9191                match nxt_color {
9192                    Mark::Gray => {
9193                        // Reconstruct the cycle from `node` back through
9194                        // the parent chain to `nxt`, then close.
9195                        let mut cycle = Vec::new();
9196                        let mut cur = node;
9197                        cycle.push(cur.to_string());
9198                        while cur != nxt {
9199                            match parent.get(cur).copied() {
9200                                Some(p) => {
9201                                    cur = p;
9202                                    cycle.push(cur.to_string());
9203                                }
9204                                None => break,
9205                            }
9206                        }
9207                        cycle.reverse();
9208                        cycle.push(nxt.to_string());
9209                        return Err(AplicacaoError::contrato_cycle(cycle));
9210                    }
9211                    Mark::White => {
9212                        parent.insert(nxt, node);
9213                        color.insert(nxt, Mark::Gray);
9214                        let nxt_neighbors: Vec<&str> = adj
9215                            .get(nxt)
9216                            .map(|s| s.iter().copied().collect())
9217                            .unwrap_or_default();
9218                        stack.push((nxt, nxt_neighbors, 0));
9219                    }
9220                    Mark::Black => {}
9221                }
9222            }
9223        }
9224        Ok(())
9225    }
9226
9227    /// Substrate-canonical destination-facing TCP port every emitted
9228    /// per-Aplicacao artifact must key `destination`-shaped port axes
9229    /// off. Returns the typed `:entrada :port` scalar when this
9230    /// Aplicacao's `:entrada` block names `destination` under its
9231    /// `:para` axis (the destination Servico *is* the ingress apex, so
9232    /// the substrate honors the author-declared listener port
9233    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
9234    /// fallback otherwise (every non-apex destination — the internal
9235    /// mesh Servicos `:contratos` reach across, the future per-edge
9236    /// policy resolver's per-destination probe targets, the
9237    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
9238    /// L4 port resolver — reads the same substrate-canonical port floor
9239    /// by construction).
9240    ///
9241    /// Prior to this lift the "if :entrada matches this destination use
9242    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
9243    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
9244    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
9245    /// prior to this lift), with no typed method on the substrate primitive
9246    /// that named the rule. A future per-destination port axis addition
9247    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
9248    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
9249    /// per-Servico listener ports land, a per-cluster override the operator
9250    /// pins through a future `:placement :default-port` slot — would have
9251    /// to be threaded through every renderer's inline cascade in lockstep
9252    /// or one consumer would silently disagree on which port a given
9253    /// destination Servico's ingress lands at. Lifting the rule to a
9254    /// typed method on the substrate primitive means the M4 CR
9255    /// materializer, the future per-edge policy resolver, and every
9256    /// downstream test-fixture navigator reach for exactly one typed
9257    /// dispatch — the resolver's accept-set moves as a unit on any
9258    /// future axis addition.
9259    ///
9260    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
9261    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
9262    /// the typed primitive, thin projections at each consumer"
9263    /// discipline lifts on the sibling `:contratos` payload / `:politicas
9264    /// :rate-limit` unit-suffix axes; extends the discipline onto the
9265    /// destination-facing port-resolution axis every per-Aplicacao
9266    /// L4-fallback renderer consumes.
9267    #[must_use]
9268    pub fn port_for_destination(&self, destination: &str) -> u16 {
9269        // Route the per-`:entrada` composite-reference read through
9270        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
9271        // the raw `self.entrada.as_ref()` field access — the
9272        // per-destination L4-port fallback resolver's composite-
9273        // projection seed is now the canonical read-side surface
9274        // every per-Aplicacao entrada consumer routes through, peer
9275        // of the sibling `validate` per-`:entrada` shape-and-
9276        // membership gate migration on the same outer-composite
9277        // axis.
9278        // Route the per-`:entrada` apex-destination membership probe
9279        // through the lifted [`Entrada::destination`] accessor rather
9280        // than the raw `e.para == destination` field access — the last
9281        // un-lifted `.para` production-code read site on the per-
9282        // `:entrada` `:para` axis, sibling to the four caixa-core
9283        // consumer sites the peer 15ddd8c converge already routed
9284        // through the accessor (the three
9285        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
9286        // membership gate sites: the `validate_entrada_para` DNS-1123
9287        // shape gate, the per-`:membros` membership lookup, and the
9288        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
9289        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
9290        // `entrada.para`-projection converge at
9291        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
9292        // route-name projection site). Prior to this converge the
9293        // `port_for_destination` resolver was the solitary consumer
9294        // bypassing the typed dispatch on the `.para` axis — the two
9295        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
9296        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
9297        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
9298        // reach through the same accessor family compose with this
9299        // resolver at the emit boundary via the apex-identity
9300        // invariant `spec.port_for_destination(entrada.destination())
9301        // == entrada.port` the sibling
9302        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
9303        // pin pins across four permutations. A future extension of the
9304        // `:entrada :para` axis to a richer author surface (a per-
9305        // cluster alias overlay the operator pins through a future
9306        // `:placement`-scoped slot, a namespace-qualified rewrite the
9307        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
9308        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
9309        // §III.2 acknowledges) that lands on the accessor would silently
9310        // disagree between this resolver and the two `caixa-mesh` emit
9311        // sites — an author-declared `:para "cart"` value the accessor
9312        // rewrote to `"cart-v2"` under a future canary arm would leave
9313        // the resolver's membership arm falling through to
9314        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
9315        // `.para`) while the peer emit-site consumers landed on the
9316        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
9317        // silently disagreed on which destination port a given typed
9318        // `:entrada` resolves to at cluster-apply time. Pinned by the
9319        // drift-detection test
9320        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
9321        // below.
9322        self.entrada()
9323            .filter(|e| e.destination() == destination)
9324            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
9325    }
9326}
9327
9328/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
9329/// entry may name the Aplicacao's own `:nome`.
9330///
9331/// An Aplicacao that lists itself as a member is a degenerate self-edge in
9332/// the typed graph — the application graph is a DAG rooted at the Aplicacao
9333/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
9334/// Servicos that compose the app; an Aplicacao is never its own constituent),
9335/// and the lacre pipeline's closure-resolution would otherwise be handed a
9336/// node that is its own parent: a one-node cycle it either rejects far from
9337/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
9338/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
9339/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
9340/// label + lacre closure root), a member whose `:caixa` equals the
9341/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
9342/// peer.
9343///
9344/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
9345/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
9346/// gate `validate_upgrade_from_against_versao` and the supervision-tree
9347/// self-parent gate `crate::supervisor::validate_no_self_supervision`
9348/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
9349/// not a tree/mesh edge" discipline, here on the second typed-graph axis
9350/// (the Aplicacao :membros set; the supervision-tree :children list was the
9351/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
9352/// every validated Supervisor's children are distinct from its `:nome`,
9353/// every validated Aplicacao's membros are distinct from its `:nome`. The
9354/// transitive consequence is that `:entrada :para` and `:contratos`
9355/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
9356/// name the Aplicacao itself, without re-deriving the partition.
9357pub fn validate_no_self_membership(
9358    membros: &[Membro],
9359    parent_nome: &str,
9360) -> Result<(), AplicacaoError> {
9361    for m in membros {
9362        if m.nome() == parent_nome {
9363            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
9364        }
9365    }
9366    Ok(())
9367}
9368
9369#[derive(Debug, Error, PartialEq, Eq)]
9370pub enum AplicacaoError {
9371    #[error("Aplicacao must declare at least one :membros entry")]
9372    NoMembros,
9373    #[error(
9374        ":membros entry has empty :caixa (every member must name a Servico; \
9375         omit the entry instead of carrying an empty name)"
9376    )]
9377    MembroCaixaEmpty,
9378    #[error(
9379        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
9380         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
9381         name / label value the member name lands in; use a lowercase \
9382         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
9383    )]
9384    MembroCaixaInvalid { caixa: String, reason: String },
9385    #[error(
9386        ":membros entry {caixa:?} has empty :versao (every member must pin a \
9387         semver constraint that resolves through the lacre pipeline)"
9388    )]
9389    MembroVersaoEmpty { caixa: String },
9390    #[error(
9391        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
9392         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
9393         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
9394         carries; the lacre pipeline resolves both through the same parser)"
9395    )]
9396    MembroVersaoInvalid {
9397        caixa: String,
9398        versao: String,
9399        reason: String,
9400    },
9401    #[error(
9402        ":membros entry {caixa:?} appears more than once (the graph node set \
9403         is a set, not a multiset; duplicate members produce duplicate \
9404         programs.yaml entries and ambiguous :contratos membership lookups)"
9405    )]
9406    MembroDuplicate { caixa: String },
9407    #[error(
9408        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
9409         never its own constituent Servico (the application graph is a DAG rooted \
9410         at the Aplicacao; :membros names the *other* caixas that compose the \
9411         app, not the app itself). Since every :nome is a globally-unique \
9412         substrate identity, a member naming the Aplicacao's own :nome is a \
9413         one-node lacre-closure recursion, not a coincidentally-named peer; \
9414         drop the self-referential :membros entry or rename it to the actual \
9415         constituent caixa."
9416    )]
9417    MembroIsSelfAplicacao { caixa: String },
9418    #[error(
9419        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
9420         caixa declared in :membros; omit the contract or fill the {slot} field with a \
9421         member name)"
9422    )]
9423    ContratoCaixaEmpty { slot: &'static str },
9424    #[error(
9425        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
9426         :contratos {slot} value names a member of :membros, which is itself a \
9427         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
9428         object the member name lands in — Service, Pod, identity-based Cilium \
9429         selector; use a lowercase alphanumeric + hyphen identifier like \
9430         `\"checkout\"` or `\"cart-v2\"`)"
9431    )]
9432    ContratoCaixaInvalid {
9433        slot: &'static str,
9434        caixa: String,
9435        reason: String,
9436    },
9437    #[error("contrato references caixa {caixa:?} not declared in :membros")]
9438    ContratoMemberMissing { caixa: String },
9439    #[error(
9440        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
9441         entry is an inter-Servico contract whose :de and :para must name distinct \
9442         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
9443         the contract, or point :para at the member it actually calls)"
9444    )]
9445    ContratoSelfLoop { caixa: String, wit: String },
9446    #[error("contrato {de:?} → {para:?} has empty :wit")]
9447    EmptyWit { de: String, para: String },
9448    #[error(
9449        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
9450         {reason} (the substrate dispatches `:wit` values on the canonical \
9451         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
9452         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
9453         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
9454         kebab-case identifier per segment)"
9455    )]
9456    ContratoWitInvalid {
9457        de: String,
9458        para: String,
9459        wit: String,
9460        reason: String,
9461    },
9462    #[error(
9463        ":entrada :para is empty (every :entrada must route to a caixa declared in \
9464         :membros; fill the :para field with a member name)"
9465    )]
9466    EntradaParaEmpty,
9467    #[error(
9468        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
9469         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
9470         label per the K8s apiserver's `metadata.name` rule on every object the \
9471         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
9472         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
9473         `\"checkout\"` or `\"cart-v2\"`)"
9474    )]
9475    EntradaParaInvalid { para: String, reason: String },
9476    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
9477    EntradaMemberMissing { para: String },
9478    #[error(":entrada must declare a non-empty :host")]
9479    EmptyEntradaHost,
9480    #[error(
9481        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
9482         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
9483         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
9484         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
9485    )]
9486    EntradaHostInvalid { host: String, reason: String },
9487    #[error(":entrada :port must be in 1..=65535, got 0")]
9488    EntradaPortZero,
9489    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
9490    EntradaPathEmpty,
9491    #[error(
9492        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
9493    )]
9494    EntradaPathNotAbsolute { path: String },
9495    #[error(
9496        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
9497         value: {reason} (the K8s apiserver enforces the same shape on \
9498         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
9499         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
9500         requires percent-encoding `%XX` for non-ASCII and whitespace)"
9501    )]
9502    EntradaPathInvalid { path: String, reason: String },
9503    #[error(":entrada :paths entry {path:?} appears more than once")]
9504    EntradaPathDuplicate { path: String },
9505    #[error(
9506        ":placement {estrategia} requires at least one :clusters entry \
9507         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
9508    )]
9509    PlacementWithoutClusters { estrategia: PlacementStrategy },
9510    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
9511    PlacementClusterEmpty,
9512    #[error(
9513        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
9514         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
9515         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
9516         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
9517         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
9518         identifier like `\"rio\"` or `\"mar-east\"`)"
9519    )]
9520    PlacementClusterInvalid { cluster: String, reason: String },
9521    #[error(":placement :clusters entry {cluster:?} appears more than once")]
9522    PlacementClusterDuplicate { cluster: String },
9523    #[error(
9524        ":placement :affinity must be non-empty when set (omit :affinity to express \
9525         `no placement hint`)"
9526    )]
9527    PlacementAffinityEmpty,
9528    #[error(
9529        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
9530         (placement hints land verbatim in the M3 Adaptive compression overlay's \
9531         `placement.affinity` field and in every future M4 placement-engine routing \
9532         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
9533         selector — both enforce the DNS-1123 label rule on admission; use a \
9534         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
9535         `\"low-latency\"`, or `\"anti-affinity\"`)"
9536    )]
9537    PlacementAffinityInvalid { affinity: String, reason: String },
9538    #[error(":placement Sharded requires :shard-key")]
9539    ShardedWithoutKey,
9540    #[error(
9541        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
9542         hashes every entity onto the same shard, defeating sharding entirely)"
9543    )]
9544    ShardedKeyEmpty,
9545    #[error(
9546        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
9547         entity-id extractor expression: {reason} (the future M4 Akka-style \
9548         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
9549         as a single-token property reference and hashes the extracted entity ID \
9550         to compute shard placement; use a printable-ASCII extractor expression \
9551         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
9552         `\"${{tenant}}\"`)"
9553    )]
9554    ShardKeyInvalid { shard_key: String, reason: String },
9555    #[error(
9556        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
9557         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
9558         convention); :estrategia Replicated runs every cluster active-active and \
9559         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
9560         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
9561         to :estrategia Sharded if hash-keyed routing is the intent"
9562    )]
9563    ShardKeyOnNonSharded {
9564        estrategia: PlacementStrategy,
9565        shard_key: String,
9566    },
9567    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
9568    ContratoMissingTarget {
9569        de: String,
9570        para: String,
9571        wit: String,
9572        expected: &'static str,
9573    },
9574    #[error(
9575        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
9576         expected `:{expected}` only"
9577    )]
9578    ContratoWrongTarget {
9579        de: String,
9580        para: String,
9581        wit: String,
9582        expected: &'static str,
9583    },
9584    #[error(
9585        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
9586         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
9587         that matches no traffic and silently drops every request)"
9588    )]
9589    ContratoEndpointEmpty { de: String, para: String },
9590    #[error(
9591        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
9592         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
9593         :entrada :paths)"
9594    )]
9595    ContratoEndpointNotAbsolute {
9596        de: String,
9597        para: String,
9598        endpoint: String,
9599    },
9600    #[error(
9601        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
9602         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
9603         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
9604         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
9605         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
9606         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
9607         and whitespace)"
9608    )]
9609    ContratoEndpointInvalid {
9610        de: String,
9611        para: String,
9612        endpoint: String,
9613        reason: String,
9614    },
9615    #[error(
9616        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
9617         subject is a no-op subscribe; omit :subject only if the WIT world is not \
9618         pub-sub-shaped)"
9619    )]
9620    ContratoSubjectEmpty { de: String, para: String },
9621    #[error(
9622        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
9623         NATS subject: {reason} (the NATS server's subject parser enforces the \
9624         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
9625         single-token and `>` multi-token wildcards — at publish/subscribe time; \
9626         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
9627         `\"orders.*.completed\"` — a malformed subject silently drops every \
9628         message at runtime far from the source caixa.lisp)"
9629    )]
9630    ContratoSubjectInvalid {
9631        de: String,
9632        para: String,
9633        subject: String,
9634        reason: String,
9635    },
9636    #[error(
9637        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
9638         addresses the bucket root, defeating the per-key isolation the slot exists \
9639         for; omit :slot only if the WIT world is not store-shaped)"
9640    )]
9641    ContratoSlotEmpty { de: String, para: String },
9642    #[error(
9643        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
9644         WASI keyvalue store slot template: {reason} (the substrate enforces \
9645         the printable-ASCII intersection-floor every kv backend admits — \
9646         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9647         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9648         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9649         slot either gets rejected on write by strict backends or silently \
9650         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9651    )]
9652    ContratoSlotInvalid {
9653        de: String,
9654        para: String,
9655        slot: String,
9656        reason: String,
9657    },
9658    #[error(
9659        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9660         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9661        cycle.join(" → ")
9662    )]
9663    ContratoCycle { cycle: Vec<String> },
9664    #[error(
9665        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9666         than once (the typed graph edges are a set, not a multiset; duplicate \
9667         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9668         values that K8s admission rejects far from the source caixa.lisp)"
9669    )]
9670    ContratoDuplicate {
9671        de: String,
9672        para: String,
9673        wit: String,
9674        target: String,
9675    },
9676    #[error(
9677        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9678         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9679         express `no per-call deadline on this axis`"
9680    )]
9681    PolicyTimeoutZero,
9682    #[error(
9683        ":politicas :retries must be > 0 when set; omit :retries to express \
9684         `no retries on transient failure`"
9685    )]
9686    PolicyRetriesZero,
9687    #[error(
9688        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9689         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9690         retry policy into a thundering-herd amplification vector on transient \
9691         failure (one caller request fans out to `(retries+1)^depth` server-side \
9692         calls across the synchronous-:contratos subgraph), exactly the failure \
9693         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9694         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9695         or omit :retries to disable retries entirely"
9696    )]
9697    PolicyRetriesExceedsCap { retries: u32 },
9698    #[error(
9699        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9700         breaker trips on the first call); omit :circuit-breaker to disable it"
9701    )]
9702    PolicyBreakerZeroFailures,
9703    #[error(
9704        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9705         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9706         above this cap turns the typed breaker policy into a no-op: the trip \
9707         threshold is structurally so high that no realistic failures-per-:window \
9708         traffic shape can reach it, so the breaker never trips and every typed-slot \
9709         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9710         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9711         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9712         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9713         omit :circuit-breaker to disable the breaker entirely"
9714    )]
9715    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9716    #[error(
9717        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9718         tracks no failures); omit :circuit-breaker to disable it"
9719    )]
9720    PolicyBreakerZeroWindow,
9721    #[error(
9722        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9723         request); omit :rate-limit to disable rate limiting"
9724    )]
9725    PolicyRateLimitZero,
9726    #[error(
9727        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9728         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9729         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9730         structurally so high that no realistic per-edge traffic shape can drain it, \
9731         so the limiter never trips and every typed-slot consumer (the future \
9732         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9733         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9734         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9735         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9736         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9737         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9738         to disable rate limiting entirely"
9739    )]
9740    PolicyRateLimitExceedsCap { rate: u32 },
9741    #[error(
9742        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9743         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9744         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9745         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9746         three canonical windows)"
9747    )]
9748    PolicyRateLimitWindowNotCanonical { window: Duration },
9749    #[error(
9750        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9751         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9752         duration codec round-trips losslessly; got {timeout:?} which carries a \
9753         sub-millisecond residue that either truncates to a different `Duration` on \
9754         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9755         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9756         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9757         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9758    )]
9759    PolicyTimeoutNotCanonical { timeout: Duration },
9760    #[error(
9761        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9762         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9763         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9764         overlays carry a deadline so long no realistic synchronous-:contratos \
9765         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9766         CSE invariant degenerates to enforcement only at the per-Servico \
9767         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9768         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9769         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9770         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9771         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9772         `no per-call deadline on this axis` (the synchronous-call deadline then \
9773         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9774    )]
9775    PolicyTimeoutExceedsCap { timeout: Duration },
9776    #[error(
9777        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9778         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9779         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9780         sub-millisecond residue that either truncates to a different `Duration` on \
9781         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9782         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9783    )]
9784    PolicyBreakerWindowNotCanonical { window: Duration },
9785    #[error(
9786        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9787         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9788         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9789         is structurally so long that transient failures are never forgotten, the breaker \
9790         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9791         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9792         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9793         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9794         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9795         the breaker entirely"
9796    )]
9797    PolicyBreakerWindowExceedsCap { window: Duration },
9798    #[error(
9799        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9800         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9801         a single timing-out call can be declared failed, so the dominant failure mode \
9802         the breaker exists to catch is structurally never counted: a call dispatched at \
9803         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9804         open at dispatch has already rolled, and every typed-slot consumer (the future \
9805         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9806         outlier_detection.interval paired against the per-route request timeout) emits a \
9807         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9808         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9809         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9810         same shape), lower :timeout, or omit one of the two axes"
9811    )]
9812    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9813    #[error(
9814        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9815         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9816         :window ({cb_window:?}) — the token-bucket dispatches at most \
9817         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9818         structurally below the trip threshold, so the breaker cannot trip even under \
9819         100% failure and every typed-slot consumer (the future \
9820         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9821         outlier_detection.consecutive_5xx paired against \
9822         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9823         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9824         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9825    )]
9826    PolicyBreakerCannotTripUnderRateLimit {
9827        rate: u32,
9828        rl_window: Duration,
9829        max_failures: u32,
9830        cb_window: Duration,
9831    },
9832    #[error(
9833        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9834         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9835         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9836         at or before the last retry, so the breaker opens with declared retries still \
9837         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9838         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9839         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9840         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9841         Envoy / resilience4j production playbooks recommend the breaker's trip \
9842         threshold be observably larger than any single client's retry budget so the \
9843         breaker distinguishes one persistently-failing client from sustained \
9844         multi-client failure), lower :retries, or omit one of the two axes"
9845    )]
9846    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9847    #[error(
9848        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9849         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9850         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9851         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9852         retry policy is silently truncated by the same rate limiter it feeds through and \
9853         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9854         overlay, Envoy's retry_policy.num_retries paired against \
9855         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9856         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9857         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9858         bucket capacity be observably larger than any single client's retry budget so the \
9859         limiter distinguishes one client's declared retries from sustained multi-client \
9860         load), lower :retries, or omit one of the two axes"
9861    )]
9862    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9863}
9864
9865// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9866// ctor `entrada_host_invalid` is folded onto the sibling
9867// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9868// `{ <field>: String, reason: String }` variants
9869// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9870// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9871// `ShardKeyInvalid`), so every variant on the uniform two-slot
9872// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9873// reads through one substrate-primitive family rather than one macro
9874// closing six sites plus a hand-written seventh ctor closing the
9875// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9876// verbatim to the macro's outer doc block.
9877
9878// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9879// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9880// substrate-primitive family per typed variant — the paired sibling on
9881// [`AplicacaoError`] of the four `LayoutError` constructor families
9882// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9883// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9884// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9885// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9886// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9887// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9888// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9889// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9890// endpoint/subject, Capability with any payload; three
9891// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9892// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9893// opened the identical six-line
9894// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9895// WitTarget::<label> }` struct-literal against the local `edge()` closure
9896// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9897// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9898// on the same altitude the peer four `LayoutError` constructor families
9899// each closed on their sibling envelopes.
9900//
9901// The macro below generates one `#[must_use]` inherent constructor per
9902// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9903// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9904// dispatch per arm: `return
9905// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9906// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9907// the pre-lift struct-literal on the same edge fixture. The uniform four-
9908// field construction (`de, para, wit` triple-destructure onto same-named
9909// fields + `expected` verbatim) is spelled once — inside the macro —
9910// rather than at every wire-up site. `#[must_use]` fires a compile warning
9911// at any wire-up that mistakenly discards the constructed error.
9912//
9913// Every future consumer that wants to construct one of these two variants
9914// outside [`WitContract::target`] (a deferred
9915// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9916// admission validator raising wrong-target / missing-target diagnostics
9917// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9918// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9919// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9920// slots) reaches the variant through one call rather than re-inlining the
9921// six-line struct-literal block in lockstep with the seven in-crate
9922// wire-up sites.
9923macro_rules! contrato_target_ctors {
9924    ($($ctor:ident => $variant:ident),* $(,)?) => {
9925        impl AplicacaoError {
9926            $(
9927                #[doc = concat!(
9928                    "Construct an [`AplicacaoError::",
9929                    stringify!($variant),
9930                    "`] naming the offending edge `(de, para, wit)` triple ",
9931                    "under the given `expected` payload-field-name label. ",
9932                    "Folds the uniform `{ de, para, wit, expected }` four-",
9933                    "slot struct-literal onto one substrate primitive so ",
9934                    "every [`WitContract::target`] wire-up on this variant ",
9935                    "reads through one dispatch rather than the pre-lift ",
9936                    "six-line open-coded block. The `edge` triple threads ",
9937                    "verbatim from [`WitContract::edge_triple`] via the ",
9938                    "local `edge()` closure at the call site."
9939                )]
9940                #[must_use]
9941                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9942                    let (de, para, wit) = edge;
9943                    Self::$variant { de, para, wit, expected }
9944                }
9945            )*
9946        }
9947    };
9948}
9949
9950contrato_target_ctors! {
9951    contrato_wrong_target => ContratoWrongTarget,
9952    contrato_missing_target => ContratoMissingTarget,
9953}
9954
9955// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9956// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9957// onto one substrate-primitive family per typed variant — the paired
9958// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9959// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9960// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9961// `ContratoMissingTarget`) and of the two-slot
9962// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9963// on the sibling per-`:entrada :host` envelope. Every one of the four
9964// wire-up sites — three under [`WitContract::target`] (the empty
9965// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9966// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9967// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9968// value-shape gate fires ahead of) — opened the identical two-line
9969// `let (de, para) = <contract>.edge_pair(); return Err(
9970// AplicacaoError::<Variant> { de, para });` block against the local
9971// [`WitContract::edge_pair`] composite-projection accessor, the exact
9972// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9973// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9974// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9975// sibling envelopes.
9976//
9977// The macro below generates one `#[must_use]` inherent constructor per
9978// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9979// collapsing the four sites onto one dispatch per arm:
9980// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9981// equal to the pre-lift struct-literal on the same edge pair. The
9982// uniform two-field construction (`de, para` pair-destructure onto
9983// same-named fields) is spelled once — inside the macro — rather than
9984// at every wire-up site. `#[must_use]` fires a compile warning at any
9985// wire-up that mistakenly discards the constructed error.
9986//
9987// Every future consumer that wants to construct one of these four
9988// variants outside the two in-crate wire-up sites (a deferred
9989// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9990// admission validator raising empty-payload / empty-`:wit` diagnostics,
9991// a future `feira validate --contratos` per-caixa admission verb, an
9992// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9993// [`WitContract`] payload slot against a canonical per-arm requirement
9994// table) reaches the variant through one call rather than re-inlining
9995// the two-line pair-destructure block in lockstep with the four
9996// in-crate wire-up sites.
9997macro_rules! contrato_empty_pair_ctors {
9998    ($($ctor:ident => $variant:ident),* $(,)?) => {
9999        impl AplicacaoError {
10000            $(
10001                #[doc = concat!(
10002                    "Construct an [`AplicacaoError::",
10003                    stringify!($variant),
10004                    "`] naming the offending edge `(de, para)` pair. ",
10005                    "Folds the uniform `{ de, para }` two-slot struct-",
10006                    "literal onto one substrate primitive so every ",
10007                    "wire-up on this variant reads through one dispatch ",
10008                    "rather than the pre-lift two-line open-coded ",
10009                    "`let (de, para) = <contract>.edge_pair(); return ",
10010                    "Err(<Variant> { de, para });` block. The `edge` ",
10011                    "pair threads verbatim from [`WitContract::edge_pair`] ",
10012                    "at the call site."
10013                )]
10014                #[must_use]
10015                pub fn $ctor(edge: (String, String)) -> Self {
10016                    let (de, para) = edge;
10017                    Self::$variant { de, para }
10018                }
10019            )*
10020        }
10021    };
10022}
10023
10024contrato_empty_pair_ctors! {
10025    empty_wit => EmptyWit,
10026    contrato_endpoint_empty => ContratoEndpointEmpty,
10027    contrato_subject_empty => ContratoSubjectEmpty,
10028    contrato_slot_empty => ContratoSlotEmpty,
10029}
10030
10031// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
10032// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
10033// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
10034// onto one substrate primitive on [`AplicacaoError`] — sibling on the
10035// `{ de: String, para: String, <field>: String }` three-slot envelope of
10036// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
10037// variants on the paired `{ de, para }` two-slot envelope carrying the
10038// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
10039// { de, para });` pair-destructure prelude), the peer four-slot
10040// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
10041// the paired `{ de, para, <field>: String, reason: String }` envelope
10042// carrying the parser-shaped `reason` trailer), and the peer four-slot
10043// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
10044// `{ de, para, wit, expected: &'static str }` envelope carrying the
10045// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
10046// variant is the sole occupant of the three-slot `{ de, para, <field>:
10047// String }` shape on [`AplicacaoError`] (no sibling
10048// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
10049// and `:slot` axes carry no "must start with /" invariant, since the
10050// NATS subject grammar and the WASI keyvalue slot template grammar don't
10051// share the Gateway-API-HTTPPathMatch leading-slash prelude the
10052// `:endpoint` axis does), so a full macro isn't warranted; a single
10053// `#[must_use]` inherent ctor matching the ambient
10054// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
10055// peer per-`:contratos` ctor families each carry closes the last
10056// open-coded three-slot struct-literal on the envelope, matching the
10057// same standalone-ctor discipline the sibling
10058// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
10059// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
10060// [`crate::SupervisorError::child_caixa_invalid`] /
10061// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
10062// `{ caixa: String, [versao: String,] reason: String }` two- and three-
10063// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
10064// one variant on the `{ host: String, reason: String }` two-slot
10065// envelope) apply on their sibling one-off variants.
10066//
10067// The one wire-up site on this variant — [`WitContract::target`]'s
10068// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
10069// six per-`:contratos` value-shape gates inside the same method body,
10070// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
10071// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
10072// `ContratoWitInvalid`) each already reach through one of the three
10073// peer macro-generated ctor families above — opened the same five-line
10074// `let (de, para) = self.edge_pair(); return
10075// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
10076// ep.to_string() });` struct-literal against the local
10077// [`WitContract::edge_pair`] composite-projection accessor and the
10078// caller-side `&str` endpoint — the exact "same block re-inlined at
10079// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10080// altitude the six peer `AplicacaoError` constructor families each
10081// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
10082// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
10083// becomes a caixa-build error, not a Cilium L7 policy-side path-match
10084// silent traffic drop far from the source caixa.lisp) now routes through
10085// one substrate primitive on the envelope.
10086//
10087// The ctor below folds the site onto one dispatch:
10088// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
10089// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
10090// on the same `(edge_pair, endpoint)` pair. The uniform three-field
10091// construction (`de, para` pair-destructure onto same-named fields +
10092// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
10093// body — rather than at the wire-up site. `#[must_use]` fires a compile
10094// warning at any future wire-up that mistakenly discards the constructed
10095// error.
10096//
10097// Every future consumer that wants to construct this variant outside
10098// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
10099// CR materializer's per-`:contratos` admission validator raising the
10100// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
10101// `feira validate --contratos` per-caixa admission verb re-running the
10102// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
10103// probing each declared `:endpoint` against the same shared
10104// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
10105// resolver rejecting a leading-slash-missing `:endpoint` against a
10106// cluster-local Cilium snapshot the M4 CR materializer projects) now
10107// reaches this variant through one call rather than re-inlining the
10108// five-line pair-destructure + struct-literal block in lockstep with
10109// the sole in-crate wire-up site.
10110impl AplicacaoError {
10111    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
10112    /// naming the offending edge `(de, para)` pair and the per-payload
10113    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
10114    /// endpoint.to_string() }` three-slot struct-literal onto one
10115    /// substrate primitive so every wire-up on this variant reads
10116    /// through one dispatch rather than the pre-lift five-line
10117    /// pair-destructure + struct-literal block. The `edge` pair threads
10118    /// verbatim from [`WitContract::edge_pair`] at the call site,
10119    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
10120    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
10121    /// paired two-slot and four-slot per-`:contratos :endpoint`
10122    /// envelopes on the same [`AplicacaoError`] type.
10123    #[must_use]
10124    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
10125        let (de, para) = edge;
10126        Self::ContratoEndpointNotAbsolute {
10127            de,
10128            para,
10129            endpoint: endpoint.to_string(),
10130        }
10131    }
10132
10133    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
10134    /// offending self-edge's owning `caixa` and its `:wit` world
10135    /// reference, projecting both slots through the [`WitContract`]'s
10136    /// own [`WitContract::source`] and [`WitContract::world_ref`]
10137    /// scalar accessors on the substrate primitive.
10138    ///
10139    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
10140    /// contract.world_ref().to_string() }` two-slot struct-literal onto
10141    /// one substrate primitive so every wire-up on this variant reads
10142    /// through one dispatch rather than the pre-lift four-line
10143    /// twin-`.to_string()` struct-literal block. The `contract` borrow
10144    /// threads verbatim from the caller-side `for c in
10145    /// self.contratos()` iteration at the sole in-crate wire-up site
10146    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
10147    /// per-`:contratos` `WitContract`-projection ctor discipline the
10148    /// peer [`AplicacaoError::empty_wit`] /
10149    /// [`AplicacaoError::contrato_endpoint_empty`] /
10150    /// [`AplicacaoError::contrato_subject_empty`] /
10151    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
10152    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
10153    /// envelope.
10154    ///
10155    /// The `caixa` slot is projected through [`WitContract::source`]
10156    /// rather than [`WitContract::destination`] to preserve byte-equal
10157    /// diagnostic ordering with the pre-lift open-coded body — a
10158    /// [`WitContract::is_self_loop`]-gated call site has
10159    /// `source() == destination()` by that predicate's own contract, so
10160    /// the two accessors are exchange-symmetric at this call site, but
10161    /// naming `source` at the ctor definition matches the pre-lift
10162    /// site's field selection and pins the discipline for any future
10163    /// consumer that constructs the variant against a not-yet-gated
10164    /// candidate contract (e.g. an M4
10165    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10166    /// webhook re-checking a per-`(:de, :para)` patched contract, a
10167    /// future `feira validate --contratos` per-caixa verb re-running
10168    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
10169    /// overlay resolver rejecting a self-edge introduced by a
10170    /// cluster-local `:contratos` override the M4 CR materializer
10171    /// projects).
10172    ///
10173    /// Peer of the sibling `WitContract`-projection ctors on the
10174    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
10175    /// same "one typed dispatch on the substrate primitive, projecting
10176    /// through the paired [`WitContract`] accessors, thin projections
10177    /// at each consumer" discipline extended here onto the last unlifted
10178    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
10179    /// inside [`AplicacaoSpec::validate_contratos`].
10180    #[must_use]
10181    pub fn contrato_self_loop(contract: &WitContract) -> Self {
10182        Self::ContratoSelfLoop {
10183            caixa: contract.source().to_string(),
10184            wit: contract.world_ref().to_string(),
10185        }
10186    }
10187
10188    /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
10189    /// offending duplicate edge's `(:de, :para, :wit)` triple and the
10190    /// per-payload `:target` byte-string, projecting the first three slots
10191    /// through the paired [`WitContract::edge_triple`] typed-accessor and
10192    /// the trailing `target:` slot through [`WitTarget::label`] on the
10193    /// substrate primitive.
10194    ///
10195    /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
10196    /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
10197    /// six-line pair-destructure + struct-literal onto one substrate
10198    /// primitive so every wire-up on this variant reads through one
10199    /// dispatch rather than the pre-lift open-coded block inside the
10200    /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
10201    /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
10202    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
10203    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
10204    /// per-`:contratos` self-edge two-slot envelope) and the sibling
10205    /// [`AplicacaoError::empty_wit`] (projecting through
10206    /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
10207    /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
10208    /// same [`AplicacaoError`] type — extended here onto the last unlifted
10209    /// four-slot `{ de: String, para: String, wit: String, target: String }`
10210    /// per-`:contratos` whole-edge-dedup envelope inside
10211    /// [`AplicacaoSpec::validate_contratos`], closing the paired
10212    /// duplicate-gate diagnostic constructor site the peer
10213    /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
10214    /// the last unlifted composite-projection wire-up.
10215    ///
10216    /// The `contract` borrow threads verbatim from the caller-side `for c
10217    /// in self.contratos()` iteration at the sole in-crate wire-up site
10218    /// [`AplicacaoSpec::validate_contratos`], and `target` threads
10219    /// verbatim from the paired `let target_view = c.target()?` local
10220    /// materialized upstream of the [`crate::render::insert_first_seen`]
10221    /// dedup dispatch — both project onto their respective substrate-
10222    /// primitive accessors ([`WitContract::edge_triple`] +
10223    /// [`WitTarget::label`]) inside the ctor body, matching the sibling
10224    /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
10225    /// posture verbatim on the paired self-edge envelope.
10226    ///
10227    /// Every future consumer that wants to construct this variant outside
10228    /// [`AplicacaoSpec::validate_contratos`] — a deferred
10229    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10230    /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
10231    /// candidate against a per-tenant `:contratos` overlay before the
10232    /// whole-edge dedup gate re-fires, a future `feira validate
10233    /// --contratos` per-caixa admission verb re-running the dedup check on
10234    /// demand, an M4 per-cluster contrato-cap resolver rejecting a
10235    /// cross-tenant duplicate-edge collision introduced by a fleet-local
10236    /// overlay the M4 CR materializer projects — now reaches this variant
10237    /// through one call rather than re-inlining the six-line pair-
10238    /// destructure + struct-literal block in lockstep with the existing
10239    /// wire-up.
10240    #[must_use]
10241    pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
10242        let (de, para, wit) = contract.edge_triple();
10243        Self::ContratoDuplicate {
10244            de,
10245            para,
10246            wit,
10247            target: target.label(),
10248        }
10249    }
10250
10251    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
10252    /// offending `:membros :caixa` and its `:versao` requirement under
10253    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
10254    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
10255    /// reason.into() }` three-slot struct-literal onto one substrate
10256    /// primitive so every wire-up on this variant reads through one
10257    /// dispatch, matching the peer
10258    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
10259    /// shape verbatim on the sibling `SupervisorError { caixa: String,
10260    /// versao: String, reason: String }` envelope's per-`:children :versao`
10261    /// axis. `reason` accepts both `&str` literals and `format!(…)`
10262    /// outputs through the `impl Into<String>` bound so the sole
10263    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
10264    /// requirement-cascade closure (routing the shared
10265    /// [`crate::render::require_valid_versao_requirement`]-delivered
10266    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
10267    /// transformation on the caller-side `reason` axis. The
10268    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
10269    /// routing the sole wire-up already threads through remains verbatim
10270    /// — the ctor's two `&str` parameters accept the two accessors'
10271    /// returns as-is with no re-allocation at the call site.
10272    #[must_use]
10273    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
10274        Self::MembroVersaoInvalid {
10275            caixa: caixa.to_string(),
10276            versao: versao.to_string(),
10277            reason: reason.into(),
10278        }
10279    }
10280
10281    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
10282    /// the offending `:placement :clusters` entry.
10283    ///
10284    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
10285    /// cluster.to_string() }` one-field struct-literal onto one substrate
10286    /// primitive so every wire-up on this variant reads through one
10287    /// dispatch rather than the pre-lift three-line open-coded
10288    /// struct-literal block. The `cluster` slot threads verbatim from the
10289    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
10290    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
10291    /// per-entry dedup closure passed to
10292    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
10293    /// bracket accepts the free function pointer as-is.
10294    ///
10295    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
10296    /// per-`:politicas <scalar>` single-slot ctor families
10297    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
10298    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
10299    /// `{ path: String }` at the peer per-gateway envelope,
10300    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
10301    /// at the peer per-`:politicas` cap-scalar envelope) on the same
10302    /// [`AplicacaoError`] type — extends the "one typed dispatch per
10303    /// substrate primitive on every single-slot per-M3-slot envelope"
10304    /// discipline onto the last unlifted `{ cluster: String }` one-slot
10305    /// per-`:placement :clusters` dedup-envelope inside
10306    /// [`AplicacaoSpec::validate_placement_shape`].
10307    ///
10308    /// Every future consumer that wants to construct this variant outside
10309    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
10310    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10311    /// webhook re-checking a `:placement :clusters` overlay against a
10312    /// per-tenant cluster-topology snapshot, a future `feira validate
10313    /// --placement` per-caixa admission verb re-running the dedup check
10314    /// on demand, an M4 per-cluster placement resolver rejecting a
10315    /// duplicate cluster-name entry introduced by a fleet-local overlay
10316    /// the M4 CR materializer projects — now reaches this variant through
10317    /// one call rather than re-inlining the three-line struct-literal.
10318    #[must_use]
10319    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
10320        Self::PlacementClusterDuplicate {
10321            cluster: cluster.to_string(),
10322        }
10323    }
10324
10325    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
10326    /// the offending `:placement :estrategia` scalar the empty `:clusters`
10327    /// list was declared against, projecting through the paired
10328    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
10329    /// primitive.
10330    ///
10331    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
10332    /// placement.estrategia() }` one-field struct-literal onto one
10333    /// substrate primitive so every wire-up on this variant reads through
10334    /// one dispatch rather than the pre-lift three-line open-coded
10335    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
10336    /// p.estrategia() }` block inside
10337    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
10338    /// projection posture as the sibling
10339    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
10340    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
10341    /// per-`:contratos` self-edge envelope) and the peer
10342    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
10343    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
10344    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
10345    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
10346    /// per-`:placement` empty-clusters envelope inside
10347    /// [`AplicacaoSpec::validate_placement`].
10348    ///
10349    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
10350    /// [`Placement::estrategia`] `Copy`-scalar return through one
10351    /// zero-runtime-work construction — no allocation, no owned-string
10352    /// materialization — so the pre-lift `Copy`-pass-through property the
10353    /// open-coded `p.estrategia()` field expression carried survives
10354    /// verbatim through the substrate primitive. The sibling
10355    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
10356    /// carries the paired `.to_string()`-owned-String allocation on the
10357    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
10358    /// preserves the zero-alloc posture at the substrate-primitive
10359    /// dispatch, matching the peer
10360    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
10361    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
10362    /// per-`:politicas` cap-scalar envelopes.
10363    ///
10364    /// Every future consumer that wants to construct this variant outside
10365    /// [`AplicacaoSpec::validate_placement`] — a deferred
10366    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10367    /// webhook re-checking a `:placement :clusters` overlay against a
10368    /// per-tenant cluster-topology snapshot when the overlay resolves to
10369    /// an empty list, a future `feira validate --placement` per-caixa
10370    /// admission verb re-running the empty-clusters check on demand, an
10371    /// M4 per-cluster placement resolver rejecting an empty cluster pool
10372    /// after a fleet-local overlay strips every declared cluster — now
10373    /// reaches this variant through one call rather than re-inlining the
10374    /// three-line struct-literal in lockstep with the one in-crate
10375    /// wire-up site.
10376    #[must_use]
10377    pub const fn placement_without_clusters(placement: &Placement) -> Self {
10378        Self::PlacementWithoutClusters {
10379            estrategia: placement.estrategia(),
10380        }
10381    }
10382
10383    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
10384    /// offending `:placement :estrategia` scalar and the declared-but-
10385    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
10386    /// the strategy through the paired [`Placement::estrategia`]
10387    /// `Copy`-scalar accessor on the substrate primitive.
10388    ///
10389    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
10390    /// placement.estrategia(), shard_key: shard_key.to_string() }`
10391    /// two-slot struct-literal onto one substrate primitive so every
10392    /// wire-up on this variant reads through one dispatch rather than
10393    /// the pre-lift four-line open-coded struct-literal block inside
10394    /// [`AplicacaoSpec::validate_placement`]'s
10395    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
10396    /// arm. Same substrate-primitive-projection posture as the sibling
10397    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10398    /// projecting through [`Placement::estrategia`] on the peer
10399    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10400    /// empty-clusters envelope) and the peer
10401    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10402    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10403    /// the paired per-`:contratos` self-edge envelope) ctors — extended
10404    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
10405    /// shard_key: String }` two-slot per-`:placement :shard-key`
10406    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
10407    /// partition.
10408    ///
10409    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
10410    /// `&str` from the sole in-crate wire-up site (narrowed from
10411    /// `Option<&str>` via [`Placement::shard_key`]) and any future
10412    /// `&String` deref from a downstream consumer that reaches for the
10413    /// slot through the paired accessor, materializing the owned
10414    /// [`String`] via one `.to_string()` at the substrate primitive so
10415    /// no per-arm `.to_string()` allocation lives at the caller. The
10416    /// `estrategia` slot threads through [`Placement::estrategia`]'s
10417    /// `Copy`-scalar return rather than accepting a bare
10418    /// [`PlacementStrategy`] argument, matching the peer
10419    /// [`AplicacaoError::placement_without_clusters`] discipline —
10420    /// carrying the [`Placement`] borrow through one accessor call at
10421    /// the substrate primitive is strictly stronger than accepting the
10422    /// scalar as a separate argument (a future caller that constructs
10423    /// the error against a candidate [`Placement`] whose
10424    /// [`Placement::estrategia`] value the caller re-derives from
10425    /// another source can silently disagree with the storage the
10426    /// [`Placement`] carries; the accessor-projected primitive cannot).
10427    ///
10428    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
10429    /// families on the same [`AplicacaoError`] type — same "one typed
10430    /// dispatch on the substrate primitive, projecting through the
10431    /// paired [`Placement`] accessors, thin projections at each
10432    /// consumer" discipline extended here onto the last unlifted
10433    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
10434    /// [`AplicacaoSpec::validate_placement`].
10435    ///
10436    /// Every future consumer that wants to construct this variant
10437    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
10438    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10439    /// webhook re-checking a `:placement (:estrategia Replicated
10440    /// :shard-key …)` overlay against a per-tenant cluster-topology
10441    /// snapshot, a future `feira validate --placement` per-caixa
10442    /// admission verb re-running the non-`Sharded`-arm refusal on
10443    /// demand, an M4 per-cluster placement resolver rejecting a
10444    /// declared-but-inert `:shard-key` introduced by a fleet-local
10445    /// overlay the M4 CR materializer projects — now reaches this
10446    /// variant through one call rather than re-inlining the four-line
10447    /// struct-literal in lockstep with the one in-crate wire-up site.
10448    #[must_use]
10449    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
10450        Self::ShardKeyOnNonSharded {
10451            estrategia: placement.estrategia(),
10452            shard_key: shard_key.to_string(),
10453        }
10454    }
10455
10456    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
10457    /// offending `:entrada :para` value the membership lookup against the
10458    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
10459    /// slot through the paired [`Entrada::destination`] byte-string
10460    /// accessor on the substrate primitive.
10461    ///
10462    /// Folds the uniform `Self::EntradaMemberMissing { para:
10463    /// entrada.destination().to_string() }` one-field struct-literal onto
10464    /// one substrate primitive so every wire-up on this variant reads
10465    /// through one dispatch rather than the pre-lift three-line
10466    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
10467    /// e.destination().to_string() }` block inside
10468    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
10469    /// projection posture as the sibling
10470    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10471    /// projecting through [`Placement::estrategia`] on the peer
10472    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10473    /// empty-clusters envelope) and the sibling
10474    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10475    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10476    /// the paired per-`:contratos` self-edge envelope) ctors — extended
10477    /// here onto the last unlifted `{ para: String }` one-slot
10478    /// per-`:entrada :para` phantom-reference envelope on the sibling
10479    /// per-`:entrada` slot.
10480    ///
10481    /// The `entrada: &Entrada` parameter threads verbatim from the
10482    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
10483    /// the sole in-crate wire-up site
10484    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
10485    /// per-`:entrada` byte-string reads that already route through
10486    /// [`Entrada::destination`] one accessor call earlier in the same
10487    /// gate (`validate_entrada_para(e.destination())?;` +
10488    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
10489    /// borrow through one accessor call at the substrate primitive is
10490    /// strictly stronger than accepting the bare `&str` as a separate
10491    /// argument — a future consumer that constructs the error against a
10492    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
10493    /// caller re-derives from another source (a raw `e.para` field
10494    /// access that skipped the accessor, a stale snapshot of the
10495    /// pre-normalization storage) can silently disagree with the
10496    /// storage the [`Entrada`] carries; the accessor-projected primitive
10497    /// cannot. Matches the peer
10498    /// [`AplicacaoError::placement_without_clusters`] and
10499    /// [`AplicacaoError::shard_key_on_non_sharded`]
10500    /// [`Placement`]-borrow-projection discipline on the sibling
10501    /// per-`:placement` envelope, and matches the peer
10502    /// [`AplicacaoError::contrato_self_loop`] and
10503    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
10504    /// [`WitContract`]-borrow-projection discipline on the sibling
10505    /// per-`:contratos` envelope.
10506    ///
10507    /// Every future consumer that wants to construct this variant
10508    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
10509    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10510    /// webhook re-checking a `:entrada :para` overlay against a
10511    /// per-tenant `:membros` snapshot after a fleet-local overlay
10512    /// renames a member, a future `feira validate --entrada` per-caixa
10513    /// admission verb re-running the phantom-reference lookup on
10514    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
10515    /// `:entrada :para` whose target Servico was stripped from the
10516    /// cluster-local `:membros` overlay, a future authoring-surface
10517    /// widening the field into a `(String, Vec<Suggestion>)` pair
10518    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
10519    /// this variant through one call rather than re-inlining the
10520    /// three-line struct-literal in lockstep with the one in-crate
10521    /// wire-up site.
10522    #[must_use]
10523    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
10524        Self::EntradaMemberMissing {
10525            para: entrada.destination().to_string(),
10526        }
10527    }
10528
10529    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
10530    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
10531    /// sync-only-subgraph gate at
10532    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
10533    /// gray-arm's back-edge target through the parent chain, folding the
10534    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
10535    /// onto one substrate primitive so every wire-up on this variant
10536    /// reads through one dispatch rather than the pre-lift open-coded
10537    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
10538    /// in-crate wire-up site inside
10539    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
10540    /// return. Same substrate-primitive-projection posture as the
10541    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
10542    /// projecting through [`Entrada::destination`] on the peer `{ para:
10543    /// String }` one-slot per-`:entrada :para` phantom-reference
10544    /// envelope) and [`AplicacaoError::placement_without_clusters`]
10545    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
10546    /// sibling `{ estrategia: PlacementStrategy }` one-slot
10547    /// per-`:placement` empty-clusters envelope) ctors — extended here
10548    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
10549    /// per-`:contratos` cross-edge sync-cycle envelope on the same
10550    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
10551    /// struct-literal wire-up under
10552    /// [`AplicacaoSpec::detect_sync_cycles`].
10553    ///
10554    /// The `cycle: Vec<String>` parameter threads verbatim from the
10555    /// caller-side DFS traversal's reconstructed cycle path (built up by
10556    /// walking `parent` from the gray-back-edge's source node back to
10557    /// its target, reversing, then appending the target once more so the
10558    /// first and last elements coincide by construction and the
10559    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
10560    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
10561    /// the pre-lift open-coded body's field selection exactly. Taking
10562    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
10563    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
10564    /// caller already owns the reconstructed [`Vec<String>`] at the
10565    /// gray-arm return, so no per-arm re-allocation lands on the ctor
10566    /// path).
10567    ///
10568    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
10569    /// families on the same [`AplicacaoError`] type — same "one typed
10570    /// dispatch on the substrate primitive, thin projections at each
10571    /// consumer" discipline extended here onto the last unlifted
10572    /// per-`:contratos` cross-edge cycle envelope inside
10573    /// [`AplicacaoSpec::detect_sync_cycles`].
10574    ///
10575    /// Every future consumer that wants to construct this variant
10576    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
10577    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10578    /// webhook re-checking a per-tenant `:contratos` overlay's
10579    /// sync-cycle invariant after a fleet-local overlay adds or removes
10580    /// a synchronous edge, a future `feira validate --contratos`
10581    /// per-caixa admission verb re-running the cross-edge cycle detector
10582    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
10583    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
10584    /// entry and needs to re-probe *just* the cycle invariant against
10585    /// the post-patch adjacency), a future authoring-surface widening
10586    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
10587    /// the per-hop WIT shape for a richer "break here" hint — now
10588    /// reaches this variant through one call rather than re-inlining the
10589    /// open-coded struct-literal in lockstep with the one in-crate
10590    /// wire-up site.
10591    #[must_use]
10592    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
10593        Self::ContratoCycle { cycle }
10594    }
10595
10596    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
10597    /// naming the offending `:politicas :circuit-breaker :window` and
10598    /// the paired `:politicas :timeout` scalars under the first-firing
10599    /// cross-axis-violation gate at
10600    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
10601    /// `window` slot through the [`CircuitBreaker::window`] scalar
10602    /// accessor on the substrate primitive.
10603    ///
10604    /// Folds the uniform `{ window: cb.window(), timeout: t }`
10605    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
10606    /// primitive so every wire-up on this variant reads through one
10607    /// dispatch rather than the pre-lift four-line struct-literal
10608    /// block. The `cb` borrow threads verbatim from the caller-side
10609    /// `if let (Some(t), Some(cb)) = (self.timeout(),
10610    /// self.circuit_breaker())` pair-destructure at the sole in-crate
10611    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
10612    /// window-below-timeout arm; `timeout` threads verbatim from the
10613    /// paired [`MeshPolicy::timeout`] accessor return already
10614    /// destructured out of the same `if let` pair. `const fn`
10615    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
10616    /// property verbatim (both fields are [`Duration`], the
10617    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
10618    /// no `.to_string()` / `.into()` allocation lands on the ctor
10619    /// path).
10620    ///
10621    /// The `window` slot is projected through [`CircuitBreaker::window`]
10622    /// (not spelled out as a bare `Duration` parameter) so a future
10623    /// widening of the `:circuit-breaker :window` axis — a
10624    /// per-`:contratos`-edge `:circuit-breaker :window` override the
10625    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
10626    /// the plain [`Duration`] window to a richer per-status-class
10627    /// window tuple once Envoy's `outlier_detection.interval` peers
10628    /// come into scope — reaches the diagnostic through one accessor
10629    /// swap rather than every wire-up in lockstep, matching the peer
10630    /// substrate-primitive-projection posture of
10631    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10632    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10633    /// the sibling `{ caixa: String, wit: String }` two-slot
10634    /// per-`:contratos` self-edge envelope),
10635    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
10636    /// through [`Entrada::destination`] on the sibling `{ para: String }`
10637    /// one-slot per-`:entrada :para` phantom-reference envelope), and
10638    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
10639    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
10640    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
10641    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
10642    /// / `:placement` envelopes.
10643    ///
10644    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10645    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10646    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10647    /// [`MeshPolicy::validate`] gate — extended here onto the
10648    /// first-firing cross-axis compound variant, whose multi-slot
10649    /// `{ window: Duration, timeout: Duration }` shape does not fit
10650    /// that macro's one-`Copy`-scalar-per-variant arity. The three
10651    /// remaining cross-axis variants
10652    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
10653    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
10654    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10655    /// on the two-slot `{ retries, max_failures }` envelope, and
10656    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10657    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10658    /// substrate-primitive-projection shape and are folded on their
10659    /// own axis by their own per-variant ctors as those wire-ups are
10660    /// lifted.
10661    ///
10662    /// Every future consumer that wants to construct this variant
10663    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10664    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10665    /// webhook re-checking a per-tenant `:politicas` overlay's
10666    /// window-vs-timeout cross-axis invariant after a cluster-local
10667    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10668    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10669    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10670    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10671    /// projecting a per-tenant per-axis ceiling into the same
10672    /// diagnostic shape — now reaches this variant through one call
10673    /// rather than re-inlining the open-coded struct-literal in
10674    /// lockstep with the one in-crate wire-up site.
10675    #[must_use]
10676    pub const fn policy_breaker_window_below_timeout(
10677        cb: &CircuitBreaker,
10678        timeout: Duration,
10679    ) -> Self {
10680        Self::PolicyBreakerWindowBelowTimeout {
10681            window: cb.window(),
10682            timeout,
10683        }
10684    }
10685
10686    /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
10687    /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
10688    /// cross-axis pair whose token-bucket window structurally starves the
10689    /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
10690    /// :window`.
10691    ///
10692    /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
10693    /// max_failures: cb.max_failures(), cb_window: cb.window() }`
10694    /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
10695    /// primitive so every wire-up on this variant reads through one dispatch
10696    /// rather than the pre-lift six-line struct-literal block. Both `rl` and
10697    /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
10698    /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
10699    /// pair-destructure at the sole in-crate wire-up site inside
10700    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
10701    /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
10702    /// zero-runtime-work property verbatim (all four fields are `u32` /
10703    /// [`Duration`], every projected accessor is itself `const fn`, and no
10704    /// `.to_string()` / `.into()` allocation lands on the ctor path).
10705    ///
10706    /// Every slot is projected through its paired substrate-primitive
10707    /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
10708    /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
10709    /// than spelled out as bare `u32` / [`Duration`] parameters so a future
10710    /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
10711    /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
10712    /// acknowledges, a promotion of the plain scalar rate to a richer
10713    /// per-status-class token bucket once Envoy's per-descriptor
10714    /// `local_rate_limit` peers come into scope — reaches the diagnostic
10715    /// through one accessor swap rather than every wire-up in lockstep.
10716    /// Matches the peer substrate-primitive-projection posture of
10717    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10718    /// projecting through [`CircuitBreaker::window`] on the sibling
10719    /// two-slot `{ window, timeout }` cross-axis
10720    /// `(:timeout, :circuit-breaker)` envelope) on the sibling
10721    /// first-firing cross-axis compound variant.
10722    ///
10723    /// Second cross-axis Policy* variant folded onto its own per-variant
10724    /// substrate primitive — extending the peer
10725    /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
10726    /// onto the second-firing cross-axis compound variant, whose four-slot
10727    /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
10728    /// the sibling two-slot ctor's arity. The two remaining cross-axis
10729    /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10730    /// on the two-slot `{ retries, max_failures }` envelope and
10731    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10732    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10733    /// substrate-primitive-projection shape and are folded on their own
10734    /// axis by their own per-variant ctors as those wire-ups are lifted.
10735    ///
10736    /// Every future consumer that wants to construct this variant outside
10737    /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
10738    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10739    /// webhook re-checking a per-tenant `:politicas` overlay's
10740    /// starve-under-rate-limit cross-axis invariant after a cluster-local
10741    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10742    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10743    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10744    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10745    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10746    /// shape — now reaches this variant through one call rather than
10747    /// re-inlining the open-coded struct-literal in lockstep with the one
10748    /// in-crate wire-up site.
10749    #[must_use]
10750    pub const fn policy_breaker_cannot_trip_under_rate_limit(
10751        rl: &RateLimit,
10752        cb: &CircuitBreaker,
10753    ) -> Self {
10754        Self::PolicyBreakerCannotTripUnderRateLimit {
10755            rate: rl.rate(),
10756            rl_window: rl.window(),
10757            max_failures: cb.max_failures(),
10758            cb_window: cb.window(),
10759        }
10760    }
10761
10762    /// Construct an
10763    /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10764    /// naming the offending `:politicas :retries` and the paired
10765    /// `:politicas :circuit-breaker :max-failures` scalars under the
10766    /// third-firing cross-axis-violation gate at
10767    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
10768    /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
10769    /// scalar accessor on the substrate primitive.
10770    ///
10771    /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
10772    /// two-slot `Copy`-`u32` struct-literal onto one substrate
10773    /// primitive so every wire-up on this variant reads through one
10774    /// dispatch rather than the pre-lift four-line struct-literal
10775    /// block. The `cb` borrow threads verbatim from the caller-side
10776    /// `if let (Some(retries), Some(cb)) = (self.retries(),
10777    /// self.circuit_breaker())` pair-destructure at the sole in-crate
10778    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
10779    /// retries-saturate arm; `retries` threads verbatim from the paired
10780    /// [`MeshPolicy::retries`] accessor return already destructured out
10781    /// of the same `if let` pair. `const fn` preserves the pre-lift
10782    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10783    /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
10784    /// is itself `const fn`, and no `.to_string()` / `.into()`
10785    /// allocation lands on the ctor path).
10786    ///
10787    /// The `max_failures` slot is projected through
10788    /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
10789    /// `u32` parameter) so a future widening of the
10790    /// `:circuit-breaker :max-failures` axis — a
10791    /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
10792    /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
10793    /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
10794    /// resolver projects, a promotion of the plain `u32` count to a
10795    /// richer per-status-class trip counter once Envoy's
10796    /// `outlier_detection.consecutive_5xx` peers come into scope —
10797    /// reaches the diagnostic through one accessor swap rather than
10798    /// every wire-up in lockstep, matching the peer
10799    /// substrate-primitive-projection posture of
10800    /// [`AplicacaoError::policy_breaker_window_below_timeout`]
10801    /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
10802    /// sibling two-slot `{ window, timeout }` first cross-axis
10803    /// envelope) and
10804    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10805    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10806    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10807    /// [`CircuitBreaker::window`] on the sibling four-slot second
10808    /// cross-axis envelope). `retries` remains a bare `u32` parameter,
10809    /// matching the sibling first-arm ctor's bare `timeout: Duration`
10810    /// parameter discipline: [`MeshPolicy::retries`] returns
10811    /// `Option<u32>` and the caller-side `if let` already destructures
10812    /// the inner `u32` out, so the ctor takes the destructured scalar
10813    /// verbatim rather than re-wrapping it into an accessor call.
10814    ///
10815    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10816    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10817    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10818    /// [`MeshPolicy::validate`] gate — extended here onto the
10819    /// third-firing cross-axis compound variant, whose multi-slot
10820    /// `{ retries: u32, max_failures: u32 }` shape does not fit that
10821    /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
10822    /// cross-axis variant
10823    /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10824    /// two-slot `{ retries, rate }` envelope) carries a distinct
10825    /// substrate-primitive-projection shape (projecting through
10826    /// [`RateLimit::rate`] rather than
10827    /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
10828    /// by its own per-variant ctor as that wire-up is lifted in a
10829    /// follow-up run.
10830    ///
10831    /// Every future consumer that wants to construct this variant
10832    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10833    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10834    /// webhook re-checking a per-tenant `:politicas` overlay's
10835    /// retries-vs-max-failures cross-axis invariant after a
10836    /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
10837    /// #3 roadmap acknowledges resolves an *effective* per-edge
10838    /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
10839    /// override the M4 CR resolver projects, an M4 per-cluster
10840    /// `:politicas`-cap resolver projecting a per-tenant per-axis
10841    /// ceiling into the same diagnostic shape — now reaches this
10842    /// variant through one call rather than re-inlining the open-coded
10843    /// struct-literal in lockstep with the one in-crate wire-up site.
10844    #[must_use]
10845    pub const fn policy_breaker_trips_before_retries_exhausted(
10846        retries: u32,
10847        cb: &CircuitBreaker,
10848    ) -> Self {
10849        Self::PolicyBreakerTripsBeforeRetriesExhausted {
10850            retries,
10851            max_failures: cb.max_failures(),
10852        }
10853    }
10854
10855    /// Construct an
10856    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
10857    /// the offending `:politicas :retries` and the paired `:politicas
10858    /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
10859    /// remaining) cross-axis-violation gate at
10860    /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
10861    /// slot through the [`RateLimit::rate`] scalar accessor on the
10862    /// substrate primitive.
10863    ///
10864    /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
10865    /// `Copy`-`u32` struct-literal onto one substrate primitive so every
10866    /// wire-up on this variant reads through one dispatch rather than
10867    /// the pre-lift four-line struct-literal block. The `rl` borrow
10868    /// threads verbatim from the caller-side `if let (Some(retries),
10869    /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
10870    /// at the sole in-crate wire-up site inside
10871    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
10872    /// limit arm; `retries` threads verbatim from the paired
10873    /// [`MeshPolicy::retries`] accessor return already destructured out
10874    /// of the same `if let` pair. `const fn` preserves the pre-lift
10875    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10876    /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
10877    /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
10878    /// the ctor path).
10879    ///
10880    /// The `rate` slot is projected through [`RateLimit::rate`] (not
10881    /// spelled out as a bare `u32` parameter) so a future widening of
10882    /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
10883    /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
10884    /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
10885    /// per-cluster `:politicas`-cap resolver projects, a promotion of
10886    /// the plain `u32` token capacity to a richer
10887    /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
10888    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
10889    /// axis comes into scope — reaches the diagnostic through one
10890    /// accessor swap rather than every wire-up in lockstep, matching
10891    /// the peer substrate-primitive-projection posture of
10892    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10893    /// projecting through [`CircuitBreaker::window`] on the sibling
10894    /// two-slot `{ window, timeout }` first cross-axis envelope),
10895    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10896    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10897    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10898    /// [`CircuitBreaker::window`] on the sibling four-slot second
10899    /// cross-axis envelope), and
10900    /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
10901    /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
10902    /// the sibling two-slot `{ retries, max_failures }` third cross-axis
10903    /// envelope). `retries` remains a bare `u32` parameter, matching
10904    /// the sibling third-arm ctor's bare `retries: u32` parameter
10905    /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
10906    /// caller-side `if let` already destructures the inner `u32` out, so
10907    /// the ctor takes the destructured scalar verbatim rather than
10908    /// re-wrapping it into an accessor call.
10909    ///
10910    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10911    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10912    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10913    /// [`MeshPolicy::validate`] gate — extended here onto the
10914    /// fourth-firing (and final) cross-axis compound variant, whose
10915    /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
10916    /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
10917    /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
10918    /// read through one substrate-primitive ctor dispatch each; the
10919    /// per-envelope compound cross-axis Policy* family closes on this
10920    /// variant.
10921    ///
10922    /// Every future consumer that wants to construct this variant
10923    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10924    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10925    /// webhook re-checking a per-tenant `:politicas` overlay's
10926    /// retries-vs-rate cross-axis invariant after a cluster-local
10927    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10928    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10929    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10930    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10931    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10932    /// shape — now reaches this variant through one call rather than
10933    /// re-inlining the open-coded struct-literal in lockstep with the
10934    /// one in-crate wire-up site.
10935    #[must_use]
10936    pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
10937        Self::PolicyRateLimitCannotAdmitRetryBurst {
10938            retries,
10939            rate: rl.rate(),
10940        }
10941    }
10942
10943    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
10944    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
10945    /// that broke the shared DNS-1123-label floor under the given
10946    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
10947    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
10948    /// struct-literal onto one substrate primitive so every wire-up on
10949    /// this variant reads through one dispatch rather than the pre-lift
10950    /// six-line struct-literal block inside
10951    /// [`validate_contrato_caixa`]'s
10952    /// [`crate::render::require_valid_dns_1123_label`]
10953    /// `|reason| …` closure.
10954    ///
10955    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
10956    /// (981060b) macro-generated ctor family
10957    /// ([`AplicacaoError::membro_caixa_invalid`],
10958    /// [`AplicacaoError::entrada_para_invalid`],
10959    /// [`AplicacaoError::entrada_host_invalid`],
10960    /// [`AplicacaoError::entrada_path_invalid`],
10961    /// [`AplicacaoError::placement_cluster_invalid`],
10962    /// [`AplicacaoError::placement_affinity_invalid`],
10963    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
10964    /// dispatch per substrate primitive on every `{ <field>: String,
10965    /// reason: String }` per-axis parser-shaped envelope" discipline
10966    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
10967    /// String, reason: String }` sibling whose extra `slot: &'static
10968    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
10969    /// on the per-`:contratos`-edge value axis and so does not fit the
10970    /// two-slot macro's arity.
10971    ///
10972    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
10973    /// (`&'static str` is `Copy`, no allocation), matching the caller-
10974    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10975    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10976    /// sole in-crate wire-up threads through. `reason: impl
10977    /// Into<String>` accepts both `&str` literals and the shared
10978    /// [`crate::render::require_valid_dns_1123_label`]-delivered
10979    /// owned-`String` return verbatim so the closure picks the ctor up
10980    /// without a per-arm wrapper transformation, matching the peer
10981    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
10982    /// Into<String>` bound. `#[must_use]` fires a compile warning at
10983    /// any wire-up that mistakenly discards the constructed error
10984    /// rather than routing it through `return Err(…)` / `.map_err(…)`
10985    /// / a closure return.
10986    ///
10987    /// Every future consumer that wants to construct this variant
10988    /// outside the current in-crate wire-up (the deferred
10989    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10990    /// per-`:contratos`-edge admission validator projecting the same
10991    /// diagnostic through the caller-facing `slot: &'static str` tag,
10992    /// a future `feira validate --contratos` per-caixa admission verb,
10993    /// an M4 per-`:contratos`-edge pre-emitter running the same
10994    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
10995    /// pair before hitting the apiserver-side selector, an M4
10996    /// per-cluster contrato-cap resolver rejecting a cross-tenant
10997    /// selector projection into the same diagnostic shape) — now
10998    /// reaches this variant through one call rather than re-inlining
10999    /// the six-line struct-literal block in lockstep with the one
11000    /// in-crate wire-up site.
11001    #[must_use]
11002    pub fn contrato_caixa_invalid(
11003        slot: &'static str,
11004        caixa: &str,
11005        reason: impl Into<String>,
11006    ) -> Self {
11007        Self::ContratoCaixaInvalid {
11008            slot,
11009            caixa: caixa.to_string(),
11010            reason: reason.into(),
11011        }
11012    }
11013
11014    /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
11015    /// offending `:contratos <slot>` (`:de` / `:para`) at which the
11016    /// caixa-reference value is the empty string. Folds the uniform
11017    /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
11018    /// one substrate primitive so the sole in-crate closure passed to
11019    /// [`crate::render::require_valid_dns_1123_label`] at
11020    /// [`validate_contrato_caixa`] on this variant reads through one
11021    /// dispatch rather than the pre-lift open-coded block. The `slot`
11022    /// label threads verbatim from the caller-side
11023    /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11024    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
11025    /// wire-up feeds through [`validate_contrato_caixa`]'s
11026    /// `slot: &'static str` parameter.
11027    ///
11028    /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
11029    /// substrate primitive on the same
11030    /// [`crate::render::require_valid_dns_1123_label`] two-closure
11031    /// cascade — the empty-arm and invalid-arm now both reach the
11032    /// `AplicacaoError` envelope through one substrate primitive per
11033    /// typed variant, closing the pair. Same shape discipline as the
11034    /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
11035    /// `{ slot: &'static str }` sibling on the `BehaviorError`
11036    /// envelope's four-arm sandboxed-lisp-path cascade
11037    /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
11038    /// onto the sibling `AplicacaoError` envelope's two-arm
11039    /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
11040    ///
11041    /// `slot` stays `&'static str` (not `&str`) — every `:contratos
11042    /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
11043    /// `const` roster carrying program-lifetime storage, matching the
11044    /// enum-field type and the [`validate_contrato_caixa`] wire-up's
11045    /// per-axis dispatch. A runtime-borrowed `&str` would silently
11046    /// downgrade the label lifetime and let a caller stash a
11047    /// non-`'static` borrow into the returned error. `#[must_use]` fires
11048    /// a compile warning at any wire-up that mistakenly discards the
11049    /// constructed error rather than routing it through `return Err(…)`
11050    /// / `.map_err(…)` / a closure return. `pub const fn` matches the
11051    /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
11052    /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
11053    /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
11054    /// at every wire-up site.
11055    ///
11056    /// Every future consumer that wants to construct this variant
11057    /// outside the current in-crate wire-up (the deferred
11058    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11059    /// per-`:contratos`-edge admission validator projecting the same
11060    /// diagnostic through the caller-facing `slot: &'static str` tag,
11061    /// a future `feira validate --contratos` per-caixa admission verb,
11062    /// an M4 per-`:contratos`-edge pre-emitter running the same
11063    /// DNS-1123-label floor's empty-arm against a caller-supplied
11064    /// `:de` / `:para` pair before hitting the apiserver-side selector,
11065    /// a per-`Caixa` overlay resolver rejecting an author-supplied
11066    /// `:contratos` overlay's empty `:de` / `:para` against a
11067    /// cluster-local snapshot) — now reaches this variant through one
11068    /// call rather than re-inlining the open-coded closure block in
11069    /// lockstep with the one in-crate wire-up site.
11070    #[must_use]
11071    pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
11072        Self::ContratoCaixaEmpty { slot }
11073    }
11074}
11075
11076// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
11077// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
11078// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
11079// substrate-primitive family per typed variant — the paired
11080// `{ <field>: String, reason: String }` two-slot sibling on
11081// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
11082// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
11083// `ContratoMissingTarget`) and the peer two-slot
11084// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
11085// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
11086// on the sibling per-`:contratos` envelopes, plus the peer four-family
11087// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
11088// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
11089// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
11090// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
11091// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
11092// sibling layout-side envelope.
11093//
11094// Every one of the seven wire-up sites — six under the per-axis
11095// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
11096// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
11097// on `EntradaParaInvalid`, `validate_placement_cluster` on
11098// `PlacementClusterInvalid`, `validate_placement_affinity` on
11099// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
11100// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
11101// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
11102// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
11103// sites at [`validate_entrada_host`] (17dd504 already folded onto the
11104// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
11105// the macro-generated ctor of the same name), opened the identical
11106// four-line `AplicacaoError::<Variant>Invalid
11107// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
11108// the local `<field>: &str` argument — the exact "same block re-inlined
11109// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
11110// same altitude the peer three `AplicacaoError` constructor families
11111// and the four peer `LayoutError` constructor families each closed on
11112// their sibling envelopes.
11113//
11114// The macro below generates one `#[must_use]` inherent constructor per
11115// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
11116// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
11117// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
11118// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
11119// pre-lift struct-literal on the same `(<field>, reason)` pair. The
11120// uniform two-field construction (`<field>: <val>.to_string()`,
11121// `reason: reason.into()`) is spelled once — inside the macro — rather
11122// than at every wire-up site. The `reason: impl Into<String>` bound
11123// accepts both `&str` literals (with or without a trailing
11124// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
11125// wire-up site changes its per-arm diagnostic shape at the lift.
11126// `#[must_use]` fires a compile warning at any wire-up that mistakenly
11127// discards the constructed error rather than routing it through
11128// `return Err(…)` / `.map_err(…)` / a closure return.
11129//
11130// Every future consumer that wants to construct one of these seven
11131// variants outside the current in-crate wire-up sites (the deferred
11132// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
11133// admission validators, a future `feira validate --<axis>` per-caixa
11134// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
11135// on `:entrada :host`, an M4 typed placement-engine per-cluster /
11136// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
11137// per-path pre-emitter) reaches the variant through one call rather
11138// than re-inlining the four-line struct-literal block in lockstep with
11139// the current in-crate wire-up sites.
11140macro_rules! aplicacao_field_reason_ctors {
11141    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
11142        impl AplicacaoError {
11143            $(
11144                #[doc = concat!(
11145                    "Construct an [`AplicacaoError::",
11146                    stringify!($variant),
11147                    "`] naming the offending `",
11148                    stringify!($field),
11149                    "` under the given `reason`. Folds the uniform ",
11150                    "`{ ",
11151                    stringify!($field),
11152                    ": ",
11153                    stringify!($field),
11154                    ".to_string(), reason: reason.into() }` two-slot ",
11155                    "construction onto one substrate primitive so every ",
11156                    "wire-up on this variant reads through one dispatch ",
11157                    "rather than the pre-lift four-line struct-literal ",
11158                    "block. `reason` accepts both `&str` literals and ",
11159                    "`format!(…)` outputs through the `impl Into<String>` ",
11160                    "bound."
11161                )]
11162                #[must_use]
11163                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
11164                    Self::$variant {
11165                        $field: $field.to_string(),
11166                        reason: reason.into(),
11167                    }
11168                }
11169            )*
11170        }
11171    };
11172}
11173
11174aplicacao_field_reason_ctors! {
11175    membro_caixa_invalid => MembroCaixaInvalid { caixa },
11176    entrada_para_invalid => EntradaParaInvalid { para },
11177    entrada_host_invalid => EntradaHostInvalid { host },
11178    entrada_path_invalid => EntradaPathInvalid { path },
11179    placement_cluster_invalid => PlacementClusterInvalid { cluster },
11180    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
11181    shard_key_invalid => ShardKeyInvalid { shard_key },
11182}
11183
11184// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
11185// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
11186// [`WitContract::target`] onto one substrate-primitive family per typed
11187// variant — the paired `{ de: String, para: String, <field>: String,
11188// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
11189// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
11190// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
11191// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
11192// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
11193// `ContratoSlotEmpty`), and the peer two-slot
11194// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
11195// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
11196// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
11197// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
11198// sibling `AplicacaoError` envelopes, plus the peer four-family
11199// `LayoutError` ctor set on the sibling layout-side envelope.
11200//
11201// Every one of the four wire-up sites — four per-`:contratos` value-
11202// shape gates inside [`WitContract::target`] (the world-ref prefix
11203// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
11204// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
11205// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
11206// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
11207// failure on `:slot`) — opened the identical five-line
11208// `let (de, para) = self.edge_pair();
11209// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
11210// <field>: <val>.to_string(), reason });` block against the local
11211// [`WitContract::edge_pair`] composite-projection accessor and the
11212// per-arm `<val>: &str` argument — the exact "same block re-inlined at
11213// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
11214// altitude the peer three `AplicacaoError` constructor families and the
11215// four peer `LayoutError` constructor families each closed on their
11216// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
11217// macro closes the last unlifted `{ de, para, <field>: String, reason:
11218// String }` four-slot envelope inside `impl WitContract`, so every
11219// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
11220// reads through this one substrate primitive.
11221//
11222// The macro below generates one `#[must_use]` inherent constructor per
11223// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
11224// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
11225// sites onto one dispatch per arm:
11226// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
11227// byte-equal to the pre-lift struct-literal on the same
11228// `(edge_pair, <val>, reason)` triple. The uniform four-field
11229// construction (`de, para` pair-destructure onto same-named fields +
11230// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
11231// once — inside the macro — rather than at every wire-up site. The
11232// `reason: impl Into<String>` bound accepts both `&str` literals and
11233// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
11234// diagnostic shape at the lift, matching the peer
11235// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
11236// envelope. `#[must_use]` fires a compile warning at any wire-up that
11237// mistakenly discards the constructed error.
11238//
11239// Every future consumer that wants to construct one of these four
11240// variants outside [`WitContract::target`] (a deferred
11241// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
11242// admission validator raising per-payload value-shape diagnostics on
11243// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
11244// future `feira validate --contratos` per-caixa admission verb, an M4
11245// typed WIT-registry-driven per-arm pre-emitter probing each declared
11246// `:endpoint` / `:subject` / `:slot` payload against a canonical
11247// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
11248// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
11249// pre-emitter probing each `:endpoint` against the same shared
11250// HTTPPathMatch grammar) reaches the variant through one call rather
11251// than re-inlining the five-line pair-destructure + struct-literal
11252// block in lockstep with the four in-crate wire-up sites.
11253macro_rules! contrato_pair_value_reason_ctors {
11254    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
11255        impl AplicacaoError {
11256            $(
11257                #[doc = concat!(
11258                    "Construct an [`AplicacaoError::",
11259                    stringify!($variant),
11260                    "`] naming the offending edge `(de, para)` pair, the ",
11261                    "per-payload `",
11262                    stringify!($field),
11263                    "` value, and the parser-shaped `reason`. Folds the ",
11264                    "uniform `{ de, para, ",
11265                    stringify!($field),
11266                    ": ",
11267                    stringify!($field),
11268                    ".to_string(), reason: reason.into() }` four-slot ",
11269                    "construction onto one substrate primitive so every ",
11270                    "wire-up on this variant reads through one dispatch ",
11271                    "rather than the pre-lift five-line pair-destructure ",
11272                    "+ struct-literal block. The `edge` pair threads ",
11273                    "verbatim from [`WitContract::edge_pair`] at the ",
11274                    "call site; `reason` accepts both `&str` literals ",
11275                    "and `format!(…)` outputs through the `impl ",
11276                    "Into<String>` bound."
11277                )]
11278                #[must_use]
11279                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
11280                    let (de, para) = edge;
11281                    Self::$variant {
11282                        de,
11283                        para,
11284                        $field: $field.to_string(),
11285                        reason: reason.into(),
11286                    }
11287                }
11288            )*
11289        }
11290    };
11291}
11292
11293contrato_pair_value_reason_ctors! {
11294    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
11295    contrato_subject_invalid => ContratoSubjectInvalid { subject },
11296    contrato_slot_invalid => ContratoSlotInvalid { slot },
11297    contrato_wit_invalid => ContratoWitInvalid { wit },
11298}
11299
11300// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
11301// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
11302// caixa-only struct-variant wire-up sites at
11303// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
11304// `:contratos :para` arms of `ContratoMemberMissing`),
11305// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
11306// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
11307// and [`validate_no_self_membership`] (one site, the parent-`:nome`
11308// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
11309// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
11310// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
11311// three variants on `{ caixa: String }` at
11312// [`crate::SupervisorSpec::validate_children`] and
11313// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
11314// `SupervisorError` envelope, extending the same "one substrate primitive per
11315// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
11316// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
11317// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
11318// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
11319// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
11320// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
11321// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
11322// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
11323// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
11324// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
11325// variants on `{ nome, caminho }`), and
11326// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
11327// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
11328// peer three `AplicacaoError` sub-family folds already lifted here
11329// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
11330// [`aplicacao_field_reason_ctors!`] 981060b,
11331// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
11332// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
11333// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
11334// [`crate::LayoutError::missing_entry`] 1b09f9d,
11335// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
11336// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
11337//
11338// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
11339// at the per-`:contratos :de`/`:para` unknown-member arms, one on
11340// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
11341// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
11342// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
11343// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
11344// three-line struct-literal against a caller-side `&str` — the exact "same
11345// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
11346// bug, on the same altitude the peer `SupervisorError` /
11347// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
11348// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
11349// their sibling envelopes. The four variants share one `{ caixa: String }`
11350// shape, so the fold routes each wire-up site through one dispatch per typed
11351// variant.
11352//
11353// The macro below generates one `#[must_use]` inherent constructor per
11354// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
11355// wire-up site collapses onto one dispatch:
11356// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
11357// on the same `&str` fixture. The uniform one-field construction
11358// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
11359// than at every wire-up site. Every constructor is `#[must_use]` so a caller
11360// who mistakenly discards the constructed error trips a compile warning at
11361// the wire-up site.
11362//
11363// Every future consumer that wants to construct one of these four variants
11364// outside the current in-crate wire-up sites — a deferred
11365// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11366// re-checking one added/renamed `:membros` entry against the sibling
11367// `:contratos` graph, a future `feira validate --membros` per-caixa admission
11368// verb re-checking each declared `:membros` entry's `:caixa` name against the
11369// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
11370// duplicate / self-referencing / unknown-membered `:contratos` entry against
11371// a cluster-local snapshot the M4 CR materializer projects — now reaches each
11372// variant through one call rather than re-inlining the three-line
11373// struct-literal in lockstep with the five in-crate wire-up sites.
11374macro_rules! aplicacao_caixa_only_ctors {
11375    ($($ctor:ident => $variant:ident),* $(,)?) => {
11376        impl AplicacaoError {
11377            $(
11378                #[doc = concat!(
11379                    "Construct an [`AplicacaoError::",
11380                    stringify!($variant),
11381                    "`] naming the offending `:membros :caixa` (or ",
11382                    "parent `:nome`, on the self-membership arm; or ",
11383                    "`:contratos :de`/`:para`, on the unknown-member ",
11384                    "arm). Folds the uniform `Self::",
11385                    stringify!($variant),
11386                    " { caixa: caixa.to_string() }` one-field ",
11387                    "struct-literal onto one substrate primitive so ",
11388                    "every wire-up on this variant reads through one ",
11389                    "dispatch rather than the pre-lift three-line ",
11390                    "open-coded struct-literal block."
11391                )]
11392                #[must_use]
11393                pub fn $ctor(caixa: &str) -> Self {
11394                    Self::$variant { caixa: caixa.to_string() }
11395                }
11396            )*
11397        }
11398    };
11399}
11400
11401aplicacao_caixa_only_ctors! {
11402    contrato_member_missing => ContratoMemberMissing,
11403    membro_versao_empty => MembroVersaoEmpty,
11404    membro_duplicate => MembroDuplicate,
11405    membro_is_self_aplicacao => MembroIsSelfAplicacao,
11406}
11407
11408// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
11409// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
11410// sites onto one substrate-primitive family per typed variant — the direct
11411// per-`:entrada :paths` value-shape sibling of the peer
11412// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
11413// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
11414// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
11415// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
11416// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
11417// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
11418// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
11419// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
11420// `:deps` envelope — every single-`String`-slot error family in caixa-core
11421// now reaches through one substrate primitive per typed variant.
11422//
11423// The three wire-up sites — one under [`validate_entrada_path`]'s
11424// leading-slash grammar arm (`EntradaPathNotAbsolute` against
11425// `path: &str`), one under the per-`:entrada :paths` loop's identical
11426// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
11427// and one under the per-`:entrada :paths` loop's dedup arm
11428// (`EntradaPathDuplicate` against the same `&String` via
11429// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
11430// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
11431// three-line struct-literal against a caller-side `&str` / `&String`, the
11432// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
11433// names as a bug. Every one of the compile-time guarantees in
11434// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
11435// start with `/` becomes a caixa-build error, not a Gateway API webhook
11436// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
11437// becomes a caixa-build error, not a silent last-writer-wins render) now
11438// routes through one dispatch per typed variant at every emit site.
11439//
11440// The macro below generates one `#[must_use]` inherent constructor per
11441// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
11442// every wire-up site onto one dispatch:
11443// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
11444// on the same `&str` fixture) or the `&String` sites through
11445// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
11446// construction (`path: path.to_string()`) is spelled once — inside the
11447// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
11448// a caller who mistakenly discards the constructed error trips a compile
11449// warning at the wire-up site.
11450//
11451// Every future consumer that wants to construct one of these two variants
11452// outside the current in-crate wire-up sites — a deferred
11453// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11454// per-`:entrada :paths` re-check against a cluster-local Gateway API
11455// snapshot, a future `feira validate --entrada` per-caixa admission verb
11456// re-checking each declared `:paths` entry against the same axes, a
11457// per-tenant per-`Aplicacao` overlay resolver rejecting a
11458// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
11459// snapshot the M4 CR materializer projects — now reaches each variant
11460// through one call rather than re-inlining the three-line struct-literal in
11461// lockstep with the three in-crate wire-up sites.
11462macro_rules! aplicacao_path_only_ctors {
11463    ($($ctor:ident => $variant:ident),* $(,)?) => {
11464        impl AplicacaoError {
11465            $(
11466                #[doc = concat!(
11467                    "Construct an [`AplicacaoError::",
11468                    stringify!($variant),
11469                    "`] naming the offending `:entrada :paths` entry. ",
11470                    "Folds the uniform `Self::",
11471                    stringify!($variant),
11472                    " { path: path.to_string() }` one-field ",
11473                    "struct-literal onto one substrate primitive so ",
11474                    "every wire-up on this variant reads through one ",
11475                    "dispatch rather than the pre-lift three-line ",
11476                    "open-coded struct-literal block."
11477                )]
11478                #[must_use]
11479                pub fn $ctor(path: &str) -> Self {
11480                    Self::$variant { path: path.to_string() }
11481                }
11482            )*
11483        }
11484    };
11485}
11486
11487aplicacao_path_only_ctors! {
11488    entrada_path_not_absolute => EntradaPathNotAbsolute,
11489    entrada_path_duplicate => EntradaPathDuplicate,
11490}
11491
11492// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
11493// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
11494// substrate-primitive family per typed variant — the per-`:politicas` copy-
11495// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
11496// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
11497// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
11498// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
11499// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
11500// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
11501// the `String`-slot axis, and the peer per-`:politicas` cross-axis
11502// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
11503// carries at line 3064 on the same M3 mesh envelope.
11504//
11505// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
11506// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
11507// { <slot> }` one-line struct-literal closure against the caller-side
11508// `<slot>: <ty>` argument that the shared
11509// [`crate::render::require_positive_bounded_u32`] /
11510// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
11511// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
11512// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
11513// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
11514// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
11515// on line 3211) — the exact "same one-line struct-literal re-inlined at every
11516// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
11517// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
11518// been folded onto a substrate primitive.
11519//
11520// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
11521// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
11522// collapsing every wire-up onto either one direct dispatch
11523// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
11524// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
11525// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
11526// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
11527// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
11528// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
11529// constructor with matching arity and signature. The `const fn` qualifier
11530// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
11531// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
11532// per-variant `$field:ident` axis re-uses the enum's canonical field name so
11533// the generated ctor's parameter name matches every wire-up's local binding
11534// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
11535// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
11536// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
11537// warning at any wire-up that mistakenly discards the constructed error, on
11538// the same footing as every sibling `AplicacaoError` / `DepError` /
11539// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
11540// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
11541// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
11542// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
11543//
11544// Every future consumer that wants to construct one of these eight variants
11545// outside [`MeshPolicy::validate`] — a deferred
11546// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
11547// checking each `:politicas` axis against a cluster-local `:politicas` cap
11548// overlay, a future per-`:contratos`-edge `:politicas` override the
11549// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
11550// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
11551// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
11552// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
11553// a future `feira validate --politicas` per-caixa admission verb re-checking
11554// each declared per-axis value against the same bounds — now reaches each
11555// variant through one call rather than re-inlining the one-line struct-
11556// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
11557// which is exactly the invariant every prior ctor-macro lift already closed
11558// on its sibling envelope. Closes the last remaining per-`:politicas`
11559// per-axis `AplicacaoError` variant family that had not yet been folded onto
11560// a substrate primitive; the compound cross-axis variants
11561// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
11562// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
11563// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
11564macro_rules! aplicacao_policy_scalar_ctors {
11565    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
11566        impl AplicacaoError {
11567            $(
11568                #[doc = concat!(
11569                    "Construct an [`AplicacaoError::",
11570                    stringify!($variant),
11571                    "`] naming the offending per-`:politicas` `",
11572                    stringify!($field),
11573                    "` scalar. Folds the uniform `Self::",
11574                    stringify!($variant),
11575                    " { ",
11576                    stringify!($field),
11577                    " }` one-field `Copy`-pass-through struct-literal onto ",
11578                    "one substrate primitive so every per-axis wire-up on ",
11579                    "this variant reads through one dispatch — as a direct ",
11580                    "call (`AplicacaoError::",
11581                    stringify!($ctor),
11582                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
11583                    "the same `Copy`-`",
11584                    stringify!($ty),
11585                    "` fixture) or as a bare function pointer in the ",
11586                    "`impl FnOnce(",
11587                    stringify!($ty),
11588                    ") -> AplicacaoError` bracket-closure slot every ",
11589                    "`crate::render::require_positive_bounded_*` / ",
11590                    "`crate::render::require_positive_canonical_bounded_*` ",
11591                    "gate carries — rather than the pre-lift open-coded ",
11592                    "one-line closure over the same one-field struct-",
11593                    "literal. `const fn` preserves the `Copy`-pass-through's ",
11594                    "zero-runtime-work property verbatim."
11595                )]
11596                #[must_use]
11597                pub const fn $ctor($field: $ty) -> Self {
11598                    Self::$variant { $field }
11599                }
11600            )*
11601        }
11602    };
11603}
11604
11605aplicacao_policy_scalar_ctors! {
11606    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
11607    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
11608    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
11609    policy_breaker_max_failures_exceeds_cap =>
11610        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
11611    policy_breaker_window_not_canonical =>
11612        PolicyBreakerWindowNotCanonical { window: Duration },
11613    policy_breaker_window_exceeds_cap =>
11614        PolicyBreakerWindowExceedsCap { window: Duration },
11615    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
11616    policy_rate_limit_window_not_canonical =>
11617        PolicyRateLimitWindowNotCanonical { window: Duration },
11618}
11619
11620#[cfg(test)]
11621mod tests {
11622    use super::*;
11623
11624    fn membro(name: &str, ver: &str) -> Membro {
11625        Membro {
11626            caixa: name.into(),
11627            versao: ver.into(),
11628        }
11629    }
11630
11631    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
11632        WitContract {
11633            de: de.into(),
11634            para: para.into(),
11635            wit: "wasi:http/proxy".into(),
11636            endpoint: Some(ep.into()),
11637            subject: None,
11638            slot: None,
11639        }
11640    }
11641
11642    fn three_member_spec() -> AplicacaoSpec {
11643        AplicacaoSpec {
11644            membros: vec![
11645                membro("catalog", "^0.1"),
11646                membro("cart", "^0.1"),
11647                membro("payment", "^0.2"),
11648            ],
11649            contratos: vec![
11650                contract_http("cart", "catalog", "/products/:id"),
11651                contract_http("cart", "payment", "/charge"),
11652            ],
11653            politicas: MeshPolicy {
11654                timeout: Some(Duration::from_secs(30)),
11655                retries: Some(3),
11656                mtls_required: Some(true),
11657                ..Default::default()
11658            },
11659            placement: Placement {
11660                estrategia: PlacementStrategy::Replicated,
11661                clusters: vec!["rio".into(), "mar".into()],
11662                affinity: Some("data-locality".into()),
11663                shard_key: None,
11664            },
11665            entrada: Some(Entrada {
11666                host: "checkout.quero.cloud".into(),
11667                para: "cart".into(),
11668                paths: vec!["/api/cart".into(), "/api/products".into()],
11669                port: 8080,
11670            }),
11671        }
11672    }
11673
11674    #[test]
11675    fn happy_path_validates() {
11676        three_member_spec().validate().unwrap();
11677    }
11678
11679    #[test]
11680    fn rejects_empty_membros() {
11681        let mut s = three_member_spec();
11682        s.membros = vec![];
11683        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
11684    }
11685
11686    #[test]
11687    fn rejects_empty_membro_caixa() {
11688        // A `:caixa ""` entry has no name to render into programs.yaml
11689        // and no caixa.lisp to resolve at lacre time.
11690        let mut s = three_member_spec();
11691        s.membros[1].caixa = String::new();
11692        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
11693    }
11694
11695    #[test]
11696    fn rejects_empty_membro_versao() {
11697        // A `:versao ""` entry can't pin a semver constraint, so the
11698        // lacre pipeline fails far from the source.
11699        let mut s = three_member_spec();
11700        s.membros[2].versao = String::new();
11701        let err = s.validate().unwrap_err();
11702        assert!(
11703            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
11704            "got {err:?}"
11705        );
11706    }
11707
11708    #[test]
11709    fn rejects_duplicate_membro_caixa() {
11710        // Two `:membros` entries with the same `:caixa` collapse to one
11711        // node in the membership HashSet, which masks `:contratos`
11712        // membership errors and produces duplicate programs.yaml entries.
11713        let mut s = three_member_spec();
11714        s.membros.push(membro("cart", "^0.2"));
11715        let err = s.validate().unwrap_err();
11716        assert!(
11717            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11718            "got {err:?}"
11719        );
11720    }
11721
11722    #[test]
11723    fn rejects_invalid_membro_versao_requirement() {
11724        // The fail-before-pass-after pin: a non-empty but malformed
11725        // semver requirement (`"^bad-version"`) silently passed
11726        // `validate()` on every pre-gate codebase because the prior
11727        // shape only refused the empty string. The parse failure
11728        // surfaced far downstream at lacre-resolve time with a
11729        // `semver::Error` that didn't name which `:membros` entry
11730        // carried the typo. The new gate moves the check to caixa-build
11731        // time at the source caixa.lisp.
11732        let mut s = three_member_spec();
11733        s.membros[2].versao = "^bad-version".into();
11734        let err = s.validate().unwrap_err();
11735        assert!(
11736            matches!(
11737                err,
11738                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11739                    if caixa == "payment" && versao == "^bad-version"
11740            ),
11741            "got {err:?}"
11742        );
11743    }
11744
11745    #[test]
11746    fn rejects_membro_versao_with_double_caret_typo() {
11747        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
11748        // Cargo-shaped requirement on first glance but fails the parser
11749        // because semver doesn't accept stacked operators. Pin this
11750        // adjacent-shape footgun explicitly so a future relaxation that
11751        // accepts "looks-canonical-but-isn't" forms surfaces here.
11752        let mut s = three_member_spec();
11753        s.membros[0].versao = "^^0.1".into();
11754        let err = s.validate().unwrap_err();
11755        assert!(
11756            matches!(
11757                err,
11758                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11759                    if caixa == "catalog" && versao == "^^0.1"
11760            ),
11761            "got {err:?}"
11762        );
11763    }
11764
11765    #[test]
11766    fn rejects_membro_versao_with_v_prefixed_tag() {
11767        // `"v0.1"` is the canonical "git-tag-shape leaking into the
11768        // semver requirement slot" typo — an author copies the
11769        // publish-side git-tag string verbatim into `:versao`, but
11770        // Cargo's semver parser rejects the leading `v` (only digits +
11771        // canonical operators are valid in the major-version
11772        // position). The gate's diagnostic names which member entry
11773        // carried the v-prefix so the fix is one edit, not a grep
11774        // through every member's `:versao`. (Note: bare `x`-glob
11775        // shorthands like `^0.1.x` are *accepted* by the semver crate
11776        // as an `*` wildcard on the patch axis — they're a Cargo-side
11777        // valid shape, not a typo, so the gate intentionally lets them
11778        // through.)
11779        let mut s = three_member_spec();
11780        s.membros[1].versao = "v0.1".into();
11781        let err = s.validate().unwrap_err();
11782        assert!(
11783            matches!(
11784                err,
11785                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11786                    if caixa == "cart" && versao == "v0.1"
11787            ),
11788            "got {err:?}"
11789        );
11790    }
11791
11792    #[test]
11793    fn accepts_canonical_membro_versao_forms() {
11794        // The four Cargo-shaped requirement forms `:deps :versao`
11795        // already accepts via `crate::parse_requirement` must pass the
11796        // membros gate without re-validating at the resolver layer.
11797        // Pin every leg so a future tightening of the canonical set
11798        // surfaces here as a test failure.
11799        for form in [
11800            "^0.1",      // caret — minor-range pin (the most common shape)
11801            "~0.1.2",    // tilde — patch-range pin
11802            "0.1.0",     // exact — single-version pin
11803            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
11804            ">=0.1, <2", // multi-range — comma-separated comparators
11805        ] {
11806            let mut s = three_member_spec();
11807            for m in &mut s.membros {
11808                m.versao = form.into();
11809            }
11810            s.validate()
11811                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11812        }
11813    }
11814
11815    #[test]
11816    fn membro_versao_empty_takes_precedence_over_invalid() {
11817        // Order pin: the existing `MembroVersaoEmpty` diagnostic
11818        // (which doesn't try to parse) fires before the new
11819        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
11820        // `:versao` keeps its narrower error message — `parse_requirement`
11821        // would also reject `""`, but the empty-string arm is the more
11822        // self-locating diagnostic for the author.
11823        let mut s = three_member_spec();
11824        s.membros[1].versao = String::new();
11825        let err = s.validate().unwrap_err();
11826        assert!(
11827            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
11828            "got {err:?}"
11829        );
11830    }
11831
11832    #[test]
11833    fn membro_versao_invalid_fires_before_duplicate_check() {
11834        // Order pin: a malformed requirement on a non-duplicate entry
11835        // surfaces *its own* diagnostic (which names the offending
11836        // `:versao` string), even when a later entry would otherwise
11837        // collapse onto an earlier name. The per-entry shape gate runs
11838        // inline before the duplicate-key insert, parallel to
11839        // `membros_validation_runs_before_contratos_membership_check`
11840        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
11841        let mut s = three_member_spec();
11842        s.membros[0].versao = "^bad".into();
11843        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11844        let err = s.validate().unwrap_err();
11845        assert!(
11846            matches!(
11847                err,
11848                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
11849            ),
11850            "got {err:?}"
11851        );
11852    }
11853
11854    #[test]
11855    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
11856        // The diagnostic-shape pin: the error names the offending
11857        // `:versao` value verbatim so the author can grep their
11858        // caixa.lisp without re-running the build, and carries a
11859        // non-empty `reason` from `semver::VersionReq::parse` so the
11860        // parser's own wording flows through to the diagnostic.
11861        let mut s = three_member_spec();
11862        s.membros[2].versao = "not-a-req".into();
11863        let err = s.validate().unwrap_err();
11864        let AplicacaoError::MembroVersaoInvalid {
11865            caixa,
11866            versao,
11867            reason,
11868        } = err
11869        else {
11870            panic!("expected MembroVersaoInvalid, got other variant");
11871        };
11872        assert_eq!(caixa, "payment");
11873        assert_eq!(versao, "not-a-req");
11874        assert!(
11875            !reason.is_empty(),
11876            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
11877        );
11878    }
11879
11880    #[test]
11881    fn membro_versao_invalid_runs_before_contratos_check() {
11882        // A malformed `:versao` on any member must surface its own
11883        // diagnostic (which names *which* member to fix) before any
11884        // `:contratos` membership lookup raises `ContratoMemberMissing`.
11885        // The `:contratos` gate runs after `validate_membros`, so this
11886        // is structurally guaranteed — pin it explicitly so a future
11887        // refactor that reorders the gates surfaces here.
11888        let mut s = three_member_spec();
11889        s.membros[1].versao = "^^0.1".into();
11890        // Add a contrato whose `:para` doesn't exist — would normally
11891        // raise ContratoMemberMissing at the membership lookup, but
11892        // the membros gate must fire first.
11893        s.contratos
11894            .push(contract_http("cart", "phantom", "/never-reached"));
11895        let err = s.validate().unwrap_err();
11896        assert!(
11897            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
11898            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
11899        );
11900    }
11901
11902    #[test]
11903    fn membros_validation_runs_before_contratos_membership_check() {
11904        // If `:membros` carries a duplicate, the membership-collapse
11905        // would silently accept a `:contratos :para "phantom"` so long
11906        // as some entry hashes to "phantom". Pinning order: the
11907        // duplicate-membros error fires first, regardless of whether
11908        // contratos reference real members.
11909        let mut s = three_member_spec();
11910        s.membros = vec![
11911            membro("cart", "^0.1"),
11912            membro("cart", "^0.2"),
11913            membro("catalog", "^0.1"),
11914            membro("payment", "^0.1"),
11915        ];
11916        let err = s.validate().unwrap_err();
11917        assert!(
11918            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11919            "got {err:?}"
11920        );
11921    }
11922
11923    #[test]
11924    fn distinct_membros_validate() {
11925        // Pin the happy-path: every `:membros` entry has a non-empty
11926        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
11927        // The fixture already satisfies this; this test makes the
11928        // invariant explicit so a future refactor of the fixture can't
11929        // silently break the guarantee.
11930        three_member_spec().validate().unwrap();
11931    }
11932
11933    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
11934
11935    #[test]
11936    fn rejects_membro_caixa_with_uppercase() {
11937        // The canonical "I copied the Servico's display name verbatim"
11938        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
11939        // but author tools often round-trip a TitleCase or CamelCase
11940        // identifier from an ADR or a sketch. Pin the diagnostic names
11941        // the offending name and suggests the lower-cased fix in one
11942        // edit, mirroring the `rejects_entrada_host_with_uppercase`
11943        // gate's shape (c7d05ec).
11944        let mut s = three_member_spec();
11945        s.membros[1].caixa = "Cart".into();
11946        let err = s.validate().unwrap_err();
11947        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11948            panic!("expected MembroCaixaInvalid, got other variant");
11949        };
11950        assert_eq!(caixa, "Cart");
11951        assert!(
11952            reason.contains("uppercase"),
11953            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11954        );
11955        assert!(
11956            reason.contains("\"cart\""),
11957            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
11958        );
11959    }
11960
11961    #[test]
11962    fn rejects_membro_caixa_with_underscore() {
11963        // The canonical "I'm thinking of a Python module / Postgres
11964        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
11965        // label schema. K8s rejects `metadata.name: my_cart` at admission
11966        // time with an opaque `field is invalid` (no source-citing
11967        // diagnostic). The gate moves it to caixa-build time.
11968        let mut s = three_member_spec();
11969        s.membros[0].caixa = "my_cart".into();
11970        let err = s.validate().unwrap_err();
11971        assert!(
11972            matches!(
11973                err,
11974                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11975                    if caixa == "my_cart" && reason.contains('_')
11976            ),
11977            "got {err:?}"
11978        );
11979    }
11980
11981    #[test]
11982    fn rejects_membro_caixa_with_dot() {
11983        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
11984        // subdomain — even though K8s `metadata.name` itself accepts
11985        // dots (DNS-1123 subdomain rule), this string also lands as a
11986        // K8s Service name (DNS-1035 label — no dots) and as a label
11987        // value on identity-based Cilium selectors. The strictest floor
11988        // among the use sites wins. The "I want to namespace my member
11989        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
11990        let mut s = three_member_spec();
11991        s.membros[2].caixa = "team.cart".into();
11992        let err = s.validate().unwrap_err();
11993        assert!(
11994            matches!(
11995                err,
11996                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11997                    if caixa == "team.cart" && reason.contains('.')
11998            ),
11999            "got {err:?}"
12000        );
12001    }
12002
12003    #[test]
12004    fn rejects_membro_caixa_with_leading_hyphen() {
12005        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
12006        // with an alphanumeric. The K8s apiserver rejects `-cart`
12007        // outright; the renderer would emit a `metadata.name: "-cart"`
12008        // that fails admission far from the source caixa.lisp.
12009        let mut s = three_member_spec();
12010        s.membros[0].caixa = "-cart".into();
12011        let err = s.validate().unwrap_err();
12012        assert!(
12013            matches!(
12014                err,
12015                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12016                    if caixa == "-cart" && reason.contains("start and end")
12017            ),
12018            "got {err:?}"
12019        );
12020    }
12021
12022    #[test]
12023    fn rejects_membro_caixa_with_trailing_hyphen() {
12024        // The symmetric arm of the boundary rule. Pin separately so
12025        // both ends of the label are covered against a future relaxation
12026        // that only checks one boundary.
12027        let mut s = three_member_spec();
12028        s.membros[1].caixa = "cart-".into();
12029        let err = s.validate().unwrap_err();
12030        assert!(
12031            matches!(
12032                err,
12033                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12034                    if caixa == "cart-"
12035            ),
12036            "got {err:?}"
12037        );
12038    }
12039
12040    #[test]
12041    fn rejects_membro_caixa_with_unicode() {
12042        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12043        // (`xn--…`) by the author before it reaches K8s. The byte-by-
12044        // byte ASCII validity check rejects multi-byte UTF-8 sequences
12045        // by the first byte that fails the `[a-z0-9-]` predicate.
12046        let mut s = three_member_spec();
12047        s.membros[2].caixa = "café".into();
12048        let err = s.validate().unwrap_err();
12049        assert!(
12050            matches!(
12051                err,
12052                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12053                    if caixa == "café"
12054            ),
12055            "got {err:?}"
12056        );
12057    }
12058
12059    #[test]
12060    fn rejects_membro_caixa_with_whitespace() {
12061        // Whitespace is the canonical "I pasted from a sketch / doc"
12062        // footgun. The apiserver rejects every `metadata.name` value
12063        // carrying whitespace; pin the gate fires at the right boundary.
12064        let mut s = three_member_spec();
12065        s.membros[0].caixa = "my cart".into();
12066        let err = s.validate().unwrap_err();
12067        assert!(
12068            matches!(
12069                err,
12070                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12071                    if caixa == "my cart"
12072            ),
12073            "got {err:?}"
12074        );
12075    }
12076
12077    #[test]
12078    fn rejects_membro_caixa_too_long() {
12079        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
12080        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
12081        // exactly. The gate's reason names both the cap and the actual
12082        // length so the author can shorten in one edit.
12083        let mut s = three_member_spec();
12084        let too_long = "a".repeat(64);
12085        s.membros[1].caixa = too_long.clone();
12086        let err = s.validate().unwrap_err();
12087        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12088            panic!("expected MembroCaixaInvalid");
12089        };
12090        assert_eq!(caixa, too_long);
12091        assert!(
12092            reason.contains("63") && reason.contains("64"),
12093            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
12094        );
12095    }
12096
12097    #[test]
12098    fn membro_caixa_max_length_validates() {
12099        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
12100        // so a future tightening (e.g. dropping to 62) surfaces here as
12101        // a regression, mirroring `entrada_host_max_length_validates`
12102        // (c7d05ec).
12103        let mut s = three_member_spec();
12104        s.membros[2].caixa = "a".repeat(63);
12105        s.entrada.as_mut().unwrap().para = "a".repeat(63);
12106        // remove contratos referencing the renamed member; they'd
12107        // raise ContratoMemberMissing otherwise
12108        s.contratos
12109            .retain(|c| c.de != "payment" && c.para != "payment");
12110        s.validate().unwrap();
12111    }
12112
12113    #[test]
12114    fn accepts_canonical_membro_caixa_forms() {
12115        // The DNS-1123 label shapes a caixa author is realistically
12116        // going to write: single-word lowercase, hyphen-joined, ending
12117        // in a digit-suffixed version (`cart-v2`), starting with a
12118        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
12119        // DNS-1035 which requires a letter at position 0), single-
12120        // character (`a` — boundary). Pin every leg so a future
12121        // tightening that bans (e.g.) digit-start identifiers surfaces
12122        // here.
12123        for form in [
12124            "checkout",
12125            "cart",
12126            "cart-v2",
12127            "a",
12128            "c0",
12129            "3rd-party-shim",
12130            "x-1-2-3-4",
12131        ] {
12132            let mut s = three_member_spec();
12133            // Renaming a member also requires updating downstream refs;
12134            // drop everything else and rebuild a minimal spec around
12135            // just the one renamed member.
12136            s.membros = vec![membro(form, "^0.1")];
12137            s.contratos = vec![];
12138            s.entrada = None;
12139            s.validate()
12140                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
12141        }
12142    }
12143
12144    #[test]
12145    fn membro_caixa_empty_takes_precedence_over_invalid() {
12146        // Order pin: the existing `MembroCaixaEmpty` diagnostic
12147        // (which doesn't try to parse) fires before the new
12148        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
12149        // `:caixa` keeps its narrower error message — the new gate
12150        // would also reject `""`, but the empty-string arm is the more
12151        // self-locating diagnostic for the author. Mirrors the
12152        // `entrada_host_empty_takes_precedence_over_invalid` pin
12153        // (c7d05ec).
12154        let mut s = three_member_spec();
12155        s.membros[1].caixa = String::new();
12156        let err = s.validate().unwrap_err();
12157        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
12158    }
12159
12160    #[test]
12161    fn membro_caixa_invalid_fires_before_versao_check() {
12162        // Order pin: an invalid-shape `:caixa` surfaces *its own*
12163        // diagnostic (which names the offending caixa name), even when
12164        // the same entry's `:versao` is also empty/invalid. The shape
12165        // gate runs first because the diagnostic is more self-locating —
12166        // an empty/invalid `:versao` on an invalid-shape caixa name is
12167        // a downstream-fix-after-the-caixa-rename concern.
12168        let mut s = three_member_spec();
12169        s.membros[1].caixa = "Cart".into();
12170        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
12171        let err = s.validate().unwrap_err();
12172        assert!(
12173            matches!(
12174                err,
12175                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
12176            ),
12177            "got {err:?}"
12178        );
12179    }
12180
12181    #[test]
12182    fn membro_caixa_invalid_fires_before_duplicate_check() {
12183        // Order pin: a malformed-shape `:caixa` on an earlier entry
12184        // surfaces *its own* diagnostic, even when a later entry would
12185        // otherwise collapse onto a duplicate name. The per-entry shape
12186        // gate runs inline before the duplicate-key insert, parallel
12187        // to `membro_versao_invalid_fires_before_duplicate_check`.
12188        let mut s = three_member_spec();
12189        s.membros[0].caixa = "Catalog".into();
12190        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
12191        let err = s.validate().unwrap_err();
12192        assert!(
12193            matches!(
12194                err,
12195                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
12196            ),
12197            "got {err:?}"
12198        );
12199    }
12200
12201    #[test]
12202    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
12203        // The diagnostic-shape pin: the error names the offending
12204        // `:caixa` value verbatim so the author can grep their
12205        // caixa.lisp without re-running the build, and carries a
12206        // non-empty `reason` naming the specific violation. Same
12207        // shape every typed-shape gate enshrines (c7d05ec's
12208        // `entrada_host_diagnostic_carries_offending_host`,
12209        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
12210        let mut s = three_member_spec();
12211        s.membros[2].caixa = "BAD_NAME".into();
12212        let err = s.validate().unwrap_err();
12213        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12214            panic!("expected MembroCaixaInvalid");
12215        };
12216        assert_eq!(caixa, "BAD_NAME");
12217        assert!(
12218            !reason.is_empty(),
12219            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
12220        );
12221    }
12222
12223    #[test]
12224    fn rejects_contrato_with_unknown_de() {
12225        let mut s = three_member_spec();
12226        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12227        let err = s.validate().unwrap_err();
12228        assert!(
12229            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
12230        );
12231    }
12232
12233    #[test]
12234    fn rejects_contrato_with_unknown_para() {
12235        let mut s = three_member_spec();
12236        s.contratos.push(contract_http("cart", "phantom", "/x"));
12237        let err = s.validate().unwrap_err();
12238        assert!(
12239            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
12240        );
12241    }
12242
12243    #[test]
12244    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
12245        // The read-path pin: the phantom-`:de` refusal arm's
12246        // `ContratoMemberMissing.caixa` carrier must be observed through
12247        // the lifted [`WitContract::source`] accessor, not the raw
12248        // `.de.clone()` field-access `String`-carry. Peer of the sibling
12249        // per-`:contratos` self-loop arm's `.source().to_string()` /
12250        // `.world_ref().to_string()` `String`-carry sites the earlier
12251        // convergence lifted onto the same accessor pair. A future
12252        // silent detour that reintroduced the raw `.de.clone()` at the
12253        // wrap envelope while the shape-gate and membership lookup
12254        // routed through the accessor would surface here as a byte-equal
12255        // miss between the fired diagnostic's `caixa:` field and the
12256        // offending edge's `.source()` — pinning the accessor as the
12257        // sole read path across the phantom-name refusal arm's arg +
12258        // wrap-envelope emit surface.
12259        let mut s = three_member_spec();
12260        let phantom = contract_http("phantom", "catalog", "/x");
12261        s.contratos.push(phantom.clone());
12262        let err = s.validate().unwrap_err();
12263        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
12264            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
12265        };
12266        assert_eq!(
12267            caixa,
12268            phantom.source(),
12269            "ContratoMemberMissing.caixa on the phantom-:de arm must \
12270             byte-equal WitContract::source — the wrap envelope must \
12271             route through the lifted accessor rather than the raw \
12272             .de.clone() field-access String-carry"
12273        );
12274    }
12275
12276    #[test]
12277    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
12278        // The symmetric read-path pin on the `:para` phantom-name
12279        // refusal arm — same shape as the sibling `:de` pin above but
12280        // on the callee-Servico axis. Pins the wrap envelope's
12281        // `caixa:` field is observed through the lifted
12282        // [`WitContract::destination`] accessor, not the raw
12283        // `.para.clone()` field-access `String`-carry.
12284        let mut s = three_member_spec();
12285        let phantom = contract_http("cart", "phantom", "/x");
12286        s.contratos.push(phantom.clone());
12287        let err = s.validate().unwrap_err();
12288        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
12289            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
12290        };
12291        assert_eq!(
12292            caixa,
12293            phantom.destination(),
12294            "ContratoMemberMissing.caixa on the phantom-:para arm must \
12295             byte-equal WitContract::destination — the wrap envelope \
12296             must route through the lifted accessor rather than the raw \
12297             .para.clone() field-access String-carry"
12298        );
12299    }
12300
12301    #[test]
12302    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
12303        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
12304        // refusal arm — the `validate_contrato_caixa` arg must be
12305        // observed through the lifted [`WitContract::source`] accessor,
12306        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
12307        // value routes through the shared
12308        // [`crate::render::require_valid_dns_1123_label`] floor with the
12309        // accessor-projected value; the fired
12310        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
12311        // the offending edge's `.source()`, pinning that the arg + the
12312        // downstream `caixa: caixa.to_string()` wrap route through the
12313        // same accessor's read path.
12314        let mut s = three_member_spec();
12315        let malformed = contract_http("BAD_NAME", "catalog", "/x");
12316        s.contratos.push(malformed.clone());
12317        let err = s.validate().unwrap_err();
12318        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
12319            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
12320        };
12321        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
12322        assert_eq!(
12323            caixa,
12324            malformed.source(),
12325            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
12326             byte-equal WitContract::source — the shape-gate arg + wrap \
12327             envelope must route through the lifted accessor rather \
12328             than the raw &c.de &String-borrow"
12329        );
12330    }
12331
12332    #[test]
12333    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
12334        // Symmetric arm to the sibling `:de` malformed-shape pin above,
12335        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
12336        // route through the lifted [`WitContract::destination`]
12337        // accessor. `:para` runs after the `:de` shape gate in the
12338        // canonical edge-direction order, so the `:de` value must be
12339        // well-shaped for the `:para` gate to fire — the `cart` :de is
12340        // canonical.
12341        let mut s = three_member_spec();
12342        let malformed = contract_http("cart", "BAD_NAME", "/x");
12343        s.contratos.push(malformed.clone());
12344        let err = s.validate().unwrap_err();
12345        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
12346            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
12347        };
12348        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
12349        assert_eq!(
12350            caixa,
12351            malformed.destination(),
12352            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
12353             byte-equal WitContract::destination — the shape-gate arg + \
12354             wrap envelope must route through the lifted accessor \
12355             rather than the raw &c.para &String-borrow"
12356        );
12357    }
12358
12359    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
12360
12361    #[test]
12362    fn rejects_contrato_de_empty() {
12363        // `:de ""` previously fell through to `ContratoMemberMissing`
12364        // (with `caixa: ""`) because the validated `:membros :caixa`
12365        // set never contains the empty string. The narrower
12366        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
12367        // the offending slot.
12368        let mut s = three_member_spec();
12369        s.contratos.push(contract_http("", "catalog", "/x"));
12370        let err = s.validate().unwrap_err();
12371        assert_eq!(
12372            err,
12373            AplicacaoError::ContratoCaixaEmpty {
12374                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12375            },
12376            "got {err:?}"
12377        );
12378    }
12379
12380    #[test]
12381    fn rejects_contrato_para_empty() {
12382        // Symmetric arm to `:de ""` — `:para ""` previously fell
12383        // through to `ContratoMemberMissing { caixa: "" }`.
12384        let mut s = three_member_spec();
12385        s.contratos.push(contract_http("cart", "", "/x"));
12386        let err = s.validate().unwrap_err();
12387        assert_eq!(
12388            err,
12389            AplicacaoError::ContratoCaixaEmpty {
12390                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12391            },
12392            "got {err:?}"
12393        );
12394    }
12395
12396    #[test]
12397    fn rejects_contrato_de_with_uppercase() {
12398        // The canonical "I copied the Servico's TitleCase display
12399        // name from an ADR" typo. Until this gate landed `:de "Cart"`
12400        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
12401        // as "this caixa isn't in `:membros`" when the root cause is
12402        // "this `:de` value's shape can never legitimately match a
12403        // validated member (DNS-1123 labels are lowercase)". The
12404        // narrower diagnostic names the offending slot, the value
12405        // verbatim, and the parser-shaped reason.
12406        let mut s = three_member_spec();
12407        s.contratos.push(contract_http("Cart", "catalog", "/x"));
12408        let err = s.validate().unwrap_err();
12409        let AplicacaoError::ContratoCaixaInvalid {
12410            slot,
12411            caixa,
12412            reason,
12413        } = err
12414        else {
12415            panic!("expected ContratoCaixaInvalid, got other variant");
12416        };
12417        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
12418        assert_eq!(caixa, "Cart");
12419        assert!(
12420            reason.contains("uppercase"),
12421            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12422        );
12423    }
12424
12425    #[test]
12426    fn rejects_contrato_para_with_underscore() {
12427        // The canonical "I'm thinking of a Python module" leak —
12428        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12429        // Pin the `:para` axis surfaces the same diagnostic shape as
12430        // the `:de` axis on the underscore violation.
12431        let mut s = three_member_spec();
12432        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
12433        let err = s.validate().unwrap_err();
12434        assert!(
12435            matches!(
12436                err,
12437                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12438                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
12439            ),
12440            "got {err:?}"
12441        );
12442    }
12443
12444    #[test]
12445    fn rejects_contrato_de_with_dot() {
12446        // A `:contratos :de` value is a single DNS-1123 *label*, not
12447        // a subdomain — mirroring the `:membros :caixa` floor. The
12448        // strictest floor among the use sites wins.
12449        let mut s = three_member_spec();
12450        s.contratos
12451            .push(contract_http("team.cart", "catalog", "/x"));
12452        let err = s.validate().unwrap_err();
12453        assert!(
12454            matches!(
12455                err,
12456                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12457                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
12458            ),
12459            "got {err:?}"
12460        );
12461    }
12462
12463    #[test]
12464    fn rejects_contrato_para_with_unicode() {
12465        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12466        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
12467        // validity check rejects multi-byte UTF-8 by the first
12468        // non-`[a-z0-9-]` byte.
12469        let mut s = three_member_spec();
12470        s.contratos.push(contract_http("cart", "café", "/x"));
12471        let err = s.validate().unwrap_err();
12472        assert!(
12473            matches!(
12474                err,
12475                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12476                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
12477            ),
12478            "got {err:?}"
12479        );
12480    }
12481
12482    #[test]
12483    fn rejects_contrato_de_with_leading_hyphen() {
12484        // DNS-1123 boundary rule: labels must start and end with an
12485        // alphanumeric. K8s rejects `-cart` outright; the narrower
12486        // shape diagnostic now names the violation at caixa-build
12487        // time rather than the misframed membership-lookup arm.
12488        let mut s = three_member_spec();
12489        s.contratos.push(contract_http("-cart", "catalog", "/x"));
12490        let err = s.validate().unwrap_err();
12491        assert!(
12492            matches!(
12493                err,
12494                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12495                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
12496            ),
12497            "got {err:?}"
12498        );
12499    }
12500
12501    #[test]
12502    fn contrato_de_empty_takes_precedence_over_invalid() {
12503        // Order pin: the `ContratoCaixaEmpty` arm fires before the
12504        // `ContratoCaixaInvalid` parse-side arm — same empty-first
12505        // cascade `validate_membro_caixa` / `validate_placement_cluster`
12506        // / `validate_entrada_host` already establish on their peer
12507        // name axes. The empty string is a structurally distinct
12508        // authoring footgun (the author left the field blank, vs.
12509        // typed a malformed value), so it gets its own diagnostic.
12510        let mut s = three_member_spec();
12511        s.contratos.push(contract_http("", "catalog", "/x"));
12512        let err = s.validate().unwrap_err();
12513        assert_eq!(
12514            err,
12515            AplicacaoError::ContratoCaixaEmpty {
12516                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12517            }
12518        );
12519    }
12520
12521    #[test]
12522    fn contrato_de_shape_fires_before_para_shape() {
12523        // Per-axis order pin: within one `:contratos` entry, the `:de`
12524        // shape gate fires before the `:para` shape gate — same
12525        // edge-direction order the existing `ContratoMemberMissing` /
12526        // `ContratoSelfLoop` / target-dispatch checks use, so the
12527        // diagnostic for a contract with both `:de` and `:para`
12528        // malformed is stable. Authors fixing the surfaced `:de`
12529        // first will see `:para`'s diagnostic on re-run.
12530        let mut s = three_member_spec();
12531        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
12532        let err = s.validate().unwrap_err();
12533        assert!(
12534            matches!(
12535                err,
12536                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12537                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
12538            ),
12539            "got {err:?}"
12540        );
12541    }
12542
12543    #[test]
12544    fn contrato_shape_fires_before_membership_lookup() {
12545        // The load-bearing pin: an invalid-shape `:de` surfaces its
12546        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
12547        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
12548        // an invalid-shape `:de` could never legitimately match any
12549        // member — the prior `ContratoMemberMissing` diagnostic was
12550        // a structural impossibility framed as a graph-membership
12551        // failure. The shape gate now routes every such input through
12552        // the narrower self-locating diagnostic.
12553        let mut s = three_member_spec();
12554        s.contratos.push(contract_http("Cart", "catalog", "/x"));
12555        let err = s.validate().unwrap_err();
12556        assert!(
12557            matches!(
12558                err,
12559                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
12560            ),
12561            "got {err:?}"
12562        );
12563        // And the symmetric case: an invalid-shape `:para` surfaces
12564        // its own diagnostic too, even when `:de` is well-shaped.
12565        let mut s = three_member_spec();
12566        s.contratos.push(contract_http("cart", "Catalog", "/x"));
12567        let err = s.validate().unwrap_err();
12568        assert!(
12569            matches!(
12570                err,
12571                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
12572            ),
12573            "got {err:?}"
12574        );
12575    }
12576
12577    #[test]
12578    fn contrato_shape_fires_before_self_edge_check() {
12579        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
12580        // bugs: the shape violation (uppercase) and the self-edge
12581        // violation. The narrower per-axis shape diagnostic surfaces
12582        // first because fixing the shape may reveal that the author
12583        // also meant to point `:para` at a different member — the
12584        // self-edge framing is only useful once both endpoints have
12585        // valid shape.
12586        let mut s = three_member_spec();
12587        s.contratos.push(contract_http("Cart", "Cart", "/x"));
12588        let err = s.validate().unwrap_err();
12589        assert!(
12590            matches!(
12591                err,
12592                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12593                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
12594            ),
12595            "got {err:?}"
12596        );
12597    }
12598
12599    #[test]
12600    fn contrato_well_shaped_phantom_still_raises_member_missing() {
12601        // Strict-improvement pin: a well-shaped `:de` that simply
12602        // isn't in `:membros` (a phantom reference — author meant
12603        // to add the member but didn't, or renamed and missed an
12604        // update) still surfaces `ContratoMemberMissing`, unchanged.
12605        // The shape gate only intercepts inputs that could never
12606        // legitimately match a validated member; legitimately-shaped
12607        // phantom references remain on the graph-membership axis.
12608        let mut s = three_member_spec();
12609        s.contratos
12610            .push(contract_http("phantom-shim", "catalog", "/x"));
12611        let err = s.validate().unwrap_err();
12612        assert!(
12613            matches!(
12614                err,
12615                AplicacaoError::ContratoMemberMissing { ref caixa }
12616                    if caixa == "phantom-shim"
12617            ),
12618            "got {err:?}"
12619        );
12620    }
12621
12622    #[test]
12623    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
12624        // The diagnostic-shape pin: the error names the offending
12625        // slot (`:de` or `:para`) verbatim and the offending value
12626        // verbatim plus a non-empty parser-shaped reason, so the
12627        // author can grep their caixa.lisp for `:de "<name>"` /
12628        // `:para "<name>"` and fix it in one edit. Same diagnostic
12629        // shape as `MembroCaixaInvalid` (3f9d7a0) and
12630        // `PlacementClusterInvalid` (6c8c00b).
12631        let mut s = three_member_spec();
12632        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
12633        let err = s.validate().unwrap_err();
12634        let AplicacaoError::ContratoCaixaInvalid {
12635            slot,
12636            caixa,
12637            reason,
12638        } = err
12639        else {
12640            panic!("expected ContratoCaixaInvalid, got {err:?}");
12641        };
12642        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
12643        assert_eq!(caixa, "BAD_NAME");
12644        assert!(
12645            !reason.is_empty(),
12646            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
12647        );
12648    }
12649
12650    #[test]
12651    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
12652        // Scalar-value pin: the two author-facing kebab-case labels the
12653        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
12654        // admits on the `:contratos` per-entry endpoint-shape axis,
12655        // one arm per typed sub-slot. Mirrors the peer scalar-value
12656        // pin the sibling top-level M2 / M3 / Supervisor
12657        // author-facing-label consts carry
12658        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
12659        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
12660        // slot itself), so every altitude of the typed-slot algebra
12661        // shares the same "one canonical byte-string per arm"
12662        // discipline. A future rebrand (`:de` → `:from` matching the
12663        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
12664        // sibling, `:para` → `:to` matching the same, or
12665        // `:de`/`:para` → `:source`/`:target` matching the WIT
12666        // world's `import`/`export` half-vocabulary) lands as an
12667        // edit to exactly one const, and every consumer that reaches
12668        // for the label picks it up at build time rather than at
12669        // runtime as a downstream `ContratoCaixaEmpty` /
12670        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
12671        // diagnostic mismatch far from the rename's commit.
12672        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
12673        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
12674    }
12675
12676    #[test]
12677    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
12678        // Production-through-const pin: the two per-axis labels the
12679        // per-`:contratos` entry endpoint-shape gate at
12680        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
12681        // argument to [`validate_contrato_caixa`] route through the
12682        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
12683        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
12684        // future rebrand that reaches the const but not the gate (or
12685        // vice versa) surfaces here at build time rather than at
12686        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
12687        // `slot: <stale-kebab-case>` diagnostic far from the rename's
12688        // commit. Mirror of the peer
12689        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
12690        // pin (882f498) on the sibling M3 top-level slot axis.
12691        let mut s = three_member_spec();
12692        s.contratos.push(contract_http("", "catalog", "/x"));
12693        assert_eq!(
12694            s.validate().unwrap_err(),
12695            AplicacaoError::ContratoCaixaEmpty {
12696                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12697            }
12698        );
12699        let mut s = three_member_spec();
12700        s.contratos.push(contract_http("cart", "", "/x"));
12701        assert_eq!(
12702            s.validate().unwrap_err(),
12703            AplicacaoError::ContratoCaixaEmpty {
12704                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12705            }
12706        );
12707    }
12708
12709    #[test]
12710    fn accepts_canonical_contrato_caixa_forms() {
12711        // The DNS-1123 label shapes a caixa author is realistically
12712        // going to write on a `:contratos :de` / `:para`. Pin every
12713        // leg so a future tightening that bans (e.g.) digit-start
12714        // identifiers surfaces here, mirroring
12715        // `accepts_canonical_membro_caixa_forms` on the peer name
12716        // axis.
12717        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
12718            let mut s = three_member_spec();
12719            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
12720            s.contratos = vec![contract_http("checkout", form, "/x")];
12721            s.entrada = None;
12722            s.validate().unwrap_or_else(|e| {
12723                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
12724            });
12725
12726            let mut s = three_member_spec();
12727            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
12728            s.contratos = vec![contract_http(form, "catalog", "/x")];
12729            s.entrada = None;
12730            s.validate().unwrap_or_else(|e| {
12731                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
12732            });
12733        }
12734    }
12735
12736    #[test]
12737    fn rejects_empty_wit() {
12738        let mut s = three_member_spec();
12739        s.contratos.push(WitContract {
12740            de: "cart".into(),
12741            para: "catalog".into(),
12742            wit: String::new(),
12743            endpoint: None,
12744            subject: None,
12745            slot: None,
12746        });
12747        let err = s.validate().unwrap_err();
12748        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
12749    }
12750
12751    #[test]
12752    fn rejects_entrada_to_unknown_member() {
12753        let mut s = three_member_spec();
12754        s.entrada.as_mut().unwrap().para = "phantom".into();
12755        assert!(matches!(
12756            s.validate().unwrap_err(),
12757            AplicacaoError::EntradaMemberMissing { .. }
12758        ));
12759    }
12760
12761    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
12762
12763    #[test]
12764    fn rejects_entrada_para_empty() {
12765        // `:para ""` previously fell through to
12766        // `EntradaMemberMissing { para: "" }` because the validated
12767        // `:membros :caixa` set never contains the empty string. The
12768        // narrower `EntradaParaEmpty` diagnostic now names the
12769        // offending slot directly — same empty-first cascade
12770        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
12771        // `ContratoCaixaEmpty` establish on the peer name axes.
12772        let mut s = three_member_spec();
12773        s.entrada.as_mut().unwrap().para = String::new();
12774        let err = s.validate().unwrap_err();
12775        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
12776    }
12777
12778    #[test]
12779    fn rejects_entrada_para_with_uppercase() {
12780        // The canonical "I copied the Servico's TitleCase display
12781        // name from an ADR" typo. Until this gate landed `:para "Cart"`
12782        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
12783        // as "this caixa isn't in `:membros`" when the root cause is
12784        // "this `:para` value's shape can never legitimately match a
12785        // validated member (DNS-1123 labels are lowercase)". The
12786        // narrower diagnostic names the value verbatim plus the
12787        // parser-shaped reason.
12788        let mut s = three_member_spec();
12789        s.entrada.as_mut().unwrap().para = "Cart".into();
12790        let err = s.validate().unwrap_err();
12791        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12792            panic!("expected EntradaParaInvalid, got other variant");
12793        };
12794        assert_eq!(para, "Cart");
12795        assert!(
12796            reason.contains("uppercase"),
12797            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12798        );
12799    }
12800
12801    #[test]
12802    fn rejects_entrada_para_with_underscore() {
12803        // The canonical "I'm thinking of a Python module" leak —
12804        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12805        let mut s = three_member_spec();
12806        s.entrada.as_mut().unwrap().para = "my_cart".into();
12807        let err = s.validate().unwrap_err();
12808        assert!(
12809            matches!(
12810                err,
12811                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12812                    if para == "my_cart" && reason.contains('_')
12813            ),
12814            "got {err:?}"
12815        );
12816    }
12817
12818    #[test]
12819    fn rejects_entrada_para_with_dot() {
12820        // An `:entrada :para` value is a single DNS-1123 *label*, not
12821        // a subdomain — mirroring the `:membros :caixa` floor. The
12822        // strictest floor among the use sites wins.
12823        let mut s = three_member_spec();
12824        s.entrada.as_mut().unwrap().para = "team.cart".into();
12825        let err = s.validate().unwrap_err();
12826        assert!(
12827            matches!(
12828                err,
12829                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12830                    if para == "team.cart" && reason.contains('.')
12831            ),
12832            "got {err:?}"
12833        );
12834    }
12835
12836    #[test]
12837    fn rejects_entrada_para_with_unicode() {
12838        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12839        // (`xn--…`) before it reaches K8s.
12840        let mut s = three_member_spec();
12841        s.entrada.as_mut().unwrap().para = "café".into();
12842        let err = s.validate().unwrap_err();
12843        assert!(
12844            matches!(
12845                err,
12846                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
12847            ),
12848            "got {err:?}"
12849        );
12850    }
12851
12852    #[test]
12853    fn rejects_entrada_para_with_leading_hyphen() {
12854        // DNS-1123 boundary rule: labels must start and end with an
12855        // alphanumeric. K8s rejects `-cart` outright.
12856        let mut s = three_member_spec();
12857        s.entrada.as_mut().unwrap().para = "-cart".into();
12858        let err = s.validate().unwrap_err();
12859        assert!(
12860            matches!(
12861                err,
12862                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12863                    if para == "-cart" && reason.contains("start and end")
12864            ),
12865            "got {err:?}"
12866        );
12867    }
12868
12869    #[test]
12870    fn rejects_entrada_para_with_trailing_hyphen() {
12871        // Symmetric boundary arm.
12872        let mut s = three_member_spec();
12873        s.entrada.as_mut().unwrap().para = "cart-".into();
12874        let err = s.validate().unwrap_err();
12875        assert!(
12876            matches!(
12877                err,
12878                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12879                    if para == "cart-" && reason.contains("start and end")
12880            ),
12881            "got {err:?}"
12882        );
12883    }
12884
12885    #[test]
12886    fn rejects_entrada_para_too_long() {
12887        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
12888        // bytes per label. K8s rejects longer names at admission on
12889        // every `metadata.name` axis.
12890        let mut s = three_member_spec();
12891        s.entrada.as_mut().unwrap().para = "a".repeat(64);
12892        let err = s.validate().unwrap_err();
12893        assert!(
12894            matches!(
12895                err,
12896                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12897                    if para.len() == 64 && reason.contains("max length")
12898            ),
12899            "got {err:?}"
12900        );
12901    }
12902
12903    #[test]
12904    fn entrada_para_empty_takes_precedence_over_invalid() {
12905        // Order pin: the `EntradaParaEmpty` arm fires before the
12906        // `EntradaParaInvalid` parse-side arm — same empty-first
12907        // cascade `validate_membro_caixa` / `validate_placement_cluster`
12908        // / `validate_contrato_caixa` already establish.
12909        let mut s = three_member_spec();
12910        s.entrada.as_mut().unwrap().para = String::new();
12911        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
12912    }
12913
12914    #[test]
12915    fn entrada_para_shape_fires_before_membership_lookup() {
12916        // The load-bearing pin: an invalid-shape `:para` surfaces its
12917        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
12918        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
12919        // an invalid-shape `:para` could never legitimately match any
12920        // member — the prior `EntradaMemberMissing` diagnostic framed
12921        // a structural impossibility as a graph-membership failure.
12922        let mut s = three_member_spec();
12923        s.entrada.as_mut().unwrap().para = "Cart".into();
12924        let err = s.validate().unwrap_err();
12925        assert!(
12926            matches!(
12927                err,
12928                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12929            ),
12930            "got {err:?}"
12931        );
12932    }
12933
12934    #[test]
12935    fn entrada_para_shape_fires_before_host_gate() {
12936        // Per-`:entrada` order pin: the `:para` shape gate fires
12937        // before the `:host` gate, mirroring the existing
12938        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
12939        // ordering where the member-lookup arm preceded the host gate.
12940        // The shape gate slots ahead of that, so a malformed `:para`
12941        // surfaces its own diagnostic even when `:host` is also wrong.
12942        let mut s = three_member_spec();
12943        let e = s.entrada.as_mut().unwrap();
12944        e.para = "Cart".into();
12945        e.host = "BAD HOST".into();
12946        let err = s.validate().unwrap_err();
12947        assert!(
12948            matches!(
12949                err,
12950                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12951            ),
12952            "got {err:?}"
12953        );
12954    }
12955
12956    #[test]
12957    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
12958        // Strict-improvement pin: a well-shaped `:para` that simply
12959        // isn't in `:membros` (a phantom reference — author meant to
12960        // add the member but didn't, or renamed and missed an
12961        // update) still surfaces `EntradaMemberMissing`, unchanged.
12962        // The shape gate only intercepts inputs that could never
12963        // legitimately match a validated member.
12964        let mut s = three_member_spec();
12965        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
12966        let err = s.validate().unwrap_err();
12967        assert!(
12968            matches!(
12969                err,
12970                AplicacaoError::EntradaMemberMissing { ref para }
12971                    if para == "phantom-shim"
12972            ),
12973            "got {err:?}"
12974        );
12975    }
12976
12977    #[test]
12978    fn entrada_para_invalid_diagnostic_carries_offending_para() {
12979        // The diagnostic-shape pin: the error names the offending
12980        // `:para` value verbatim plus a non-empty parser-shaped
12981        // reason, so the author can grep their caixa.lisp for
12982        // `:para "<name>"` and fix it in one edit. Same diagnostic
12983        // shape as `MembroCaixaInvalid` (3f9d7a0),
12984        // `PlacementClusterInvalid` (6c8c00b), and
12985        // `ContratoCaixaInvalid` (8d5af6b).
12986        let mut s = three_member_spec();
12987        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
12988        let err = s.validate().unwrap_err();
12989        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12990            panic!("expected EntradaParaInvalid, got {err:?}");
12991        };
12992        assert_eq!(para, "BAD_NAME");
12993        assert!(
12994            !reason.is_empty(),
12995            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
12996        );
12997    }
12998
12999    #[test]
13000    fn accepts_canonical_entrada_para_forms() {
13001        // Positive-control sweep covering the DNS-1123 label shapes a
13002        // caixa author is realistically going to write on `:entrada
13003        // :para`. Pin every leg so a future tightening that bans
13004        // (e.g.) digit-start identifiers surfaces here, mirroring
13005        // `accepts_canonical_membro_caixa_forms` and
13006        // `accepts_canonical_contrato_caixa_forms` on the peer name
13007        // axes.
13008        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
13009            let mut s = three_member_spec();
13010            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
13011            s.contratos = vec![contract_http(form, "catalog", "/x")];
13012            s.entrada = Some(Entrada {
13013                host: "checkout.quero.cloud".into(),
13014                para: form.into(),
13015                paths: vec!["/api".into()],
13016                port: 8080,
13017            });
13018            s.validate().unwrap_or_else(|e| {
13019                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
13020            });
13021        }
13022    }
13023
13024    #[test]
13025    fn rejects_replicated_without_clusters() {
13026        let mut s = three_member_spec();
13027        s.placement.clusters = vec![];
13028        assert!(matches!(
13029            s.validate().unwrap_err(),
13030            AplicacaoError::PlacementWithoutClusters { .. }
13031        ));
13032    }
13033
13034    #[test]
13035    fn rejects_sharded_without_key() {
13036        let mut s = three_member_spec();
13037        s.placement.estrategia = PlacementStrategy::Sharded;
13038        s.placement.shard_key = None;
13039        s.placement.clusters = vec!["rio".into()];
13040        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
13041    }
13042
13043    #[test]
13044    fn sharded_with_key_validates() {
13045        let mut s = three_member_spec();
13046        s.placement.estrategia = PlacementStrategy::Sharded;
13047        s.placement.shard_key = Some("$tenantId".into());
13048        s.validate().unwrap();
13049    }
13050
13051    #[test]
13052    fn round_trip_via_json_preserves_shape() {
13053        let s = three_member_spec();
13054        let json = serde_json::to_string(&s.membros).unwrap();
13055        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
13056        assert_eq!(back, s.membros);
13057
13058        let json = serde_json::to_string(&s.contratos).unwrap();
13059        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
13060        assert_eq!(back, s.contratos);
13061
13062        let json = serde_json::to_string(&s.placement).unwrap();
13063        let back: Placement = serde_json::from_str(&json).unwrap();
13064        assert_eq!(back, s.placement);
13065
13066        let json = serde_json::to_string(&s.entrada).unwrap();
13067        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
13068        assert_eq!(back, s.entrada);
13069    }
13070
13071    #[test]
13072    fn rate_limit_round_trip_seconds() {
13073        let policy = MeshPolicy {
13074            rate_limit: Some(RateLimit {
13075                rate: 100,
13076                window: Duration::from_secs(1),
13077            }),
13078            ..Default::default()
13079        };
13080        let json = serde_json::to_string(&policy).unwrap();
13081        assert!(json.contains("\"100/s\""));
13082        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13083        assert_eq!(back.rate_limit.unwrap().rate, 100);
13084        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
13085    }
13086
13087    #[test]
13088    fn rate_limit_round_trip_minutes() {
13089        let policy = MeshPolicy {
13090            rate_limit: Some(RateLimit {
13091                rate: 5000,
13092                window: Duration::from_secs(60),
13093            }),
13094            ..Default::default()
13095        };
13096        let json = serde_json::to_string(&policy).unwrap();
13097        assert!(json.contains("\"5000/m\""));
13098    }
13099
13100    #[test]
13101    fn circuit_breaker_round_trip() {
13102        let policy = MeshPolicy {
13103            circuit_breaker: Some(CircuitBreaker {
13104                max_failures: 5,
13105                window: Duration::from_secs(60),
13106            }),
13107            ..Default::default()
13108        };
13109        let json = serde_json::to_string(&policy).unwrap();
13110        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13111        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
13112        assert_eq!(
13113            back.circuit_breaker.unwrap().window,
13114            Duration::from_secs(60)
13115        );
13116    }
13117
13118    #[test]
13119    fn rejects_http_contrato_without_endpoint() {
13120        let mut s = three_member_spec();
13121        s.contratos.push(WitContract {
13122            de: "cart".into(),
13123            para: "catalog".into(),
13124            wit: "wasi:http/proxy".into(),
13125            endpoint: None,
13126            subject: None,
13127            slot: None,
13128        });
13129        let err = s.validate().unwrap_err();
13130        assert!(matches!(
13131            err,
13132            AplicacaoError::ContratoMissingTarget {
13133                expected: WitTarget::HTTP_FIELD_NAME,
13134                ..
13135            }
13136        ));
13137    }
13138
13139    #[test]
13140    fn rejects_http_contrato_with_subject() {
13141        let mut s = three_member_spec();
13142        s.contratos.push(WitContract {
13143            de: "cart".into(),
13144            para: "catalog".into(),
13145            wit: "wasi:http/proxy".into(),
13146            endpoint: Some("/x".into()),
13147            subject: Some("not.allowed.here".into()),
13148            slot: None,
13149        });
13150        let err = s.validate().unwrap_err();
13151        assert!(matches!(
13152            err,
13153            AplicacaoError::ContratoWrongTarget {
13154                expected: WitTarget::HTTP_FIELD_NAME,
13155                ..
13156            }
13157        ));
13158    }
13159
13160    #[test]
13161    fn rejects_pubsub_contrato_without_subject() {
13162        let mut s = three_member_spec();
13163        s.contratos.push(WitContract {
13164            de: "cart".into(),
13165            para: "catalog".into(),
13166            wit: "nats:pub-sub".into(),
13167            endpoint: None,
13168            subject: None,
13169            slot: None,
13170        });
13171        let err = s.validate().unwrap_err();
13172        assert!(matches!(
13173            err,
13174            AplicacaoError::ContratoMissingTarget {
13175                expected: WitTarget::PUBSUB_FIELD_NAME,
13176                ..
13177            }
13178        ));
13179    }
13180
13181    #[test]
13182    fn rejects_pubsub_contrato_with_endpoint() {
13183        let mut s = three_member_spec();
13184        s.contratos.push(WitContract {
13185            de: "cart".into(),
13186            para: "catalog".into(),
13187            wit: "kafka:topic".into(),
13188            endpoint: Some("/wrong".into()),
13189            subject: Some("topic.x".into()),
13190            slot: None,
13191        });
13192        let err = s.validate().unwrap_err();
13193        assert!(matches!(
13194            err,
13195            AplicacaoError::ContratoWrongTarget {
13196                expected: WitTarget::PUBSUB_FIELD_NAME,
13197                ..
13198            }
13199        ));
13200    }
13201
13202    #[test]
13203    fn rejects_store_contrato_without_slot() {
13204        let mut s = three_member_spec();
13205        s.contratos.push(WitContract {
13206            de: "cart".into(),
13207            para: "catalog".into(),
13208            wit: "wasi:keyvalue/store".into(),
13209            endpoint: None,
13210            subject: None,
13211            slot: None,
13212        });
13213        let err = s.validate().unwrap_err();
13214        assert!(matches!(
13215            err,
13216            AplicacaoError::ContratoMissingTarget {
13217                expected: WitTarget::STORE_FIELD_NAME,
13218                ..
13219            }
13220        ));
13221    }
13222
13223    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
13224
13225    #[test]
13226    fn rejects_http_contrato_with_empty_endpoint() {
13227        // `Some("")` for an HTTP endpoint passes the presence check
13228        // (target() previously returned WitTarget::Http { endpoint: "" })
13229        // but renders as a `path: ""` Cilium L7 rule that matches no
13230        // traffic. Same value-shape footgun closed for :entrada :paths
13231        // entries (eb3456d).
13232        let mut s = three_member_spec();
13233        s.contratos.push(WitContract {
13234            de: "cart".into(),
13235            para: "catalog".into(),
13236            wit: "wasi:http/proxy".into(),
13237            endpoint: Some(String::new()),
13238            subject: None,
13239            slot: None,
13240        });
13241        let err = s.validate().unwrap_err();
13242        assert!(
13243            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
13244                if de == "cart" && para == "catalog"),
13245            "got {err:?}"
13246        );
13247    }
13248
13249    #[test]
13250    fn rejects_http_contrato_with_relative_endpoint() {
13251        // Cilium L7 :path + Gateway API PathPrefix both require a
13252        // leading `/`. Same shape required of :entrada :paths
13253        // (eb3456d). Lifted into target() so every consumer of the
13254        // typed WitTarget view inherits the guarantee.
13255        let mut s = three_member_spec();
13256        s.contratos.push(WitContract {
13257            de: "cart".into(),
13258            para: "catalog".into(),
13259            wit: "wasi:http/proxy".into(),
13260            endpoint: Some("products/:id".into()),
13261            subject: None,
13262            slot: None,
13263        });
13264        let err = s.validate().unwrap_err();
13265        assert!(
13266            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
13267                if endpoint == "products/:id"),
13268            "got {err:?}"
13269        );
13270    }
13271
13272    #[test]
13273    fn rejects_pubsub_contrato_with_empty_subject() {
13274        // NATS / Kafka publish without a subject is a no-op subscribe;
13275        // never the author's intent. Same empty-string rejection as
13276        // :membros :caixa, :placement :clusters entries, :entrada
13277        // :paths entries — every value carried by every typed slot is
13278        // value-shape-checked at validate().
13279        let mut s = three_member_spec();
13280        s.contratos.push(WitContract {
13281            de: "cart".into(),
13282            para: "catalog".into(),
13283            wit: "nats:pub-sub".into(),
13284            endpoint: None,
13285            subject: Some(String::new()),
13286            slot: None,
13287        });
13288        let err = s.validate().unwrap_err();
13289        assert!(
13290            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
13291                if de == "cart" && para == "catalog"),
13292            "got {err:?}"
13293        );
13294    }
13295
13296    #[test]
13297    fn rejects_store_contrato_with_empty_slot() {
13298        // An empty slot template addresses the bucket root, defeating
13299        // the per-key isolation the slot exists for — a footgun on
13300        // `wasi:keyvalue/store` whose closest analog is the empty
13301        // shard-key rejected on :placement Sharded (c7c7799).
13302        let mut s = three_member_spec();
13303        s.contratos.push(WitContract {
13304            de: "cart".into(),
13305            para: "catalog".into(),
13306            wit: "wasi:keyvalue/store".into(),
13307            endpoint: None,
13308            subject: None,
13309            slot: Some(String::new()),
13310        });
13311        let err = s.validate().unwrap_err();
13312        assert!(
13313            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
13314                if de == "cart" && para == "catalog"),
13315            "got {err:?}"
13316        );
13317    }
13318
13319    #[test]
13320    fn http_contrato_root_endpoint_validates() {
13321        // Pin the boundary case: a single-`/` endpoint is the catch-all
13322        // form the Gateway HTTPRoute renderer falls back to when
13323        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
13324        // must remain a valid contrato endpoint too.
13325        let mut s = three_member_spec();
13326        s.contratos.push(contract_http("cart", "catalog", "/"));
13327        s.validate().unwrap();
13328    }
13329
13330    // ── :contratos :endpoint value-shape gate ────────────────────────────
13331    //
13332    // Mirrors the `:entrada :paths` value-shape suite on the peer
13333    // HTTP-path axis. Until this gate landed `WitContract::target()`
13334    // only refused the empty string + the missing-leading-`/` form
13335    // (c4213a4); a structurally invalid endpoint passed validate and
13336    // landed verbatim as a Cilium L7 `path:` rule
13337    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
13338    // traffic or was rejected at apply time by Cilium policy admission.
13339    // Every authoring footgun the K8s Gateway API webhook / Cilium
13340    // policy validator would catch on admission now becomes a caixa-
13341    // build-time `ContratoEndpointInvalid` with the offending
13342    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
13343    // shape as `EntradaPathInvalid` on the sibling axis; same shared
13344    // predicate (`crate::render::is_gateway_api_http_path`) ensures
13345    // drift between the two axes' rule enforcement is a build error
13346    // at the predicate.
13347
13348    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
13349        // Fresh spec per call so the would-be-duplicate edge
13350        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
13351        // `three_member_spec`'s pre-existing
13352        // `(cart, catalog, …, /products/:id)` entry — only the
13353        // endpoint payload differs.
13354        let mut s = three_member_spec();
13355        s.contratos.push(contract_http("cart", "catalog", ep));
13356        s.validate().unwrap_err()
13357    }
13358
13359    #[test]
13360    fn rejects_http_contrato_endpoint_with_query() {
13361        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
13362        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
13363        // rule the L7 matcher would never satisfy.
13364        let err = contrato_endpoint_err("/charge?token=X");
13365        assert!(
13366            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13367                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
13368            "got {err:?}"
13369        );
13370    }
13371
13372    #[test]
13373    fn rejects_http_contrato_endpoint_with_fragment() {
13374        let err = contrato_endpoint_err("/charge#frag");
13375        assert!(
13376            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13377                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
13378            "got {err:?}"
13379        );
13380    }
13381
13382    #[test]
13383    fn rejects_http_contrato_endpoint_with_whitespace() {
13384        let err = contrato_endpoint_err("/foo bar");
13385        assert!(
13386            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13387                if endpoint == "/foo bar" && reason.contains("whitespace")),
13388            "got {err:?}"
13389        );
13390    }
13391
13392    #[test]
13393    fn rejects_http_contrato_endpoint_with_control_char() {
13394        let err = contrato_endpoint_err("/api/\x01bar");
13395        assert!(
13396            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13397                if endpoint == "/api/\x01bar" && reason.contains("control character")),
13398            "got {err:?}"
13399        );
13400    }
13401
13402    #[test]
13403    fn rejects_http_contrato_endpoint_with_non_ascii() {
13404        let err = contrato_endpoint_err("/api/café");
13405        assert!(
13406            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13407                if endpoint == "/api/café" && reason.contains("non-ASCII")),
13408            "got {err:?}"
13409        );
13410    }
13411
13412    #[test]
13413    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
13414        let err = contrato_endpoint_err("/api//cart");
13415        assert!(
13416            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13417                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
13418            "got {err:?}"
13419        );
13420    }
13421
13422    #[test]
13423    fn rejects_http_contrato_endpoint_with_dot_segment() {
13424        let err = contrato_endpoint_err("/api/./cart");
13425        assert!(
13426            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13427                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
13428            "got {err:?}"
13429        );
13430    }
13431
13432    #[test]
13433    fn rejects_http_contrato_endpoint_with_parent_segment() {
13434        // Path-traversal in a contrato endpoint is the canonical
13435        // "L7 rule that the workload's HTTP server's path-resolution
13436        // logic interprets differently than the policy enforcer"
13437        // footgun. Rejected outright at validate time.
13438        let err = contrato_endpoint_err("/api/../etc");
13439        assert!(
13440            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13441                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
13442            "got {err:?}"
13443        );
13444    }
13445
13446    #[test]
13447    fn rejects_http_contrato_endpoint_too_long() {
13448        // 1025-byte endpoint — one over the Gateway API
13449        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
13450        // path matcher has no inherent length limit but the policy
13451        // CR itself rides through the K8s apiserver, which enforces
13452        // ConfigMap-shaped limits; sharing the Gateway API cap is the
13453        // conservative floor.
13454        let big = format!("/api/{}", "a".repeat(1020));
13455        assert_eq!(big.len(), 1025);
13456        let err = contrato_endpoint_err(&big);
13457        assert!(
13458            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13459                if endpoint == &big && reason.contains("max length of 1024")),
13460            "got {err:?}"
13461        );
13462    }
13463
13464    #[test]
13465    fn http_contrato_endpoint_max_length_validates() {
13466        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
13467        // in the cap surfaces here and at
13468        // `rejects_http_contrato_endpoint_too_long` simultaneously,
13469        // mirroring `entrada_path_max_length_validates` on the peer
13470        // axis.
13471        let big = format!("/api/{}", "a".repeat(1019));
13472        assert_eq!(big.len(), 1024);
13473        let mut s = three_member_spec();
13474        s.contratos.push(contract_http("cart", "catalog", &big));
13475        s.validate().unwrap();
13476    }
13477
13478    #[test]
13479    fn http_contrato_endpoint_accepts_canonical_forms() {
13480        // Positive-set sweep: every canonical HTTP-path shape the
13481        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
13482        // plain paths, hidden-file-style `.config` segments distinct
13483        // from the `.` segment, digit-bearing segments, the canonical
13484        // route-template `:param` form, trailing-slash form,
13485        // percent-encoded segments, the `/foo..bar` interior-`..`-
13486        // substring forms that are NOT `..` segments) must remain a
13487        // valid contrato endpoint too. Drift between this list and
13488        // the entrada path positive sweep surfaces at the shared
13489        // `is_gateway_api_http_path` substrate-side suite — one
13490        // source of truth. Uses a fresh `(payment, catalog)` edge so
13491        // none of the swept endpoints collide with the pre-existing
13492        // `(cart, catalog, /products/:id)` / `(cart, payment,
13493        // /charge)` entries in `three_member_spec`.
13494        for ep in [
13495            "/",
13496            "/charge",
13497            "/v1/charge",
13498            "/api/.config",
13499            "/products/:id",
13500            "/api/cart/",
13501            "/api/caf%C3%A9",
13502            "/foo..bar",
13503            "/...",
13504        ] {
13505            let mut s = three_member_spec();
13506            s.contratos.push(contract_http("payment", "catalog", ep));
13507            s.validate()
13508                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
13509        }
13510    }
13511
13512    #[test]
13513    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
13514        // Ordering pin: `ContratoEndpointEmpty` is the more self-
13515        // locating diagnostic on `""` and must lead — the value-
13516        // shape gate is only reached after the empty-check fires.
13517        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
13518        // on the peer axis.
13519        let mut s = three_member_spec();
13520        s.contratos.push(WitContract {
13521            de: "cart".into(),
13522            para: "catalog".into(),
13523            wit: "wasi:http/proxy".into(),
13524            endpoint: Some(String::new()),
13525            subject: None,
13526            slot: None,
13527        });
13528        let err = s.validate().unwrap_err();
13529        assert!(
13530            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13531            "got {err:?}"
13532        );
13533    }
13534
13535    #[test]
13536    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
13537        // Ordering pin: an endpoint without a leading `/` surfaces the
13538        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
13539        // value-shape gate is only consulted on endpoints that already
13540        // satisfy the absolute-prefix invariant. Mirrors
13541        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
13542        let err = contrato_endpoint_err("bad path");
13543        assert!(
13544            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
13545                if endpoint == "bad path"),
13546            "got {err:?}"
13547        );
13548    }
13549
13550    #[test]
13551    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
13552        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
13553        // `:para` + a non-empty reason flow through verbatim so the
13554        // author can grep their caixa.lisp for the offending contrato
13555        // block and fix it in one edit. Same shape as
13556        // `entrada_path_diagnostic_carries_offending_path`.
13557        let err = contrato_endpoint_err("/api?q=1");
13558        match err {
13559            AplicacaoError::ContratoEndpointInvalid {
13560                de,
13561                para,
13562                endpoint,
13563                reason,
13564            } => {
13565                assert_eq!(de, "cart");
13566                assert_eq!(para, "catalog");
13567                assert_eq!(endpoint, "/api?q=1");
13568                assert!(!reason.is_empty(), "reason field must be non-empty");
13569            }
13570            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
13571        }
13572    }
13573
13574    #[test]
13575    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
13576        // The compounding theorem: every &str inside a WitTarget
13577        // returned by target() is non-empty (and absolute, for Http).
13578        // Renderers downstream of typed_view() can rely on this
13579        // without re-checking — the type system carries the proof.
13580        let http = contract_http("cart", "catalog", "/x");
13581        match http.target().unwrap() {
13582            WitTarget::Http { endpoint } => {
13583                assert!(!endpoint.is_empty());
13584                assert!(endpoint.starts_with('/'));
13585            }
13586            other => panic!("expected Http, got {other:?}"),
13587        }
13588        let nats = WitContract {
13589            de: "a".into(),
13590            para: "b".into(),
13591            wit: "nats:pub-sub".into(),
13592            endpoint: None,
13593            subject: Some("topic.x".into()),
13594            slot: None,
13595        };
13596        match nats.target().unwrap() {
13597            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
13598            other => panic!("expected PubSub, got {other:?}"),
13599        }
13600        let kv = WitContract {
13601            de: "a".into(),
13602            para: "b".into(),
13603            wit: "wasi:keyvalue/store".into(),
13604            endpoint: None,
13605            subject: None,
13606            slot: Some("checkout/$orderId".into()),
13607        };
13608        match kv.target().unwrap() {
13609            WitTarget::Store { slot } => assert!(!slot.is_empty()),
13610            other => panic!("expected Store, got {other:?}"),
13611        }
13612    }
13613
13614    #[test]
13615    fn target_diagnostic_names_offending_endpoint_value() {
13616        // When the malformed endpoint string is non-trivial, the
13617        // diagnostic carries the actual value back to the author —
13618        // not a generic "endpoint malformed" error.
13619        let bad = WitContract {
13620            de: "src".into(),
13621            para: "dst".into(),
13622            wit: "wasi:http/proxy".into(),
13623            endpoint: Some("api/v1/charge".into()),
13624            subject: None,
13625            slot: None,
13626        };
13627        match bad.target().unwrap_err() {
13628            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
13629                assert_eq!(de, "src");
13630                assert_eq!(para, "dst");
13631                assert_eq!(endpoint, "api/v1/charge");
13632            }
13633            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
13634        }
13635    }
13636
13637    #[test]
13638    fn rejects_unknown_wit_with_target_set() {
13639        let mut s = three_member_spec();
13640        s.contratos.push(WitContract {
13641            de: "cart".into(),
13642            para: "catalog".into(),
13643            wit: "custom:exchange".into(),
13644            endpoint: Some("/leaked".into()),
13645            subject: None,
13646            slot: None,
13647        });
13648        let err = s.validate().unwrap_err();
13649        assert!(matches!(
13650            err,
13651            AplicacaoError::ContratoWrongTarget {
13652                expected: WitTarget::CAPABILITY_EXPECTED,
13653                ..
13654            }
13655        ));
13656    }
13657
13658    #[test]
13659    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
13660        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
13661        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
13662        // fourth arm of the same "which payload field name goes in the
13663        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
13664        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13665        // consts cover on the peer HTTP / PubSub / Store arms
13666        // (`wit_target_field_name_pins_per_variant`). Until this lift
13667        // landed the byte-string sat twice — once inline in the
13668        // [`WitContract::target`] Capability-arm rejection at the
13669        // production dispatch, once in `rejects_unknown_wit_with_target_set`
13670        // pinning against the same literal — with no compile-time link
13671        // between them. Same "one canonical declaration, next to the
13672        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
13673        // lift established for the payload-less arm's human-readable
13674        // label axis; this test is the shape peer of
13675        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
13676        // pair (routes-through-const + scalar-value pin) on the
13677        // wrong-target diagnostic-scalar axis.
13678        //
13679        // Fail-before-pass-after was verified locally by mutating the
13680        // const declaration to `"capability"` — the scalar-value pin
13681        // below fires (`"capability" != "none"`) and the routes-through
13682        // assertion below still holds (production and const walk in
13683        // lockstep), which is the correct behavior: a rename on the
13684        // const drifts here first, not at a downstream consumer.
13685        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
13686
13687        let mut s = three_member_spec();
13688        s.contratos.push(WitContract {
13689            de: "cart".into(),
13690            para: "catalog".into(),
13691            wit: "custom:exchange".into(),
13692            endpoint: Some("/leaked".into()),
13693            subject: None,
13694            slot: None,
13695        });
13696        match s.validate().unwrap_err() {
13697            AplicacaoError::ContratoWrongTarget { expected, .. } => {
13698                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
13699            }
13700            other => panic!("expected ContratoWrongTarget, got {other:?}"),
13701        }
13702    }
13703
13704    #[test]
13705    fn unknown_wit_capability_only_validates() {
13706        let mut s = three_member_spec();
13707        s.contratos.push(WitContract {
13708            de: "cart".into(),
13709            para: "catalog".into(),
13710            // A WIT world we haven't yet shaped — accept it as a typed
13711            // capability edge so authors aren't blocked while the WIT
13712            // registry catches up. No payload field may be carried.
13713            wit: "custom:exchange".into(),
13714            endpoint: None,
13715            subject: None,
13716            slot: None,
13717        });
13718        s.validate().unwrap();
13719        let added = s.contratos.last().unwrap();
13720        assert_eq!(added.target().unwrap(), WitTarget::Capability);
13721    }
13722
13723    #[test]
13724    fn target_typed_view_round_trips_each_shape() {
13725        let http = contract_http("cart", "catalog", "/products/:id");
13726        assert_eq!(
13727            http.target().unwrap(),
13728            WitTarget::Http {
13729                endpoint: "/products/:id"
13730            }
13731        );
13732        let nats = WitContract {
13733            de: "a".into(),
13734            para: "b".into(),
13735            wit: "nats:pub-sub".into(),
13736            endpoint: None,
13737            subject: Some("topic.x".into()),
13738            slot: None,
13739        };
13740        assert_eq!(
13741            nats.target().unwrap(),
13742            WitTarget::PubSub { subject: "topic.x" }
13743        );
13744        let kv = WitContract {
13745            de: "a".into(),
13746            para: "b".into(),
13747            wit: "wasi:keyvalue/store".into(),
13748            endpoint: None,
13749            subject: None,
13750            slot: Some("checkout/$orderId".into()),
13751        };
13752        assert_eq!(
13753            kv.target().unwrap(),
13754            WitTarget::Store {
13755                slot: "checkout/$orderId"
13756            }
13757        );
13758    }
13759
13760    #[test]
13761    fn wit_contract_kind_predicates() {
13762        let http = contract_http("a", "b", "/x");
13763        assert!(http.is_http());
13764        assert!(!http.is_pubsub());
13765        assert!(!http.is_store());
13766        assert!(!http.is_capability());
13767
13768        let nats = WitContract {
13769            de: "a".into(),
13770            para: "b".into(),
13771            wit: "nats:pub-sub".into(),
13772            endpoint: None,
13773            subject: Some("topic.x".into()),
13774            slot: None,
13775        };
13776        assert!(nats.is_pubsub());
13777        assert!(!nats.is_http());
13778        assert!(!nats.is_capability());
13779
13780        let kv = WitContract {
13781            de: "a".into(),
13782            para: "b".into(),
13783            wit: "wasi:keyvalue/store".into(),
13784            endpoint: None,
13785            subject: None,
13786            slot: Some("checkout/$orderId".into()),
13787        };
13788        assert!(kv.is_store());
13789        assert!(!kv.is_http());
13790        assert!(!kv.is_capability());
13791
13792        // Fourth arm on the paired closed-set predicate family: the
13793        // payload-less capability edge that projects to the payload-
13794        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
13795        // Extends the 3-arm predicate sweep this test opened to cover
13796        // the closed 4-way partition [`WitContract::is_capability`]
13797        // closes on the pre-projection WIT-shape axis, matched with the
13798        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
13799        // 4-arm predicate set.
13800        let cap = WitContract {
13801            de: "a".into(),
13802            para: "b".into(),
13803            wit: "custom:capability-only".into(),
13804            endpoint: None,
13805            subject: None,
13806            slot: None,
13807        };
13808        assert!(cap.is_capability());
13809        assert!(!cap.is_http());
13810        assert!(!cap.is_pubsub());
13811        assert!(!cap.is_store());
13812    }
13813
13814    // ── :contratos :wit value-shape gate ─────────────────────────────────
13815    //
13816    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
13817    // dispatch-discriminator axis. Until this gate landed
13818    // `WitContract::target()` accepted any non-empty string and
13819    // silently demoted unrecognized shapes to a capability-only L4
13820    // edge — the canonical "I thought I had L7 HTTP routing, got
13821    // L4-only" footgun. Every authoring footgun the WIT registry's
13822    // own grammar rejects (uppercase, hyphen-for-colon typo,
13823    // whitespace, empty package, doubled `@`, …) now becomes a
13824    // caixa-build-time `ContratoWitInvalid` with the offending
13825    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
13826    // as `ContratoEndpointInvalid` on the sibling axis; same shared
13827    // predicate (`crate::render::is_wit_world_ref`) ensures drift
13828    // between any two axes' rule enforcement is a build error at the
13829    // predicate, not piecemeal across renderers.
13830
13831    fn contrato_wit_err(wit: &str) -> AplicacaoError {
13832        // Fresh spec per call so the new contract doesn't collide on
13833        // identity with `three_member_spec`'s pre-existing entries.
13834        // The new edge uses `(payment, catalog)` — a pair the fixture
13835        // doesn't already declare — with no payload field set, so the
13836        // wit-shape gate fires before any payload-shape arm.
13837        let mut s = three_member_spec();
13838        s.contratos.push(WitContract {
13839            de: "payment".into(),
13840            para: "catalog".into(),
13841            wit: wit.into(),
13842            endpoint: None,
13843            subject: None,
13844            slot: None,
13845        });
13846        s.validate().unwrap_err()
13847    }
13848
13849    #[test]
13850    fn rejects_wit_with_uppercase_namespace() {
13851        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
13852        // didn't match the lowercase `wasi:http/` prefix is_http() keys
13853        // off, so the dispatch fell through to the capability arm and
13854        // the contract silently rendered as an L4-only Cilium edge.
13855        // The new gate surfaces the uppercase typo at validate time
13856        // with the offending `:wit` named.
13857        let err = contrato_wit_err("WASI:http/proxy");
13858        assert!(
13859            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13860                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
13861            "got {err:?}"
13862        );
13863    }
13864
13865    #[test]
13866    fn rejects_wit_with_hyphen_for_colon_typo() {
13867        // The canonical "I forgot the `:` separator" typo — pre-gate
13868        // this passed as Capability silently, so the renderer emitted
13869        // an L4-only policy where the author expected L7 HTTP rules.
13870        let err = contrato_wit_err("wasi-http/proxy");
13871        assert!(
13872            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13873                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
13874            "got {err:?}"
13875        );
13876    }
13877
13878    #[test]
13879    fn rejects_wit_with_multiple_colons() {
13880        // Doubled `:` — the namespace/package split has nowhere to
13881        // anchor, so the dispatch silently demotes to Capability.
13882        let err = contrato_wit_err("wasi:http:proxy");
13883        assert!(
13884            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13885                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
13886            "got {err:?}"
13887        );
13888    }
13889
13890    #[test]
13891    fn rejects_wit_with_empty_package() {
13892        // `wasi:` — namespace alone with no package. Pre-gate this
13893        // failed neither the is_http nor is_pubsub nor is_store
13894        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
13895        // a bare `wasi:`), so it silently demoted to Capability.
13896        let err = contrato_wit_err("wasi:");
13897        assert!(
13898            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13899                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
13900            "got {err:?}"
13901        );
13902    }
13903
13904    #[test]
13905    fn rejects_wit_with_underscore() {
13906        // Underscore — WIT identifiers are kebab-case, same rule
13907        // DNS-1123 enforces on its peer axes. The diagnostic carries
13908        // the explicit "use `-` instead" remediation.
13909        let err = contrato_wit_err("wasi:http_proxy");
13910        assert!(
13911            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13912                if wit == "wasi:http_proxy" && reason.contains('_')),
13913            "got {err:?}"
13914        );
13915    }
13916
13917    #[test]
13918    fn rejects_wit_with_whitespace() {
13919        // Whitespace mid-token — the prefix check matches but the
13920        // package-and-onward parse silently demoted to Capability.
13921        let err = contrato_wit_err("wasi:http proxy");
13922        assert!(
13923            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13924                if wit == "wasi:http proxy" && reason.contains("whitespace")),
13925            "got {err:?}"
13926        );
13927    }
13928
13929    #[test]
13930    fn rejects_wit_with_non_ascii() {
13931        // Un-percent-encoded non-ASCII byte — the canonical "I copied
13932        // the package name from a doc with smart quotes / accented
13933        // characters" footgun.
13934        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
13935        assert!(
13936            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13937                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
13938            "got {err:?}"
13939        );
13940    }
13941
13942    #[test]
13943    fn rejects_wit_with_consecutive_hyphens() {
13944        // `pub--sub` — WIT identifiers join words with single hyphens.
13945        let err = contrato_wit_err("nats:pub--sub");
13946        assert!(
13947            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13948                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
13949            "got {err:?}"
13950        );
13951    }
13952
13953    #[test]
13954    fn rejects_wit_with_trailing_at_no_version() {
13955        // `wasi:http/proxy@` — the version-suffix author started to
13956        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
13957        // parser would reject this; surface it at validate time.
13958        let err = contrato_wit_err("wasi:http/proxy@");
13959        assert!(
13960            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13961                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
13962            "got {err:?}"
13963        );
13964    }
13965
13966    #[test]
13967    fn rejects_wit_too_long() {
13968        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
13969        // The legitimate-shape arms all pass (lowercase, single `:`,
13970        // kebab-case identifiers); only the cap arm fires. Surfaces
13971        // the paste-from-binary / accidental-multi-line-blob landing
13972        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
13973        // on the peer axis.
13974        let big = format!("wasi:{}", "a".repeat(124));
13975        assert_eq!(big.len(), 129);
13976        let err = contrato_wit_err(&big);
13977        assert!(
13978            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13979                if wit == &big && reason.contains("max length of 128")),
13980            "got {err:?}"
13981        );
13982    }
13983
13984    #[test]
13985    fn wit_max_length_validates() {
13986        // 128-byte WIT reference — exactly the cap. Boundary pin:
13987        // drift in the cap surfaces here and at `rejects_wit_too_long`
13988        // simultaneously, mirroring
13989        // `http_contrato_endpoint_max_length_validates` on the peer
13990        // axis.
13991        let big = format!("wasi:{}", "a".repeat(123));
13992        assert_eq!(big.len(), 128);
13993        let mut s = three_member_spec();
13994        s.contratos.push(WitContract {
13995            de: "payment".into(),
13996            para: "catalog".into(),
13997            wit: big,
13998            endpoint: None,
13999            subject: None,
14000            slot: None,
14001        });
14002        s.validate().unwrap();
14003    }
14004
14005    #[test]
14006    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
14007        // Positive-set sweep through the AplicacaoSpec::validate
14008        // surface (rather than the substrate-side predicate directly)
14009        // — pins every shape the existing test fixtures + the
14010        // checkout-aplicacao example carry, so the gate's accept-set
14011        // matches the substrate's emit-set. Drift between this list
14012        // and `render::tests::wit_world_ref_accepts_canonical_forms`
14013        // surfaces at the substrate layer's positive sweep — one
14014        // source of truth for the rule.
14015        for wit in [
14016            "wasi:http/proxy",
14017            "wasi:keyvalue/store",
14018            "nats:pub-sub",
14019            "kafka:topic",
14020            "custom:exchange",
14021            "pleme:cap/audit",
14022            "wasi:http/proxy@0.2.0",
14023        ] {
14024            // Payload field paired to the dispatched WIT shape so the
14025            // shape-↔-target arm doesn't fire instead of the wit-shape
14026            // arm we're exercising. Routes off the same
14027            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
14028            // `wit_shape_is_store` free functions the production
14029            // `WitContract::is_http` / `is_pubsub` / `is_store`
14030            // methods delegate to (both consult the lifted
14031            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
14032            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
14033            // future prefix addition to the routing accept-set
14034            // reaches this test's payload-dispatch arm by
14035            // construction — no per-test-site drift can hide a
14036            // shape-→-target-slot mismatch that would silently
14037            // demote a canonical `:wit` value to the
14038            // `(None, None, None)` capability-only arm and let the
14039            // `AplicacaoSpec::validate` positive sweep pass on a
14040            // shape it should exercise as HTTP / pub-sub / store.
14041            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
14042                (Some("/x".into()), None, None)
14043            } else if wit_shape_is_pubsub(wit) {
14044                (None, Some("topic.x".into()), None)
14045            } else if wit_shape_is_store(wit) {
14046                (None, None, Some("bucket/$key".into()))
14047            } else {
14048                (None, None, None)
14049            };
14050            let mut s = three_member_spec();
14051            s.contratos.push(WitContract {
14052                de: "payment".into(),
14053                para: "catalog".into(),
14054                wit: wit.into(),
14055                endpoint,
14056                subject,
14057                slot,
14058            });
14059            s.validate()
14060                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
14061        }
14062    }
14063
14064    #[test]
14065    fn wit_shape_predicates_accept_canonical_prefix_set() {
14066        // Positive-set sweep pinning every prefix in
14067        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
14068        // WIT_STORE_SHAPE_PREFIXES against the three free-function
14069        // dispatch predicates. The six prefixes are the load-bearing
14070        // routing keys the substrate's WIT-shape dispatch consults
14071        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
14072        // key/value-store-slot admission); any drift between the
14073        // free-function accept-set and this list surfaces here
14074        // rather than at apply time as a silent
14075        // shape-→-capability-only demotion.
14076        assert!(wit_shape_is_http("wasi:http/proxy"));
14077        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
14078        assert!(wit_shape_is_http("http:incoming"));
14079
14080        assert!(wit_shape_is_pubsub("nats:pub-sub"));
14081        assert!(wit_shape_is_pubsub("kafka:topic"));
14082
14083        assert!(wit_shape_is_store("wasi:keyvalue/store"));
14084        assert!(wit_shape_is_store("kv:cache/session"));
14085    }
14086
14087    #[test]
14088    fn wit_shape_predicates_reject_uncanonical_forms() {
14089        // Negative-set pin: the six canonical prefixes are
14090        // lowercase-only (mirrors the `is_wit_world_ref` substrate
14091        // predicate's lowercase invariant — see its docstring on the
14092        // "I thought I had L7 HTTP routing, got L4-only" footgun).
14093        // The empty string, an uppercase-prefixed form, a hyphen-
14094        // instead-of-colon typo, and a bare kebab identifier all miss
14095        // every shape arm — reachable-by-construction only via the
14096        // `is_wit_world_ref` gate that admission-checks the `:wit`
14097        // value first, but pinned here so any future
14098        // free-function change (e.g. a case-insensitive
14099        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
14100        // this unit level.
14101        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
14102            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
14103            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
14104            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
14105        }
14106    }
14107
14108    #[test]
14109    fn wit_shape_predicates_partition_canonical_set() {
14110        // Every canonical prefix routes to exactly one shape arm —
14111        // the three prefix sets are pairwise disjoint. Pins the
14112        // routing property [`WitContract::target`] relies on: an
14113        // `is_http()` return of `true` guarantees `is_pubsub()` and
14114        // `is_store()` return `false`, so the shape-→-target-slot
14115        // dispatch (endpoint vs subject vs slot) is unambiguous.
14116        // Drift (e.g. a future `"kv:"` moved into the HTTP set
14117        // without removal from the store set) would silently route
14118        // one prefix to two arms and the first-matching-arm order
14119        // becomes load-bearing — this pin surfaces it as a build
14120        // error instead.
14121        for prefix in WIT_HTTP_SHAPE_PREFIXES {
14122            let sample = format!("{prefix}x");
14123            assert!(wit_shape_is_http(&sample));
14124            assert!(!wit_shape_is_pubsub(&sample));
14125            assert!(!wit_shape_is_store(&sample));
14126        }
14127        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
14128            let sample = format!("{prefix}x");
14129            assert!(!wit_shape_is_http(&sample));
14130            assert!(wit_shape_is_pubsub(&sample));
14131            assert!(!wit_shape_is_store(&sample));
14132        }
14133        for prefix in WIT_STORE_SHAPE_PREFIXES {
14134            let sample = format!("{prefix}x");
14135            assert!(!wit_shape_is_http(&sample));
14136            assert!(!wit_shape_is_pubsub(&sample));
14137            assert!(wit_shape_is_store(&sample));
14138        }
14139    }
14140
14141    #[test]
14142    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
14143        // Positive pin: [`wit_shape_matches`] is exactly the
14144        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
14145        // parameterized on the accept-set. Two-prefix accept-set,
14146        // one-prefix accept-set, and empty accept-set (which must
14147        // reject everything, including the empty string — an empty
14148        // `any()` fold returns `false`) all pinned so a future
14149        // reimplementation that swaps `starts_with` for `contains`,
14150        // `==`, or a case-folded comparator surfaces at unit-test
14151        // time.
14152        let two = &["wasi:http/", "http:"];
14153        assert!(wit_shape_matches("wasi:http/proxy", two));
14154        assert!(wit_shape_matches("http:incoming", two));
14155        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
14156
14157        let one = &["nats:"];
14158        assert!(wit_shape_matches("nats:pub-sub", one));
14159        assert!(!wit_shape_matches("kafka:topic", one));
14160
14161        // Empty accept-set matches nothing — the identity element
14162        // for the disjunctive `any()` fold across the prefix set.
14163        // Reachable via a future `wit_shape_is_<name>` const paired
14164        // to a still-empty prefix table on a nascent shape-arm draft.
14165        let empty: &[&str] = &[];
14166        assert!(!wit_shape_matches("wasi:http/proxy", empty));
14167        assert!(!wit_shape_matches("", empty));
14168
14169        // starts_with, not contains: a prefix embedded mid-string
14170        // never matches. Pins the routing invariant [`WitContract::target`]
14171        // relies on (an authored `:wit "custom:wasi:http/"` string
14172        // does not silently route through the HTTP arm just because
14173        // it happens to contain the canonical HTTP prefix).
14174        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
14175    }
14176
14177    #[test]
14178    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
14179        // Equivalence pin: each per-shape predicate is exactly
14180        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
14181        // every canonical prefix + the empty string + one negative
14182        // sample against every peer so a future predicate that grew
14183        // its own inline `iter().any(starts_with)` (rather than
14184        // delegating through the lifted combinator) drifts loudly here
14185        // — the peer-const table's contents must agree with the
14186        // predicate's accept-set by construction.
14187        let samples = [
14188            String::new(),
14189            "wasi:http/proxy".to_string(),
14190            "http:incoming".to_string(),
14191            "nats:pub-sub".to_string(),
14192            "kafka:topic".to_string(),
14193            "wasi:keyvalue/store".to_string(),
14194            "kv:cache/session".to_string(),
14195            "custom-shape".to_string(),
14196            "WASI:HTTP/proxy".to_string(),
14197        ];
14198        for wit in &samples {
14199            assert_eq!(
14200                wit_shape_is_http(wit),
14201                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14202                "wit_shape_is_http drifted from combinator on {wit:?}",
14203            );
14204            assert_eq!(
14205                wit_shape_is_pubsub(wit),
14206                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
14207                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
14208            );
14209            assert_eq!(
14210                wit_shape_is_store(wit),
14211                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
14212                "wit_shape_is_store drifted from combinator on {wit:?}",
14213            );
14214        }
14215    }
14216
14217    #[test]
14218    fn wit_contract_shape_methods_delegate_to_free_functions() {
14219        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
14220        // `is_store` are `&self` conveniences on top of the free
14221        // functions — for every canonical prefix the method's return
14222        // matches its free-function peer. Sweeps the union of the
14223        // three prefix sets so a future method that grew its own
14224        // inline prefix logic (rather than delegating) drifts loudly
14225        // here on the first prefix the free function accepts and the
14226        // method doesn't.
14227        for shape_set in [
14228            WIT_HTTP_SHAPE_PREFIXES,
14229            WIT_PUBSUB_SHAPE_PREFIXES,
14230            WIT_STORE_SHAPE_PREFIXES,
14231        ] {
14232            for prefix in shape_set {
14233                let c = WitContract {
14234                    de: "cart".into(),
14235                    para: "catalog".into(),
14236                    wit: format!("{prefix}x"),
14237                    endpoint: None,
14238                    subject: None,
14239                    slot: None,
14240                };
14241                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
14242                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
14243                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
14244                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
14245            }
14246        }
14247        // Capability-arm delegation sweep: two representative
14248        // Capability-shaped `:wit` values (a bare non-prefix-matching
14249        // WIT world, the deliberately-shaped empty string
14250        // [`WitContract::is_capability`]'s docstring calls out as
14251        // syntactically Capability). Extends the free-function
14252        // delegation pin onto the fourth arm so a future
14253        // [`WitContract::is_capability`] rewrite that grew an inline
14254        // prefix-set scan (rather than delegating through
14255        // [`wit_shape_is_capability`]) drifts loudly here on the first
14256        // Capability-shaped sample.
14257        for wit in ["custom:capability-only", ""] {
14258            let c = WitContract {
14259                de: "cart".into(),
14260                para: "catalog".into(),
14261                wit: wit.into(),
14262                endpoint: None,
14263                subject: None,
14264                slot: None,
14265            };
14266            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
14267        }
14268    }
14269
14270    #[test]
14271    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
14272        // 4-way partition-witness pin on the raw `&str` axis: for every
14273        // canonical prefix in the three payload-arm accept-sets,
14274        // exactly one of the four [`wit_shape_is_http`] /
14275        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
14276        // [`wit_shape_is_capability`] free functions returns `true` and
14277        // the other three return `false` — the four-arm partition
14278        // witness that locks the free-function WIT-shape-classifier
14279        // family into a partition of the `:contratos :wit` axis
14280        // load-bearing. Peer of the sibling [`WitContract`]-surface
14281        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
14282        // partition pin — extends the discipline onto the raw `&str`
14283        // axis so any future arm addition (a hypothetical
14284        // `wasi:sockets/*` transport-layer shape, an `oci:*`
14285        // capability-import carrier per the sibling
14286        // [`wit_shape_matches`] docstring's trajectory bullet) that
14287        // landed on one of the payload-arm free functions without
14288        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
14289        // here as two arms returning `true` simultaneously at
14290        // caixa-core build time rather than a silent per-consumer
14291        // misclassification at renderer emit time.
14292        for shape_set in [
14293            WIT_HTTP_SHAPE_PREFIXES,
14294            WIT_PUBSUB_SHAPE_PREFIXES,
14295            WIT_STORE_SHAPE_PREFIXES,
14296        ] {
14297            for prefix in shape_set {
14298                let wit = format!("{prefix}x");
14299                let hits = [
14300                    wit_shape_is_http(&wit),
14301                    wit_shape_is_pubsub(&wit),
14302                    wit_shape_is_store(&wit),
14303                    wit_shape_is_capability(&wit),
14304                ]
14305                .iter()
14306                .filter(|&&b| b)
14307                .count();
14308                assert_eq!(
14309                    hits,
14310                    1,
14311                    "raw-&str WIT-shape 4-way predicate partition must \
14312                     admit exactly one arm per canonical prefix; got {hits} \
14313                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
14314                     is_capability={})",
14315                    wit_shape_is_http(&wit),
14316                    wit_shape_is_pubsub(&wit),
14317                    wit_shape_is_store(&wit),
14318                    wit_shape_is_capability(&wit),
14319                );
14320            }
14321        }
14322        // Capability-arm sweep on the raw `&str` axis: two
14323        // representative Capability-shaped `:wit` values (a bare non-
14324        // prefix-matching WIT world, the deliberately-shaped empty
14325        // string the pure classifier still admits per
14326        // [`wit_shape_is_capability`]'s docstring). Both must land on
14327        // the fourth arm exclusively so the partition witness holds
14328        // across the full 4-arm closure on the raw `&str` axis.
14329        for wit in ["custom:capability-only", ""] {
14330            let hits = [
14331                wit_shape_is_http(wit),
14332                wit_shape_is_pubsub(wit),
14333                wit_shape_is_store(wit),
14334                wit_shape_is_capability(wit),
14335            ]
14336            .iter()
14337            .filter(|&&b| b)
14338            .count();
14339            assert_eq!(
14340                hits, 1,
14341                "raw-&str WIT-shape 4-way predicate partition must \
14342                 admit exactly one arm on Capability-shaped wit={wit:?}"
14343            );
14344            assert!(
14345                wit_shape_is_capability(wit),
14346                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
14347            );
14348        }
14349    }
14350
14351    #[test]
14352    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
14353        // Composition-witness pin: [`wit_shape_is_capability`] is the
14354        // exact-inverse disjunction of the sibling payload-arm free-
14355        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
14356        // / [`wit_shape_is_store`]. A future reimplementation that
14357        // grew its own prefix-set scan (e.g. inlining a fourth
14358        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
14359        // not own today) rather than delegating to the sibling trio
14360        // would drift loudly here — the composition contract binds the
14361        // fourth-arm free-function predicate to the exact-inverse of
14362        // the three payload-arm free-function predicates, so any
14363        // rebrand of any prefix-set const flows through
14364        // [`wit_shape_is_capability`] by construction without a
14365        // coordinated per-consumer rewrite. Peer of the sibling
14366        // [`WitContract`]-surface
14367        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
14368        // composition pin — extends the discipline onto the raw
14369        // `&str` axis.
14370        let mut cases: Vec<String> = Vec::new();
14371        for shape_set in [
14372            WIT_HTTP_SHAPE_PREFIXES,
14373            WIT_PUBSUB_SHAPE_PREFIXES,
14374            WIT_STORE_SHAPE_PREFIXES,
14375        ] {
14376            for prefix in shape_set {
14377                cases.push(format!("{prefix}x"));
14378            }
14379        }
14380        cases.push("custom:capability-only".to_string());
14381        cases.push(String::new());
14382        for wit in cases {
14383            assert_eq!(
14384                wit_shape_is_capability(&wit),
14385                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
14386                "wit_shape_is_capability must equal \
14387                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
14388                 at wit={wit:?}"
14389            );
14390        }
14391    }
14392
14393    #[test]
14394    fn wit_shape_classifier_family_is_const_fn() {
14395        // Fail-before-pass-after pin on the 4-arm free-function WIT-
14396        // shape classifier family's `const`-eval posture. Each of the
14397        // four peer classifiers ([`wit_shape_is_http`] /
14398        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
14399        // [`wit_shape_is_capability`]) and the underlying combinator
14400        // [`wit_shape_matches`] must be `pub const fn` — any future
14401        // accidental downgrade to non-`const` fails the `const fn`
14402        // wrappers below at caixa-core build time with E0015
14403        // (`cannot call non-const function`), strictly stronger than
14404        // a runtime `assert!` and strictly stronger than the module-
14405        // scope `const _: () = assert!(…)` pins immediately after the
14406        // classifier declarations (those anchor specific accept-set
14407        // truth-table entries; this pin anchors the `const` posture
14408        // itself via `const fn` wrappers that are only well-formed
14409        // when the callee is itself `const fn`).
14410        //
14411        // Verified fail-before-pass-after by locally reverting
14412        // `pub const fn` → `pub fn` on each classifier and observing
14413        // E0015 at every corresponding wrapper call site (build
14414        // error, no test-time surface), then restoring `pub const fn`
14415        // and observing the pin pass at test time. Peer of the
14416        // sibling M3
14417        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
14418        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
14419        // M2
14420        // [`child_spec_restart_accessor_is_const_fn`] /
14421        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
14422        // and M3
14423        // [`placement_estrategia_accessor_is_const_fn`] /
14424        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
14425        // sibling `const`-eval-surface-pass axes.
14426        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
14427            wit_shape_matches(wit, prefixes)
14428        }
14429        const fn http_via_const_fn(wit: &str) -> bool {
14430            wit_shape_is_http(wit)
14431        }
14432        const fn pubsub_via_const_fn(wit: &str) -> bool {
14433            wit_shape_is_pubsub(wit)
14434        }
14435        const fn store_via_const_fn(wit: &str) -> bool {
14436            wit_shape_is_store(wit)
14437        }
14438        const fn capability_via_const_fn(wit: &str) -> bool {
14439            wit_shape_is_capability(wit)
14440        }
14441        // Sweep one canonical accept-set sample per arm plus the
14442        // payload-less/empty capability samples, asserting the
14443        // wrapper and direct dispatches agree byte-for-byte across
14444        // the closed 4-arm partition.
14445        let cases: [(&str, bool, bool, bool, bool); 6] = [
14446            ("wasi:http/proxy", true, false, false, false),
14447            ("http:incoming", true, false, false, false),
14448            ("nats:events", false, true, false, false),
14449            ("kafka:topic", false, true, false, false),
14450            ("wasi:keyvalue/store", false, false, true, false),
14451            ("kv:cache", false, false, true, false),
14452        ];
14453        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
14454            assert_eq!(
14455                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
14456                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14457                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
14458            );
14459            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
14460            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
14461            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
14462            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14463            assert_eq!(wit_shape_is_http(wit), is_http);
14464            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
14465            assert_eq!(wit_shape_is_store(wit), is_store);
14466        }
14467        // Payload-less capability arm (the 4th partition arm).
14468        let capability_samples: [&str; 3] =
14469            ["wasi:filesystem/preopens", "custom:capability-only", ""];
14470        for wit in capability_samples {
14471            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14472            assert!(wit_shape_is_capability(wit));
14473            assert!(!wit_shape_is_http(wit));
14474            assert!(!wit_shape_is_pubsub(wit));
14475            assert!(!wit_shape_is_store(wit));
14476        }
14477    }
14478
14479    // Canonical `(wit, expected)` sweep the four [`WitShape`] pins below
14480    // key off — one accept-set sample per prefix in each of the three
14481    // payload-arm prefix sets [`WIT_HTTP_SHAPE_PREFIXES`] /
14482    // [`WIT_PUBSUB_SHAPE_PREFIXES`] / [`WIT_STORE_SHAPE_PREFIXES`], plus
14483    // three canonical Capability-arm samples (a non-prefix-matching WIT
14484    // world, an empty string, a partial-match probe that lands after
14485    // the accepted prefix boundary). Declared once so a future arm
14486    // addition or prefix-set edit grows the truth table at one
14487    // authored site and every downstream pin picks up the new row by
14488    // construction.
14489    const WIT_SHAPE_CLASSIFY_TRUTH_TABLE: &[(&str, WitShape)] = &[
14490        ("wasi:http/proxy", WitShape::Http),
14491        ("http:incoming", WitShape::Http),
14492        ("nats:events", WitShape::PubSub),
14493        ("kafka:topic", WitShape::PubSub),
14494        ("wasi:keyvalue/store", WitShape::Store),
14495        ("kv:cache", WitShape::Store),
14496        ("wasi:filesystem/preopens", WitShape::Capability),
14497        ("custom:capability-only", WitShape::Capability),
14498        ("", WitShape::Capability),
14499    ];
14500
14501    #[test]
14502    fn wit_shape_all_matches_declaration_order_and_covers_every_arm() {
14503        // Fail-before-pass-after pin on [`WitShape::ALL`]: the slice
14504        // must enumerate every arm exactly once in declaration order
14505        // (`Http` → `PubSub` → `Store` → `Capability`), so downstream
14506        // consumers that walk the shape space through the const slice
14507        // reach every arm and see them in the canonical order the
14508        // paired [`WitShape::classify`] arm-preference dispatches on.
14509        // A future variant addition that forgets to grow the slice
14510        // trips here (the length no longer matches the number of arms
14511        // touched by the `match self` below); a rearrangement of the
14512        // declaration order without updating the slice trips too.
14513        let expected: [WitShape; 4] = [
14514            WitShape::Http,
14515            WitShape::PubSub,
14516            WitShape::Store,
14517            WitShape::Capability,
14518        ];
14519        assert_eq!(WitShape::ALL.len(), expected.len());
14520        assert_eq!(WitShape::ALL, &expected[..]);
14521        // Exhaustive-match witness: touch every arm so a future
14522        // variant addition without a matching `WitShape::ALL` extension
14523        // trips at compile time here on the missing arm.
14524        for arm in WitShape::ALL {
14525            match arm {
14526                WitShape::Http | WitShape::PubSub | WitShape::Store | WitShape::Capability => {}
14527            }
14528        }
14529    }
14530
14531    #[test]
14532    fn wit_shape_classify_pins_the_canonical_truth_table() {
14533        // Pin the [`WitShape::classify`] arm-dispatch against the
14534        // shared truth table [`WIT_SHAPE_CLASSIFY_TRUTH_TABLE`]. A
14535        // future prefix-set edit that reroutes any canonical sample
14536        // onto the wrong arm trips at exactly the offending row.
14537        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
14538            assert_eq!(
14539                WitShape::classify(wit),
14540                *expected,
14541                "WitShape::classify({wit:?}) drifted from truth table",
14542            );
14543        }
14544    }
14545
14546    #[test]
14547    fn wit_shape_classify_partitions_via_is_variant_predicates() {
14548        // Fail-before-pass-after pin: for every canonical truth-table
14549        // row, the classified arm satisfies exactly one of the four
14550        // [`gen_platform::IsVariant`]-derived arm-discriminator
14551        // predicates ([`WitShape::is_http`] / [`is_pubsub`] /
14552        // [`is_store`] / [`is_capability`]) — the observed 4-slot
14553        // predicate row must equal a one-hot row with the `true` at
14554        // exactly the same index as the declared arm's slot in
14555        // [`WitShape::ALL`]. A future rebind (an `#[is_variant(name =
14556        // "…")]` drift, a manual `impl` shadowing the derive, an arm
14557        // rename that reroutes one arm through the wrong predicate
14558        // lane) trips here at exactly the offending row rather than
14559        // surfacing far from the derive commit.
14560        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
14561            let arm = WitShape::classify(wit);
14562            let observed = [
14563                arm.is_http(),
14564                arm.is_pubsub(),
14565                arm.is_store(),
14566                arm.is_capability(),
14567            ];
14568            let mut expected_row = [false; 4];
14569            let idx = WitShape::ALL
14570                .iter()
14571                .position(|a| a == expected)
14572                .expect("truth-table arm appears in WitShape::ALL");
14573            expected_row[idx] = true;
14574            assert_eq!(
14575                observed, expected_row,
14576                "WitShape::classify({wit:?}).is_* row must be one-hot at slot {idx}",
14577            );
14578        }
14579    }
14580
14581    #[test]
14582    fn wit_shape_classify_agrees_with_free_predicates() {
14583        // Equivalence pin against the four free classifier predicates
14584        // ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
14585        // [`wit_shape_is_store`] / [`wit_shape_is_capability`]) — after
14586        // this lift the free predicates route through
14587        // `matches!(WitShape::classify(wit), WitShape::<arm>)`, so this
14588        // pin proves the delegation preserves each predicate's
14589        // accept-set on the canonical truth table. A future accidental
14590        // reintroduction of an open-coded free-predicate body (or a
14591        // classify-side arm reorder that shifts arm preference in a
14592        // way that breaks disjointness) trips here at the offending
14593        // row rather than at a downstream consumer.
14594        for (wit, _expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
14595            let arm = WitShape::classify(wit);
14596            assert_eq!(arm.is_http(), wit_shape_is_http(wit));
14597            assert_eq!(arm.is_pubsub(), wit_shape_is_pubsub(wit));
14598            assert_eq!(arm.is_store(), wit_shape_is_store(wit));
14599            assert_eq!(arm.is_capability(), wit_shape_is_capability(wit));
14600        }
14601    }
14602
14603    #[test]
14604    fn wit_shape_as_str_display_and_asref_route_through_one_source() {
14605        // Fail-before-pass-after pin on the canonical-projection triple
14606        // [`WitShape::as_str`] / [`std::fmt::Display for WitShape`] /
14607        // [`AsRef<str> for WitShape`]: every arm's `Display`-formatted
14608        // and `AsRef<str>`-borrowed output must byte-equal its
14609        // `as_str` output. Same discipline the sibling
14610        // [`crate::CaixaKind`] / [`crate::dialeto::CaixaDialeto`] /
14611        // [`PlacementStrategy`] / [`RateLimitUnit`] canonical-projection
14612        // triples carry — a future accidental hand-rolled `Display`
14613        // body that diverges from `as_str` trips here.
14614        let expected: &[(WitShape, &str)] = &[
14615            (WitShape::Http, "http"),
14616            (WitShape::PubSub, "pubsub"),
14617            (WitShape::Store, "store"),
14618            (WitShape::Capability, "capability"),
14619        ];
14620        for (arm, want) in expected {
14621            assert_eq!(arm.as_str(), *want, "WitShape::as_str({arm:?}) drifted");
14622            assert_eq!(
14623                format!("{arm}"),
14624                *want,
14625                "Display for WitShape drifted from as_str at {arm:?}",
14626            );
14627            assert_eq!(
14628                AsRef::<str>::as_ref(arm),
14629                *want,
14630                "AsRef<str> for WitShape drifted from as_str at {arm:?}",
14631            );
14632        }
14633    }
14634
14635    #[test]
14636    fn wit_shape_classify_is_const_fn() {
14637        // Fail-before-pass-after pin on [`WitShape::classify`]'s
14638        // `const`-eval posture. The classifier must be `pub const fn`
14639        // — any future accidental downgrade to non-`const` fails the
14640        // wrapper below with E0015 at caixa-core build time, strictly
14641        // stronger than a runtime `assert!`. Peer of the sibling
14642        // [`wit_shape_classifier_family_is_const_fn`] pin on the
14643        // free-function classifier family.
14644        const fn classify_via_const_fn(wit: &str) -> WitShape {
14645            WitShape::classify(wit)
14646        }
14647        // Compile-time truth-table pin: every canonical row's
14648        // classification is reachable at const-eval time, so any
14649        // downstream `const`-context consumer (a module-scope
14650        // `const _: () = assert!(matches!(WitShape::classify(<lit>),
14651        // WitShape::<arm>))` invariant pin on a typed fixture, a
14652        // future `const fn` per-`:contratos :wit` arm-resolver over a
14653        // static wit literal) reaches the classifier through one
14654        // dispatch on the substrate primitive without an intermediate
14655        // non-`const` step.
14656        const _: () = assert!(matches!(
14657            classify_via_const_fn("wasi:http/proxy"),
14658            WitShape::Http
14659        ));
14660        const _: () = assert!(matches!(
14661            classify_via_const_fn("nats:events"),
14662            WitShape::PubSub
14663        ));
14664        const _: () = assert!(matches!(
14665            classify_via_const_fn("wasi:keyvalue/store"),
14666            WitShape::Store
14667        ));
14668        const _: () = assert!(matches!(classify_via_const_fn(""), WitShape::Capability));
14669        // Also assert const `as_str` routes through the const `classify`
14670        // on the same const path.
14671        const _: () = assert!(matches!(
14672            classify_via_const_fn("wasi:http/proxy").as_str().as_bytes(),
14673            b"http"
14674        ));
14675    }
14676
14677    #[test]
14678    fn wit_shape_from_wire_accepts_every_as_str_output() {
14679        // Fail-before-pass-after per-arm accept pin on the newly lifted
14680        // [`WitShape::from_wire`] reverse projection: every arm in
14681        // [`WitShape::ALL`] must parse back through `from_wire` when fed
14682        // its own [`WitShape::as_str`] output, landing on
14683        // `Some(same_variant)`. A regression that hand-rolled either
14684        // side's per-arm match without threading through the shared
14685        // four-string closed set would silently disagree on any future
14686        // arm rename (or a new arm the WIT-shape space grows — a
14687        // hypothetical `wasi:sockets/*` transport-layer shape, an
14688        // `oci:*` capability-import carrier per the sibling
14689        // [`wit_shape_matches`] docstring's trajectory bullet) and this
14690        // pin flags it at caixa-core build time rather than at a
14691        // downstream `feira app graph --by-wit-shape` consumer's silent
14692        // tag misclassification.
14693        //
14694        // Peer of the sibling
14695        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_accepts_every_variant_slug_output`
14696        // (1e4cc81) /
14697        // `caixa_theme::style::tests::semantic_from_wire_accepts_every_as_str_output`
14698        // (e7bca7b) /
14699        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_accepts_every_as_str_output`
14700        // (bd505a1) /
14701        // `caixa_lint::diagnostic::tests::severity_from_wire_accepts_every_as_str_output`
14702        // (5afff0e) /
14703        // `caixa_arch::report::tests::arch_verdict_from_wire_accepts_every_as_str_output`
14704        // (6afe564) /
14705        // `caixa_arch::invariants::tests::invariant_kind_from_wire_accepts_every_as_str_output`
14706        // (b9e4e61) round-trip pins on the peer caixa-provedor /
14707        // caixa-theme / caixa-lint / caixa-arch closed-set-enum
14708        // reverse-projection axes, and of the sibling
14709        // `crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`
14710        // (2aa6d23) /
14711        // `crate::dialeto::tests::caixa_dialeto_from_wire_accepts_every_as_str_output`
14712        // (d0e65ea) /
14713        // `placement_strategy_from_wire_accepts_every_lifted_constant`
14714        // (18c7342) /
14715        // `crate::dep::tests::dep_list_round_trips_through_as_str_and_from_wire`
14716        // (45ee563) /
14717        // `crate::render::tests::path_shape_violation_from_wire_accepts_every_as_str_output`
14718        // (aebd9c6) round-trip pins on the sibling caixa-core closed-
14719        // set typed-enum reverse-projection axes.
14720        for &variant in WitShape::ALL {
14721            let wire = variant.as_str();
14722            let parsed = WitShape::from_wire(wire).unwrap_or_else(|| {
14723                panic!(
14724                    "WitShape::from_wire({wire:?}) must accept every \
14725                     WitShape::as_str output — got None for the wire \
14726                     byte-string of {variant:?}"
14727                )
14728            });
14729            assert_eq!(
14730                parsed, variant,
14731                "WitShape::from_wire(WitShape::{variant:?}.as_str()) must \
14732                 return WitShape::{variant:?} — the (as_str, from_wire) \
14733                 pair must form a total round-trip on the closed four-arm \
14734                 WitShape arm-set",
14735            );
14736        }
14737        // Pin the exact per-arm accept-set so a future rebrand of the
14738        // census-label byte-strings ("http" / "pubsub" / "store" /
14739        // "capability") surfaces at this pin rather than at a downstream
14740        // consumer's silent tag drift.
14741        assert_eq!(WitShape::from_wire("http"), Some(WitShape::Http));
14742        assert_eq!(WitShape::from_wire("pubsub"), Some(WitShape::PubSub));
14743        assert_eq!(WitShape::from_wire("store"), Some(WitShape::Store));
14744        assert_eq!(
14745            WitShape::from_wire("capability"),
14746            Some(WitShape::Capability),
14747        );
14748    }
14749
14750    #[test]
14751    fn wit_shape_from_wire_rejects_unknown_byte_strings() {
14752        // Rejection pin on the [`WitShape::from_wire`] parser's
14753        // accept-set: any string outside the four-arm
14754        // [`WitShape::as_str`] output set must return [`None`]. A future
14755        // accidental widening of the accept-set (a case-insensitive
14756        // match that accepts `"HTTP"` / `"Http"`, a silent acceptance of
14757        // the PascalCase Debug-derived shapes `"Http"` / `"PubSub"` /
14758        // `"Store"` / `"Capability"` on the wire axis, a Levenshtein-
14759        // forgiving arm-lookup that admits typos, a silent absorption of
14760        // the sibling raw `:contratos :wit` identifiers [`Self::classify`]
14761        // consumes on the peer classifier axis — `"wasi:http/proxy"`,
14762        // `"nats:events"`, `"wasi:keyvalue/store"`, `"kafka:topic"`,
14763        // `"kv:cache"`, `"http:incoming"` — a silent absorption of the
14764        // paired [`WitTarget::label`] short-form tags every downstream
14765        // renderer already handles on the post-validation axis) would
14766        // silently drift the parser's accept-set from the emitter's — a
14767        // downstream re-loader that bound a prior emission's
14768        // [`Self::as_str`] output back to the typed enum through this
14769        // parser would then bind a malformed byte-string to a
14770        // plausibly-wrong typed arm the caller does not route through
14771        // any fallback, silently misclassifying the reloaded row.
14772        //
14773        // The raw `:contratos :wit` identifier vectors are load-bearing:
14774        // [`WitShape::classify`] is a *total* function on every `&str`
14775        // (falling through to [`WitShape::Capability`] on unknown
14776        // prefixes), so a caller who confuses the two axes and routes a
14777        // raw WIT identifier through [`from_wire`] instead of
14778        // [`classify`] must observe [`None`] here rather than a plausibly-
14779        // wrong `Some(WitShape::Capability)` silently — the peer axes
14780        // carry different accept-sets by design.
14781        //
14782        // Peer of the sibling
14783        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_rejects_unknown_byte_strings`
14784        // (1e4cc81) /
14785        // `caixa_theme::style::tests::semantic_from_wire_rejects_unknown_byte_strings`
14786        // (e7bca7b) /
14787        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_rejects_unknown_byte_strings`
14788        // (bd505a1) /
14789        // `caixa_lint::diagnostic::tests::severity_from_wire_rejects_unknown_byte_strings`
14790        // (5afff0e) /
14791        // `caixa_arch::report::tests::arch_verdict_from_wire_rejects_unknown_byte_strings`
14792        // (6afe564) /
14793        // `caixa_arch::invariants::tests::invariant_kind_from_wire_rejects_unknown_byte_strings`
14794        // (b9e4e61) rejection pins on the peer caixa-provedor /
14795        // caixa-theme / caixa-lint / caixa-arch axes, and of the sibling
14796        // `caixa_kind_from_wire_rejects_unknown_byte_strings` (2aa6d23),
14797        // `caixa_dialeto_from_wire_rejects_unknown_byte_strings`
14798        // (d0e65ea),
14799        // `placement_strategy_from_wire_rejects_unknown_byte_strings`
14800        // (18c7342),
14801        // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
14802        // (45ee563), and
14803        // `path_shape_violation_from_wire_rejects_unknown_byte_strings`
14804        // (aebd9c6) rejection pins on the sibling caixa-core axes.
14805        for bad in [
14806            "",
14807            " ",
14808            "http ",
14809            " http",
14810            "HTTP",
14811            "Http",
14812            "PUBSUB",
14813            "PubSub",
14814            "pub_sub",
14815            "pub-sub",
14816            "STORE",
14817            "Store",
14818            "CAPABILITY",
14819            "Capability",
14820            "kv",
14821            "nats",
14822            "kafka",
14823            "wasi:http/proxy",
14824            "wasi:http/",
14825            "http:",
14826            "http:incoming",
14827            "nats:events",
14828            "kafka:topic",
14829            "wasi:keyvalue/store",
14830            "wasi:keyvalue/",
14831            "kv:cache",
14832            "kv:",
14833            "oci:capability",
14834            "wasi:sockets/tcp",
14835            "\u{200b}http",
14836            "http\u{200b}",
14837        ] {
14838            assert!(
14839                WitShape::from_wire(bad).is_none(),
14840                "WitShape::from_wire({bad:?}) must reject byte-strings \
14841                 outside the four-arm WitShape::as_str output set — got \
14842                 {:?}",
14843                WitShape::from_wire(bad),
14844            );
14845        }
14846    }
14847
14848    #[test]
14849    fn wit_shape_from_wire_and_classify_partition_the_axis() {
14850        // Cross-axis discipline pin: [`WitShape::classify`] is a total
14851        // function on the raw `:contratos :wit` identifier axis (every
14852        // `&str` classifies), while [`WitShape::from_wire`] is a partial
14853        // function on the census-label axis (the four
14854        // [`WitShape::as_str`] outputs and nothing else). The two axes
14855        // meet on exactly zero strings by construction — the four
14856        // census labels (`"http"` / `"pubsub"` / `"store"` /
14857        // `"capability"`) are not prefix-matched by any of
14858        // [`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
14859        // [`WIT_STORE_SHAPE_PREFIXES`], so on the shared four-string
14860        // census-label set:
14861        //
14862        //   * [`WitShape::from_wire`] returns `Some(<matching arm>)`
14863        //     per [`WitShape::as_str`]'s output;
14864        //   * [`WitShape::classify`] falls through to the
14865        //     [`WitShape::Capability`] catch-all fallback (since none of
14866        //     the payload-arm prefix sets begin with `"http"` /
14867        //     `"pubsub"` / `"store"` / `"capability"`).
14868        //
14869        // A future WIT-prefix set edit that accidentally started with
14870        // one of the four census labels (a hypothetical
14871        // `"http"` prefix directly, a `"pubsub://"` scheme addition, a
14872        // `"store:"` capability-carrier extension) would silently
14873        // collide the two axes on the same string — [`from_wire`] would
14874        // still yield the census-label arm while [`classify`] would
14875        // route the payload-arm dispatch through the accidental overlap.
14876        // Locking the partition here means such a prefix-set edit
14877        // trips this pin at caixa-core build time before the collision
14878        // becomes observable at any downstream consumer.
14879        for &variant in WitShape::ALL {
14880            let label = variant.as_str();
14881            // The census-label axis half — [`from_wire`] resolves to
14882            // the emitter's arm identity.
14883            assert_eq!(
14884                WitShape::from_wire(label),
14885                Some(variant),
14886                "WitShape::from_wire({label:?}) must resolve to the \
14887                 emitter's arm identity on the census-label axis",
14888            );
14889            // The raw-classifier axis half — [`classify`] falls through
14890            // to [`WitShape::Capability`] on every census label under
14891            // the current prefix set. Any future overlap trips here.
14892            assert_eq!(
14893                WitShape::classify(label),
14894                WitShape::Capability,
14895                "WitShape::classify({label:?}) must fall through to \
14896                 WitShape::Capability on every census label — a match \
14897                 to any payload arm here means a payload-prefix set \
14898                 has silently collided the census-label axis with the \
14899                 raw-classifier axis",
14900            );
14901        }
14902    }
14903
14904    #[test]
14905    fn wit_shape_classify_matches_wit_contract_target_arm_on_valid_inputs() {
14906        // Cross-surface equivalence pin: for every canonical
14907        // truth-table row that also validates cleanly through
14908        // [`WitContract::target`], the pre-projection [`WitShape`] arm
14909        // matches the post-projection [`WitTarget`] arm — the pre- and
14910        // post-validation classifications agree on the arm identity
14911        // even though the payload-carrying view carries additional
14912        // per-arm information. A future edit that reroutes
14913        // `WitContract::target`'s HTTP/pubsub/store dispatch through a
14914        // different predicate than the [`WitShape::classify`] the free
14915        // predicates now route through would trip here at the offending
14916        // row rather than at a downstream renderer.
14917        //
14918        // The Capability arm is excluded from the paired sweep: an
14919        // arbitrary Capability-classified string need not pass
14920        // [`crate::render::is_wit_world_ref`]'s value-shape gate, so
14921        // `WitContract::target` would raise `ContratoWitInvalid`
14922        // rather than return `WitTarget::Capability`; the arm-identity
14923        // agreement lives in the payload-arm rows.
14924        //
14925        // Per-row shape: `(wit, endpoint, subject, slot)` — one row per
14926        // payload arm with its shape's canonical payload field filled
14927        // and the peer fields `None`. Named type-alias closes the
14928        // `clippy::type_complexity` warning the raw tuple triggers.
14929        type WitTargetArmRow = (
14930            &'static str,
14931            Option<&'static str>,
14932            Option<&'static str>,
14933            Option<&'static str>,
14934        );
14935        let cases: [WitTargetArmRow; 6] = [
14936            ("wasi:http/proxy", Some("/x"), None, None),
14937            ("http:incoming", Some("/x"), None, None),
14938            ("nats:events", None, Some("subject.x"), None),
14939            ("kafka:topic", None, Some("subject.x"), None),
14940            ("wasi:keyvalue/store", None, None, Some("bucket/x")),
14941            ("kv:cache", None, None, Some("bucket/x")),
14942        ];
14943        for (wit, endpoint, subject, slot) in cases {
14944            let c = WitContract {
14945                de: "cart".into(),
14946                para: "catalog".into(),
14947                wit: wit.to_string(),
14948                endpoint: endpoint.map(str::to_string),
14949                subject: subject.map(str::to_string),
14950                slot: slot.map(str::to_string),
14951            };
14952            let target = c.target().unwrap_or_else(|e| {
14953                panic!("expected target() to validate for wit={wit:?}, got: {e}")
14954            });
14955            let shape = WitShape::classify(wit);
14956            // Match arm-for-arm — the raw &str classifier and the
14957            // validated payload view must agree on which arm carries
14958            // the edge.
14959            let agree = matches!(
14960                (shape, target),
14961                (WitShape::Http, WitTarget::Http { .. })
14962                    | (WitShape::PubSub, WitTarget::PubSub { .. })
14963                    | (WitShape::Store, WitTarget::Store { .. })
14964                    | (WitShape::Capability, WitTarget::Capability)
14965            );
14966            assert!(
14967                agree,
14968                "WitShape::classify({wit:?}) and WitContract::target arm-identity disagree",
14969            );
14970        }
14971    }
14972
14973    #[test]
14974    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
14975        // Composition-witness pin: [`wit_shape_matches`] agrees with
14976        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
14977        // dispatch (the prior non-`const` implementation) across
14978        // boundary lengths — empty `wit`, empty prefix, one-byte
14979        // slack, prefix longer than `wit`, one-byte trailing slack.
14980        // The rewrite to a byte-level manual starts_with loop (the
14981        // enabler for the `pub const fn` posture) must not change any
14982        // truth-table entry on the canonical accept-set — this pin
14983        // sweeps a targeted boundary corpus and asserts byte-for-byte
14984        // agreement, locking the const-fn rewrite's semantics against
14985        // the prior iterator body by construction.
14986        let prefixes = &["wasi:http/", "http:"][..];
14987        let cases: [(&str, bool); 12] = [
14988            ("wasi:http/proxy", true),
14989            ("wasi:http/", true), // exact-length match on prefix
14990            ("wasi:http", false), // one byte short
14991            ("http:", true),
14992            ("http:incoming", true),
14993            ("http", false), // one byte short
14994            ("", false),
14995            ("wasi:https/proxy", false),
14996            ("nats:events", false),
14997            ("HTTPS:", false), // uppercase — no case-fold in classifier
14998            ("wasi:HTTP/proxy", false),
14999            ("wasi:http", false),
15000        ];
15001        for (wit, expected) in cases {
15002            assert_eq!(
15003                wit_shape_matches(wit, prefixes),
15004                expected,
15005                "wit_shape_matches disagrees with reference at wit={wit:?}",
15006            );
15007            // Byte-equal to the iterator body it replaced.
15008            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
15009            assert_eq!(
15010                wit_shape_matches(wit, prefixes),
15011                via_iter,
15012                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
15013            );
15014        }
15015        // Empty prefix set → always false regardless of `wit`.
15016        let empty: &[&str] = &[];
15017        assert!(!wit_shape_matches("", empty));
15018        assert!(!wit_shape_matches("wasi:http/proxy", empty));
15019        // Empty prefix inside a non-empty set → always true (every
15020        // string starts with the empty string, matching the
15021        // iterator body's semantics on `str::starts_with("")`).
15022        let contains_empty: &[&str] = &["nats:", ""];
15023        assert!(wit_shape_matches("", contains_empty));
15024        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
15025    }
15026
15027    #[test]
15028    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
15029        // 4-way partition-witness pin: for every canonical prefix in
15030        // the payload-arm accept-sets, exactly one of the four
15031        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
15032        // [`WitContract::is_store`] / [`WitContract::is_capability`]
15033        // predicates returns `true` and the other three return `false`
15034        // — the four-arm partition witness that locks the substrate's
15035        // WIT-shape-space closure on the pre-projection axis load-
15036        // bearing. A future arm addition (a hypothetical fourth
15037        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
15038        // shape) that landed on one of the payload-arm predicates
15039        // without shrinking [`WitContract::is_capability`]'s accept-set
15040        // would surface here as two arms returning `true` simultaneously
15041        // — a partition-witness break the pin catches at caixa-core
15042        // build time rather than a silent per-consumer misclassification
15043        // at renderer emit time. Peer of the sibling `WitTarget`-side
15044        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
15045        // partition-witness pin on the post-projection payload-scalar
15046        // arm-set — extends the discipline onto the pre-projection
15047        // 4-arm shape-space.
15048        for shape_set in [
15049            WIT_HTTP_SHAPE_PREFIXES,
15050            WIT_PUBSUB_SHAPE_PREFIXES,
15051            WIT_STORE_SHAPE_PREFIXES,
15052        ] {
15053            for prefix in shape_set {
15054                let c = WitContract {
15055                    de: "cart".into(),
15056                    para: "catalog".into(),
15057                    wit: format!("{prefix}x"),
15058                    endpoint: None,
15059                    subject: None,
15060                    slot: None,
15061                };
15062                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
15063                    .iter()
15064                    .filter(|&&b| b)
15065                    .count();
15066                assert_eq!(
15067                    hits,
15068                    1,
15069                    "WitContract WIT-shape 4-way predicate partition must \
15070                     admit exactly one arm per canonical prefix; got {hits} \
15071                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
15072                     is_capability={})",
15073                    c.wit,
15074                    c.is_http(),
15075                    c.is_pubsub(),
15076                    c.is_store(),
15077                    c.is_capability(),
15078                );
15079            }
15080        }
15081        // Capability-arm sweep: two representative capability shapes
15082        // (a bare WIT world outside the three payload-arm prefix sets,
15083        // and the deliberately-shaped empty string that
15084        // [`crate::render::is_wit_world_ref`] rejects at
15085        // [`WitContract::target`] time but which the pure classifier
15086        // still admits — see the method docstring's "purely syntactic
15087        // classification" note). Both must land on the fourth arm
15088        // exclusively, so the partition witness holds across the full
15089        // 4-arm closure.
15090        for wit in ["custom:capability-only", ""] {
15091            let c = WitContract {
15092                de: "cart".into(),
15093                para: "catalog".into(),
15094                wit: wit.into(),
15095                endpoint: None,
15096                subject: None,
15097                slot: None,
15098            };
15099            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
15100                .iter()
15101                .filter(|&&b| b)
15102                .count();
15103            assert_eq!(
15104                hits, 1,
15105                "WitContract WIT-shape 4-way predicate partition must \
15106                 admit exactly one arm on Capability-shaped wit={wit:?}"
15107            );
15108            assert!(
15109                c.is_capability(),
15110                "wit={wit:?} must project onto the Capability arm"
15111            );
15112        }
15113    }
15114
15115    #[test]
15116    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
15117        // Composition-witness pin: [`WitContract::is_capability`] is the
15118        // exact-inverse disjunction of the sibling payload-arm predicate
15119        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
15120        // [`WitContract::is_store`]. A future reimplementation that
15121        // grew its own prefix-set scan (e.g. inlining a fourth
15122        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
15123        // own today) rather than delegating to the sibling trio would
15124        // drift loudly here — the composition contract binds the
15125        // fourth-arm predicate to the exact-inverse of the three
15126        // payload-arm predicates, so any rebrand of any prefix-set const
15127        // flows through this method by construction without a
15128        // coordinated per-consumer rewrite. Sweeps the union of the
15129        // three payload-arm prefix sets plus two Capability-shaped
15130        // shapes (a bare non-prefix-matching WIT world, the deliberately-
15131        // empty string the pure classifier still admits per the method
15132        // docstring's "purely syntactic classification" note).
15133        let mut cases: Vec<String> = Vec::new();
15134        for shape_set in [
15135            WIT_HTTP_SHAPE_PREFIXES,
15136            WIT_PUBSUB_SHAPE_PREFIXES,
15137            WIT_STORE_SHAPE_PREFIXES,
15138        ] {
15139            for prefix in shape_set {
15140                cases.push(format!("{prefix}x"));
15141            }
15142        }
15143        cases.push("custom:capability-only".to_string());
15144        cases.push(String::new());
15145        for wit in cases {
15146            let c = WitContract {
15147                de: "cart".into(),
15148                para: "catalog".into(),
15149                wit: wit.clone(),
15150                endpoint: None,
15151                subject: None,
15152                slot: None,
15153            };
15154            assert_eq!(
15155                c.is_capability(),
15156                !c.is_http() && !c.is_pubsub() && !c.is_store(),
15157                "WitContract::is_capability must equal \
15158                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
15159            );
15160        }
15161    }
15162
15163    #[test]
15164    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
15165        // Cross-projection-witness pin: whenever [`WitContract::target`]
15166        // succeeds, the pre-projection [`WitContract::is_capability`]
15167        // classification agrees with the post-projection
15168        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
15169        // predicate — the 4-arm typed partition on the substrate's
15170        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
15171        // partition on the pre-projection axis line up by construction.
15172        // A future divergence between the two axes (a peer
15173        // [`WitTarget`] variant addition that landed on the typed-view
15174        // surface without a peer prefix-set + [`WitContract`] predicate
15175        // extension, or vice versa) would surface here at caixa-core
15176        // build time rather than a silent per-consumer split at renderer
15177        // emit time. Peer of the sibling pre-/post-projection
15178        // agreement pins the payload-carrier trio
15179        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
15180        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
15181        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
15182        // post-projection — b11bb49 trio lift) already carry across the
15183        // three payload arms — this pin closes the pair on the fourth
15184        // payload-less arm.
15185        let http = WitContract {
15186            de: "cart".into(),
15187            para: "catalog".into(),
15188            wit: "wasi:http/proxy".into(),
15189            endpoint: Some("/x".into()),
15190            subject: None,
15191            slot: None,
15192        };
15193        assert!(!http.is_capability());
15194        assert!(!http.target().unwrap().is_capability());
15195
15196        let nats = WitContract {
15197            de: "cart".into(),
15198            para: "catalog".into(),
15199            wit: "nats:pub-sub".into(),
15200            endpoint: None,
15201            subject: Some("events.x".into()),
15202            slot: None,
15203        };
15204        assert!(!nats.is_capability());
15205        assert!(!nats.target().unwrap().is_capability());
15206
15207        let kv = WitContract {
15208            de: "cart".into(),
15209            para: "catalog".into(),
15210            wit: "wasi:keyvalue/store".into(),
15211            endpoint: None,
15212            subject: None,
15213            slot: Some("checkout/$orderId".into()),
15214        };
15215        assert!(!kv.is_capability());
15216        assert!(!kv.target().unwrap().is_capability());
15217
15218        let cap = WitContract {
15219            de: "cart".into(),
15220            para: "catalog".into(),
15221            wit: "custom:capability-only".into(),
15222            endpoint: None,
15223            subject: None,
15224            slot: None,
15225        };
15226        assert!(cap.is_capability());
15227        assert!(cap.target().unwrap().is_capability());
15228    }
15229
15230    #[test]
15231    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
15232        // Fail-before-pass-after pin on the [`WitContract`] pre-
15233        // projection accessor family's `const`-eval-surface posture.
15234        // Each of the three per-`:contratos` byte-string scalar
15235        // accessors ([`WitContract::source`] / [`WitContract::destination`]
15236        // / [`WitContract::world_ref`], each projecting through
15237        // `String::as_str` — const-stable since Rust 1.87, well within
15238        // the workspace MSRV) and each of the four peer WIT-shape
15239        // predicates ([`WitContract::is_http`] /
15240        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
15241        // [`WitContract::is_capability`], each composing
15242        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
15243        // free-function classifier family the sibling
15244        // [`wit_shape_classifier_family_is_const_fn`] pin already
15245        // anchors on the raw `&str → bool` axis) must be `pub const fn`
15246        // — any future accidental downgrade to non-`const` fails the
15247        // `const fn` wrappers below at caixa-core build time with E0015
15248        // (`cannot call non-const function`), strictly stronger than a
15249        // runtime `assert!` and strictly stronger than a
15250        // module-scope `const _: () = assert!(…)` pin (which cannot be
15251        // formed on a `&WitContract` fixture because the type's
15252        // `String` / `Option<String>` carriers rule out `const`-context
15253        // construction; the `const fn` wrapper is the load-bearing
15254        // shape that side-steps the destructor-in-const restriction on
15255        // the value axis while still pinning the `const`-fn posture on
15256        // the callee).
15257        //
15258        // Peer of the sibling free-function classifier pin
15259        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
15260        // raw `&str → bool` axis — this pin extends the same
15261        // `const`-eval-surface discipline onto the peer method surface
15262        // that composes through those free-function classifiers, and
15263        // simultaneously onto the underlying per-`:contratos`
15264        // byte-string scalar-accessor trio each predicate reads
15265        // through. Sibling of the peer M3
15266        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
15267        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
15268        // M2
15269        // [`child_spec_restart_accessor_is_const_fn`] /
15270        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
15271        // and M3
15272        // [`placement_estrategia_accessor_is_const_fn`] /
15273        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
15274        // sibling `const`-eval-surface-pass axes.
15275        const fn source_via_const_fn(c: &WitContract) -> &str {
15276            c.source()
15277        }
15278        const fn destination_via_const_fn(c: &WitContract) -> &str {
15279            c.destination()
15280        }
15281        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
15282            c.world_ref()
15283        }
15284        const fn is_http_via_const_fn(c: &WitContract) -> bool {
15285            c.is_http()
15286        }
15287        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
15288            c.is_pubsub()
15289        }
15290        const fn is_store_via_const_fn(c: &WitContract) -> bool {
15291            c.is_store()
15292        }
15293        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
15294            c.is_capability()
15295        }
15296        // Sweep one canonical accept-set sample per WIT-shape arm plus
15297        // a payload-less capability sample, asserting the wrapper and
15298        // direct dispatches agree byte-for-byte across the closed
15299        // 4-arm partition on both the scalar-accessor trio and the
15300        // WIT-shape-predicate family.
15301        for (wit, is_http, is_pubsub, is_store, is_capability) in [
15302            ("wasi:http/proxy", true, false, false, false),
15303            ("http:incoming", true, false, false, false),
15304            ("nats:events", false, true, false, false),
15305            ("kafka:topic", false, true, false, false),
15306            ("wasi:keyvalue/store", false, false, true, false),
15307            ("kv:cache", false, false, true, false),
15308            ("custom:capability-only", false, false, false, true),
15309            ("", false, false, false, true),
15310        ] {
15311            let c = WitContract {
15312                de: "cart".into(),
15313                para: "catalog".into(),
15314                wit: wit.into(),
15315                endpoint: None,
15316                subject: None,
15317                slot: None,
15318            };
15319            assert_eq!(source_via_const_fn(&c), c.source());
15320            assert_eq!(destination_via_const_fn(&c), c.destination());
15321            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
15322            assert_eq!(is_http_via_const_fn(&c), c.is_http());
15323            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
15324            assert_eq!(is_store_via_const_fn(&c), c.is_store());
15325            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
15326            assert_eq!(c.source(), "cart");
15327            assert_eq!(c.destination(), "catalog");
15328            assert_eq!(c.world_ref(), wit);
15329            assert_eq!(c.is_http(), is_http);
15330            assert_eq!(c.is_pubsub(), is_pubsub);
15331            assert_eq!(c.is_store(), is_store);
15332            assert_eq!(c.is_capability(), is_capability);
15333        }
15334    }
15335
15336    #[test]
15337    fn wit_contract_identity_projection_accessor_is_const_fn() {
15338        // Fail-before-pass-after pin on the [`WitContract::identity`]
15339        // six-arm composite-projection accessor's `const`-eval-surface
15340        // posture. The accessor projects the typed edge's six identity
15341        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
15342        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
15343        // every callee is itself `pub const fn` ([`WitContract::source`]
15344        // / [`WitContract::destination`] / [`WitContract::world_ref`]
15345        // through `String::as_str`, const-stable since Rust 1.87;
15346        // [`WitContract::endpoint`] / [`WitContract::subject`] /
15347        // [`WitContract::slot`] through the sibling `match &self
15348        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
15349        // 0650f64 closed the const-eval surface on) and the tuple
15350        // constructor from borrowed-reference / `Option`-of-borrowed-
15351        // reference arms is trivially const. Any future accidental
15352        // downgrade fails the `identity_via_const_fn` wrapper at
15353        // caixa-core build time with E0015 (`cannot call non-const
15354        // method`), strictly stronger than a runtime `assert!` and
15355        // strictly stronger than a module-scope `const _: () =
15356        // assert!(…)` pin (which cannot be formed on a `&WitContract`
15357        // fixture because the type's `String` / `Option<String>`
15358        // carriers rule out `const`-context value construction; the
15359        // `const fn` wrapper is the load-bearing shape that side-steps
15360        // the destructor-in-const restriction on the value axis while
15361        // still pinning the `const`-fn posture on the callee — mirror
15362        // of the sibling
15363        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
15364        // pin's discipline verbatim on the peer scalar-accessor
15365        // surface).
15366        //
15367        // Peer of the sibling
15368        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
15369        // (279823b) pin on the six per-`:contratos` scalar-accessor
15370        // callees this composite-projection reads through — where that
15371        // pin anchors the const-eval surface at the six individual
15372        // scalar-accessor arms, this pin extends the same posture onto
15373        // the composite six-tuple projection every consumer that dedups
15374        // typed edges on the [`ContratoIdentity`] axis keys off (the
15375        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
15376        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
15377        // materializer's per-edge identity-based admission webhook; a
15378        // future L7 policy-emitter that shards CNPs by identity-tuple
15379        // rather than by name). Same fail-before-pass-after wrapper
15380        // discipline as the peer M2 / M3 accessor-family pins on the
15381        // sibling `const`-eval-surface passes.
15382        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
15383            c.identity()
15384        }
15385        // Sweep one canonical WIT-shape sample per payload-carrier arm
15386        // plus a payload-less capability sample so the pin exercises
15387        // both `Some(_)`-carrying and `None`-carrying arms on all three
15388        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
15389        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
15390        // with the direct method call on every arm of the closed WIT-
15391        // shape partition.
15392        for (wit, endpoint, subject, slot) in [
15393            ("wasi:http/proxy", Some("/checkout"), None, None),
15394            ("http:incoming", Some("/api"), None, None),
15395            ("nats:events", None, Some("orders.placed"), None),
15396            ("kafka:topic", None, Some("orders.stream"), None),
15397            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
15398            ("kv:cache", None, None, Some("session/{token}")),
15399            ("custom:capability-only", None, None, None),
15400        ] {
15401            let c = WitContract {
15402                de: "cart".into(),
15403                para: "catalog".into(),
15404                wit: wit.into(),
15405                endpoint: endpoint.map(str::to_string),
15406                subject: subject.map(str::to_string),
15407                slot: slot.map(str::to_string),
15408            };
15409            assert_eq!(identity_via_const_fn(&c), c.identity());
15410            assert_eq!(
15411                c.identity(),
15412                ("cart", "catalog", wit, endpoint, subject, slot,),
15413            );
15414        }
15415    }
15416
15417    #[test]
15418    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
15419        // Fail-before-pass-after pin on the four M3 mesh-slot
15420        // `String → &str` scalar accessors ([`Membro::nome`] /
15421        // [`Membro::versao_requirement`] on the per-`:membros` axis,
15422        // [`Entrada::hostname`] / [`Entrada::destination`] on the
15423        // per-`:entrada` axis) — each projects the typed slot's
15424        // [`String`] storage through the `pub const fn`
15425        // [`String::as_str`] (const-stable since Rust 1.87, well
15426        // within the workspace MSRV) and any future accidental
15427        // downgrade to non-`const` fails the corresponding
15428        // `<name>_via_const_fn` wrapper at caixa-core build time with
15429        // E0015 (`cannot call non-const method`), strictly stronger
15430        // than a runtime `assert!` and strictly stronger than a
15431        // module-scope `const _: () = assert!(…)` pin (which cannot
15432        // be formed on `&Membro` / `&Entrada` fixtures because the
15433        // types' `String` carriers rule out `const`-context value
15434        // construction; the `const fn` wrapper is the load-bearing
15435        // shape that side-steps the destructor-in-const restriction
15436        // on the value axis while still pinning the `const`-fn
15437        // posture on the callee — mirror of the sibling
15438        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
15439        // (279823b) pin on the per-`:contratos` axis). Peer of the
15440        // sibling per-M2/M3/universal-axis `String → &str` accessor
15441        // family pins on the sibling `const`-eval-surface passes
15442        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
15443        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
15444        // typed-newtype wrapper,
15445        // [`crate::supervisor::ChildSpec::nome`] /
15446        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
15447        // M2 supervisor-tree axis,
15448        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
15449        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
15450        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
15451        // axis, and the sibling per-`:contratos`
15452        // [`WitContract::source`] / [`WitContract::destination`] /
15453        // [`WitContract::world_ref`] trio at 279823b).
15454        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
15455            m.nome()
15456        }
15457        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
15458            m.versao_requirement()
15459        }
15460        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
15461            e.hostname()
15462        }
15463        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
15464            e.destination()
15465        }
15466        for (caixa, versao) in [
15467            ("cart", "^0.1"),
15468            ("catalog-v2", "~0.2.3"),
15469            ("checkout", "*"),
15470        ] {
15471            let m = Membro {
15472                caixa: caixa.into(),
15473                versao: versao.into(),
15474            };
15475            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
15476            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
15477            assert_eq!(m.nome(), caixa);
15478            assert_eq!(m.versao_requirement(), versao);
15479        }
15480        for (host, para) in [
15481            ("cart.example.com", "cart"),
15482            ("api.checkout.io", "checkout"),
15483        ] {
15484            let e = Entrada {
15485                host: host.into(),
15486                para: para.into(),
15487                paths: vec![],
15488                port: DEFAULT_SERVICO_PORT,
15489            };
15490            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
15491            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
15492            assert_eq!(e.hostname(), host);
15493            assert_eq!(e.destination(), para);
15494        }
15495    }
15496
15497    #[test]
15498    fn m3_option_string_scalar_accessor_family_is_const_fn() {
15499        // Fail-before-pass-after pin on the five M3 mesh-slot
15500        // `Option<String> → Option<&str>` scalar accessors
15501        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
15502        // [`WitContract::slot`] on the per-`:contratos` HTTP /
15503        // pub-sub / key-value payload-carrier trio,
15504        // [`Placement::shard_key`] / [`Placement::affinity`] on the
15505        // per-`:placement` Akka-sharding-key + Adaptive-compression-
15506        // hint pair). Each accessor destructures the typed slot's
15507        // `Option<String>` storage through the `match &self.<field> {
15508        // Some(s) => Some(s.as_str()), None => None }` shape —
15509        // routing through [`String::as_str`] (const-stable since Rust
15510        // 1.87, well within the workspace MSRV) rather than the
15511        // non-const [`Option::as_deref`] the pre-lift bodies carried
15512        // — and any future accidental downgrade to non-`const` fails
15513        // the corresponding `<name>_via_const_fn` wrapper at
15514        // caixa-core build time with E0015 (`cannot call non-const
15515        // method`), strictly stronger than a runtime `assert!` and
15516        // strictly stronger than a module-scope `const _: () =
15517        // assert!(…)` pin (which cannot be formed on `&WitContract`
15518        // / `&Placement` fixtures because the types' `String` /
15519        // `Option<String>` carriers rule out `const`-context value
15520        // construction; the `const fn` wrapper is the load-bearing
15521        // shape that side-steps the destructor-in-const restriction
15522        // on the value axis while still pinning the `const`-fn
15523        // posture on the callee — mirror of the sibling
15524        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
15525        // (279823b) and
15526        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
15527        // (29c5d7e) pins on the peer `String → &str` axes at the same
15528        // structs).
15529        //
15530        // Peer of the sibling per-`Caixa` `Option<String> →
15531        // Option<&str>` accessor family pin
15532        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
15533        // on the top-level manifest's optional universal-axis surface
15534        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
15535        // `:restart-window`).
15536        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
15537            w.endpoint()
15538        }
15539        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
15540            w.subject()
15541        }
15542        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
15543            w.slot()
15544        }
15545        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
15546            p.shard_key()
15547        }
15548        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
15549            p.affinity()
15550        }
15551        // Sweep every closed shape-arm partition on the
15552        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
15553        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
15554        // pair None), key-value (`:slot` Some, sibling pair None),
15555        // and Capability (all three None) so each accessor's
15556        // Some/None arm carries a pin through the const dispatch.
15557        for (wit, endpoint, subject, slot) in [
15558            ("wasi:http/proxy", Some("/api"), None, None),
15559            ("nats:pub-sub", None, Some("orders.paid"), None),
15560            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
15561            ("custom:capability-only", None, None, None),
15562        ] {
15563            let c = WitContract {
15564                de: "cart".into(),
15565                para: "catalog".into(),
15566                wit: wit.into(),
15567                endpoint: endpoint.map(str::to_string),
15568                subject: subject.map(str::to_string),
15569                slot: slot.map(str::to_string),
15570            };
15571            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
15572            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
15573            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
15574            assert_eq!(c.endpoint(), endpoint);
15575            assert_eq!(c.subject(), subject);
15576            assert_eq!(c.slot(), slot);
15577        }
15578        // Sweep both `Some`/`None` arms on each per-`:placement`
15579        // optional-scalar so the shard-key + affinity pair carries a
15580        // const-dispatch pin on both arms.
15581        for (shard_key, affinity) in [
15582            (Some("tenantId"), Some("data-locality")),
15583            (Some("$tenantId"), None),
15584            (None, Some("low-latency")),
15585            (None, None),
15586        ] {
15587            let p = Placement {
15588                estrategia: PlacementStrategy::default(),
15589                clusters: vec![],
15590                affinity: affinity.map(str::to_string),
15591                shard_key: shard_key.map(str::to_string),
15592            };
15593            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
15594            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
15595            assert_eq!(p.shard_key(), shard_key);
15596            assert_eq!(p.affinity(), affinity);
15597        }
15598    }
15599
15600    #[test]
15601    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
15602        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
15603        // composite `Vec → &[String]` slice-return accessors on
15604        // [`Placement::clusters`] and [`Entrada::paths`]. Each
15605        // destructures the typed slot's `Vec<String>` storage through
15606        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
15607        // 1.66, well within the workspace MSRV) — any future accidental
15608        // downgrade to non-`const` fails the corresponding
15609        // `<name>_via_const_fn` wrapper at caixa-core build time with
15610        // E0015 (`cannot call non-const method`), strictly stronger
15611        // than a runtime `assert!`. Sibling of the peer
15612        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
15613        // pin on the outer-`AplicacaoSpec` reference-return family
15614        // (`:membros` / `:contratos` slice-return + `:politicas` /
15615        // `:placement` / `:entrada` composite-reference), and of the
15616        // peer M2 slice-return axis pins
15617        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
15618        // (on `SupervisorSpec::children`) and
15619        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
15620        // (on `UpgradeFromEntry::instructions`). Together the four
15621        // pins close the last unlifted reference-return accessor
15622        // family across the substrate primitive.
15623        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
15624            p.clusters()
15625        }
15626        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
15627            e.paths()
15628        }
15629        // Sweep both the empty-Vec (no author-declared entries) and
15630        // the populated-Vec arms on every slice-return accessor so
15631        // each carries a const-dispatch pin on both arms.
15632        let p_empty = Placement {
15633            estrategia: PlacementStrategy::default(),
15634            clusters: vec![],
15635            affinity: None,
15636            shard_key: None,
15637        };
15638        let p_full = Placement {
15639            estrategia: PlacementStrategy::default(),
15640            clusters: vec!["prod-a".into(), "prod-b".into()],
15641            affinity: None,
15642            shard_key: None,
15643        };
15644        assert_eq!(
15645            placement_clusters_via_const_fn(&p_empty),
15646            p_empty.clusters()
15647        );
15648        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
15649        assert!(p_empty.clusters().is_empty());
15650        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
15651        let e_empty = Entrada {
15652            host: "web.example.com".into(),
15653            para: "web".into(),
15654            paths: vec![],
15655            port: DEFAULT_SERVICO_PORT,
15656        };
15657        let e_full = Entrada {
15658            host: "web.example.com".into(),
15659            para: "web".into(),
15660            paths: vec!["/api".into(), "/health".into()],
15661            port: DEFAULT_SERVICO_PORT,
15662        };
15663        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
15664        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
15665        assert!(e_empty.paths().is_empty());
15666        assert_eq!(e_full.paths(), &["/api", "/health"]);
15667    }
15668
15669    #[test]
15670    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
15671        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
15672        // reference-return accessors — the two `Vec → &[T]` slice-
15673        // return accessors on [`AplicacaoSpec::membros`] and
15674        // [`AplicacaoSpec::contratos`] (each routes through the
15675        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
15676        // 1.66), the two `&Composite` composite-reference accessors
15677        // on [`AplicacaoSpec::politicas`] and
15678        // [`AplicacaoSpec::placement`] (each routes through a raw
15679        // `&self.<field>` borrow, trivially const), and the one
15680        // `Option<&Composite>` optional-composite-reference accessor
15681        // on [`AplicacaoSpec::entrada`] (routes through the
15682        // `pub const fn` [`Option::as_ref`], const-stable since Rust
15683        // 1.83). Any future accidental downgrade to non-`const` fails
15684        // the corresponding `<name>_via_const_fn` wrapper at caixa-
15685        // core build time with E0015 (`cannot call non-const
15686        // method`), strictly stronger than a runtime `assert!`.
15687        // Sibling of the peer inner-composite pin
15688        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
15689        // on the `Placement::clusters` + `Entrada::paths` slice-
15690        // return pair, and of the peer M2 axis pins on
15691        // [`crate::supervisor::SupervisorSpec::children`] and
15692        // [`crate::upgrade::UpgradeFromEntry::instructions`].
15693        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
15694            s.membros()
15695        }
15696        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
15697            s.contratos()
15698        }
15699        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
15700            s.politicas()
15701        }
15702        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
15703            s.placement()
15704        }
15705        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
15706            s.entrada()
15707        }
15708        // Construct both a minimal "no :entrada" (internal-only
15709        // mesh) and a full "with :entrada" (external-gateway)
15710        // fixture so the family pins both the `None`-arm (author-
15711        // omitted `:entrada`) and the `Some`-arm (author-declared
15712        // `:entrada`) on the optional-composite axis.
15713        let membro = Membro {
15714            caixa: "web".into(),
15715            versao: "^0.1".into(),
15716        };
15717        let entrada_full = Entrada {
15718            host: "web.example.com".into(),
15719            para: "web".into(),
15720            paths: vec!["/api".into()],
15721            port: DEFAULT_SERVICO_PORT,
15722        };
15723        let internal_only = AplicacaoSpec {
15724            membros: vec![membro.clone()],
15725            contratos: vec![],
15726            politicas: MeshPolicy::default(),
15727            placement: Placement::default(),
15728            entrada: None,
15729        };
15730        let with_entrada = AplicacaoSpec {
15731            membros: vec![membro],
15732            contratos: vec![],
15733            politicas: MeshPolicy::default(),
15734            placement: Placement::default(),
15735            entrada: Some(entrada_full),
15736        };
15737        assert_eq!(
15738            aplicacao_membros_via_const_fn(&internal_only),
15739            internal_only.membros()
15740        );
15741        assert_eq!(
15742            aplicacao_membros_via_const_fn(&with_entrada),
15743            with_entrada.membros()
15744        );
15745        assert_eq!(
15746            aplicacao_contratos_via_const_fn(&internal_only),
15747            internal_only.contratos()
15748        );
15749        assert!(std::ptr::eq(
15750            aplicacao_politicas_via_const_fn(&internal_only),
15751            internal_only.politicas(),
15752        ));
15753        assert!(std::ptr::eq(
15754            aplicacao_placement_via_const_fn(&internal_only),
15755            internal_only.placement(),
15756        ));
15757        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
15758        match (
15759            aplicacao_entrada_via_const_fn(&with_entrada),
15760            with_entrada.entrada(),
15761        ) {
15762            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
15763            _ => panic!(
15764                "aplicacao_entrada_via_const_fn must agree with \
15765                 AplicacaoSpec::entrada on the Some-arm reference"
15766            ),
15767        }
15768    }
15769
15770    #[test]
15771    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
15772        // Load-bearing contract pin: on every canonical
15773        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
15774        // [`WitContract::target_projected`] returns byte-equal to
15775        // [`WitContract::target`]`().unwrap()` — the post-validation
15776        // projection accessor is a thin panicking wrapper over the
15777        // pre-validation validator, no extra work in the projection
15778        // path. Any future divergence (a validator-side normalization
15779        // the projection doesn't route through, an accessor-side
15780        // caching layer the validator doesn't populate) would surface
15781        // here at caixa-core build time rather than a silent per-consumer
15782        // split at renderer emit time. Sweeps the closed 4-arm
15783        // [`WitTarget`] partition ([`WitTarget::Http`] /
15784        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
15785        // [`WitTarget::Capability`]) so every arm carries a byte-equality
15786        // pin on the two-accessor pair.
15787        for (wit, endpoint, subject, slot) in [
15788            ("wasi:http/proxy", Some("/x"), None, None),
15789            ("nats:pub-sub", None, Some("events.x"), None),
15790            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
15791            ("custom:capability-only", None, None, None),
15792        ] {
15793            let c = WitContract {
15794                de: "cart".into(),
15795                para: "catalog".into(),
15796                wit: wit.into(),
15797                endpoint: endpoint.map(str::to_string),
15798                subject: subject.map(str::to_string),
15799                slot: slot.map(str::to_string),
15800            };
15801            assert_eq!(
15802                c.target_projected(),
15803                c.target().unwrap(),
15804                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
15805            );
15806        }
15807    }
15808
15809    #[test]
15810    #[should_panic(expected = "validated by typed_view")]
15811    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
15812        // Panic-path pin: [`WitContract::target_projected`] threads the
15813        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
15814        // through its expect-panic when called on a contract whose
15815        // (`:wit`, payload) shape has not been crossed by
15816        // [`AplicacaoSpec::validate`] — a contract with a structurally-
15817        // invalid `:wit` (hyphen-for-colon typo) that would surface
15818        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
15819        // A future rebrand on the panic-message axis would land at one
15820        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
15821        // and this pin's [`should_panic(expected = …)`] literal would
15822        // migrate alongside — the pin catches drift between the const
15823        // and the accessor's `expect(…)` call by construction.
15824        let c = WitContract {
15825            de: "cart".into(),
15826            para: "catalog".into(),
15827            // Hyphen-for-colon typo: `WitContract::target` returns
15828            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
15829            // driving the [`WitContract::target_projected`] expect-panic.
15830            wit: "wasi-http/proxy".into(),
15831            endpoint: Some("/x".into()),
15832            subject: None,
15833            slot: None,
15834        };
15835        let _ = c.target_projected();
15836    }
15837
15838    #[test]
15839    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
15840        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
15841        // carries the exact byte-string the two prior open-coded
15842        // `.target().expect("validated by typed_view")` production
15843        // consumers threaded through inline before this lift converged
15844        // them onto [`WitContract::target_projected`] — the caixa-mesh
15845        // per-`(:de, :para)` CNP L7 introspection branch at
15846        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
15847        // graph` per-`:contratos` payload-column printer at
15848        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
15849        // byte-string load-bearing so a well-meaning const-side rebrand
15850        // that didn't carry a matched pin migration would surface here
15851        // at caixa-core build time rather than a silent per-consumer
15852        // panic-message drift at cluster-apply time. Peer of the
15853        // sibling [`WitTarget::CAPABILITY_LABEL`] /
15854        // [`WitTarget::CAPABILITY_EXPECTED`] /
15855        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
15856        // the paired payload-less-arm scalar-const family.
15857        assert_eq!(
15858            WitContract::PROJECTED_INVARIANT_MSG,
15859            "validated by typed_view"
15860        );
15861    }
15862
15863    #[test]
15864    fn empty_wit_takes_precedence_over_invalid() {
15865        // Ordering pin: `EmptyWit` is the more self-locating
15866        // diagnostic on `""` and must lead — the value-shape gate is
15867        // only reached after the empty-check fires. Mirrors
15868        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15869        // the peer payload axis.
15870        let mut s = three_member_spec();
15871        s.contratos.push(WitContract {
15872            de: "payment".into(),
15873            para: "catalog".into(),
15874            wit: String::new(),
15875            endpoint: None,
15876            subject: None,
15877            slot: None,
15878        });
15879        let err = s.validate().unwrap_err();
15880        assert!(
15881            matches!(err, AplicacaoError::EmptyWit { .. }),
15882            "got {err:?}"
15883        );
15884    }
15885
15886    #[test]
15887    fn wit_invalid_fires_before_payload_shape_arm() {
15888        // Ordering pin: a malformed `:wit` surfaces *its own*
15889        // diagnostic (which names the offending wit verbatim) before
15890        // any payload-field check — a contrato whose wit is
15891        // structurally invalid AND carries a wrong target field
15892        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
15893        // because the dispatch on the wit is what decides which
15894        // payload field is "right" in the first place. Without this
15895        // ordering, the author would see "wrong target field" for a
15896        // wit that hasn't even been parsed, which doesn't name the
15897        // root cause.
15898        let mut s = three_member_spec();
15899        s.contratos.push(WitContract {
15900            de: "payment".into(),
15901            para: "catalog".into(),
15902            // Hyphen-for-colon typo + endpoint set: pre-gate this
15903            // raised `ContratoWrongTarget { expected: "none" }` (the
15904            // Capability arm rejecting the endpoint), masking the
15905            // real authoring mistake (the wit isn't `wasi:http/proxy`).
15906            wit: "wasi-http/proxy".into(),
15907            endpoint: Some("/x".into()),
15908            subject: None,
15909            slot: None,
15910        });
15911        let err = s.validate().unwrap_err();
15912        assert!(
15913            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
15914                if wit == "wasi-http/proxy"),
15915            "got {err:?}"
15916        );
15917    }
15918
15919    #[test]
15920    fn wit_invalid_diagnostic_carries_offending_wit() {
15921        // Diagnostic-shape pin — the offending `:wit` + `:de` +
15922        // `:para` + a non-empty reason flow through verbatim so the
15923        // author can grep their caixa.lisp for the offending contrato
15924        // block and fix it in one edit. Same shape as
15925        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
15926        let err = contrato_wit_err("WASI:HTTP/proxy");
15927        match err {
15928            AplicacaoError::ContratoWitInvalid {
15929                de,
15930                para,
15931                wit,
15932                reason,
15933            } => {
15934                assert_eq!(de, "payment");
15935                assert_eq!(para, "catalog");
15936                assert_eq!(wit, "WASI:HTTP/proxy");
15937                assert!(!reason.is_empty(), "reason field must be non-empty");
15938            }
15939            other => panic!("expected ContratoWitInvalid, got {other:?}"),
15940        }
15941    }
15942
15943    // ── :contratos :subject value-shape gate ─────────────────────────────
15944    //
15945    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
15946    // suites on the peer payload axes. Until this gate landed
15947    // `WitContract::target()` only refused the empty string; a
15948    // structurally invalid subject silently passed validate and the
15949    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
15950    // Subject'` on publish / subscribe, or as a silent message drop,
15951    // far from the source caixa.lisp. Every authoring footgun the
15952    // NATS server's subject parser would catch on admission now
15953    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
15954    // offending `:subject` + `:de` + `:para` named verbatim. Same
15955    // diagnostic shape as `ContratoEndpointInvalid` /
15956    // `ContratoWitInvalid` on the peer payload axes; same shared
15957    // predicate (`crate::render::is_nats_subject`) ensures drift
15958    // between any two axes' rule enforcement is a build error at the
15959    // predicate, not piecemeal across renderers.
15960
15961    fn contrato_subject_err(subject: &str) -> AplicacaoError {
15962        // Fresh spec per call so the new contract doesn't collide on
15963        // identity with `three_member_spec`'s pre-existing entries.
15964        // The new edge uses `(payment, catalog)` — a pair the fixture
15965        // doesn't already declare — with `:wit "nats:pub-sub"` and the
15966        // varying `:subject`, so the subject-shape gate fires cleanly
15967        // after the wit-shape gate (which `"nats:pub-sub"` passes).
15968        let mut s = three_member_spec();
15969        s.contratos.push(WitContract {
15970            de: "payment".into(),
15971            para: "catalog".into(),
15972            wit: "nats:pub-sub".into(),
15973            endpoint: None,
15974            subject: Some(subject.into()),
15975            slot: None,
15976        });
15977        s.validate().unwrap_err()
15978    }
15979
15980    #[test]
15981    fn rejects_pubsub_contrato_subject_with_whitespace() {
15982        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
15983        // landed at the NATS server as a malformed subject the parser
15984        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
15985        // source caixa.lisp.
15986        let err = contrato_subject_err("foo bar");
15987        assert!(
15988            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15989                if subject == "foo bar" && reason.contains("whitespace")),
15990            "got {err:?}"
15991        );
15992    }
15993
15994    #[test]
15995    fn rejects_pubsub_contrato_subject_with_control_char() {
15996        let err = contrato_subject_err("foo\x01bar");
15997        assert!(
15998            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15999                if subject == "foo\x01bar" && reason.contains("control character")),
16000            "got {err:?}"
16001        );
16002    }
16003
16004    #[test]
16005    fn rejects_pubsub_contrato_subject_with_non_ascii() {
16006        // Un-percent-encoded non-ASCII byte — the canonical "I copied
16007        // the subject from a doc with smart quotes / accented
16008        // characters" footgun.
16009        let err = contrato_subject_err("foo.caf\u{e9}");
16010        assert!(
16011            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16012                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
16013            "got {err:?}"
16014        );
16015    }
16016
16017    #[test]
16018    fn rejects_pubsub_contrato_subject_with_leading_dot() {
16019        // Empty leading token — NATS rejects.
16020        let err = contrato_subject_err(".foo");
16021        assert!(
16022            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16023                if subject == ".foo" && reason.contains("must not start with `.`")),
16024            "got {err:?}"
16025        );
16026    }
16027
16028    #[test]
16029    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
16030        // Empty trailing token — NATS rejects. The remediation
16031        // (use `>` instead) is in the reason string.
16032        let err = contrato_subject_err("foo.");
16033        assert!(
16034            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16035                if subject == "foo." && reason.contains("must not end with `.`")),
16036            "got {err:?}"
16037        );
16038    }
16039
16040    #[test]
16041    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
16042        // The canonical "I forgot to fill in the middle segment"
16043        // typo — `"foo..bar"`. NATS rejects empty tokens.
16044        let err = contrato_subject_err("foo..bar");
16045        assert!(
16046            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16047                if subject == "foo..bar" && reason.contains("consecutive `.`")),
16048            "got {err:?}"
16049        );
16050    }
16051
16052    #[test]
16053    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
16054        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
16055        // as the final segment. Pre-gate this passed as a typed edge
16056        // and surfaced at runtime as a NATS subscribe rejection.
16057        let err = contrato_subject_err("foo.>.bar");
16058        assert!(
16059            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16060                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
16061            "got {err:?}"
16062        );
16063    }
16064
16065    #[test]
16066    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
16067        // `foo*.bar` — NATS wildcards are standalone tokens. The
16068        // remediation is in the reason string.
16069        let err = contrato_subject_err("foo*.bar");
16070        assert!(
16071            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16072                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
16073            "got {err:?}"
16074        );
16075    }
16076
16077    #[test]
16078    fn rejects_pubsub_contrato_subject_with_invalid_char() {
16079        // `foo,bar` — comma is not a valid NATS subject character.
16080        // Pinned separately from the wildcard arms so the invalid-
16081        // character diagnostic is in force.
16082        let err = contrato_subject_err("foo,bar");
16083        assert!(
16084            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16085                if subject == "foo,bar" && reason.contains("invalid character")),
16086            "got {err:?}"
16087        );
16088    }
16089
16090    #[test]
16091    fn rejects_pubsub_contrato_subject_too_long() {
16092        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
16093        // The legitimate-shape arms all pass (one all-`a` token, no
16094        // `.`, no wildcards); only the cap arm fires. Surfaces the
16095        // paste-from-binary / accidental-multi-line-blob landing
16096        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
16097        // on the peer axis.
16098        let big = "a".repeat(257);
16099        assert_eq!(big.len(), 257);
16100        let err = contrato_subject_err(&big);
16101        assert!(
16102            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16103                if subject == &big && reason.contains("max length of 256")),
16104            "got {err:?}"
16105        );
16106    }
16107
16108    #[test]
16109    fn pubsub_contrato_subject_max_length_validates() {
16110        // 256-byte subject — exactly the cap. Boundary pin: drift in
16111        // the cap surfaces here and at
16112        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
16113        // mirroring `http_contrato_endpoint_max_length_validates` and
16114        // `wit_max_length_validates` on the peer axes.
16115        let big = "a".repeat(256);
16116        assert_eq!(big.len(), 256);
16117        let mut s = three_member_spec();
16118        s.contratos.push(WitContract {
16119            de: "payment".into(),
16120            para: "catalog".into(),
16121            wit: "nats:pub-sub".into(),
16122            endpoint: None,
16123            subject: Some(big),
16124            slot: None,
16125        });
16126        s.validate().unwrap();
16127    }
16128
16129    #[test]
16130    fn pubsub_contrato_subject_accepts_canonical_forms() {
16131        // Positive-set sweep: every canonical NATS subject shape the
16132        // substrate-side `is_nats_subject` predicate accepts (the
16133        // multi-dot `events.order.charged`, the snake_case / kebab-
16134        // case / mixed-case tokens, the digit-bearing tokens, the
16135        // single-token wildcard `*` at every segment position, and
16136        // the trailing `>` multi-token wildcard) must remain a valid
16137        // contrato subject too. Drift between this list and the
16138        // substrate-side `nats_subject_accepts_canonical_forms` sweep
16139        // surfaces at the shared predicate — one source of truth.
16140        // Uses a fresh `(payment, catalog)` edge so none of the swept
16141        // subjects collide with the pre-existing entries in
16142        // `three_member_spec`.
16143        for subject in [
16144            "checkout.events.charge.failed",
16145            "rio.events.order.charged",
16146            "orders",
16147            "orders.123",
16148            "snake_case.token",
16149            "kebab-case.token",
16150            "MixedCase.Token",
16151            "orders.*.charged",
16152            "*.events.*",
16153            "orders.>",
16154        ] {
16155            let mut s = three_member_spec();
16156            s.contratos.push(WitContract {
16157                de: "payment".into(),
16158                para: "catalog".into(),
16159                wit: "nats:pub-sub".into(),
16160                endpoint: None,
16161                subject: Some(subject.into()),
16162                slot: None,
16163            });
16164            s.validate()
16165                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
16166        }
16167    }
16168
16169    #[test]
16170    fn contrato_subject_empty_takes_precedence_over_invalid() {
16171        // Ordering pin: `ContratoSubjectEmpty` is the more self-
16172        // locating diagnostic on `""` and must lead — the value-shape
16173        // gate is only reached after the empty-check fires. Mirrors
16174        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
16175        // the peer payload axis.
16176        let mut s = three_member_spec();
16177        s.contratos.push(WitContract {
16178            de: "payment".into(),
16179            para: "catalog".into(),
16180            wit: "nats:pub-sub".into(),
16181            endpoint: None,
16182            subject: Some(String::new()),
16183            slot: None,
16184        });
16185        let err = s.validate().unwrap_err();
16186        assert!(
16187            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
16188            "got {err:?}"
16189        );
16190    }
16191
16192    #[test]
16193    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
16194        // Diagnostic-shape pin — the offending `:subject` + `:de` +
16195        // `:para` + a non-empty reason flow through verbatim so the
16196        // author can grep their caixa.lisp for the offending contrato
16197        // block and fix it in one edit. Same shape as
16198        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
16199        // and `wit_invalid_diagnostic_carries_offending_wit`.
16200        let err = contrato_subject_err("foo..bar");
16201        match err {
16202            AplicacaoError::ContratoSubjectInvalid {
16203                de,
16204                para,
16205                subject,
16206                reason,
16207            } => {
16208                assert_eq!(de, "payment");
16209                assert_eq!(para, "catalog");
16210                assert_eq!(subject, "foo..bar");
16211                assert!(!reason.is_empty(), "reason field must be non-empty");
16212            }
16213            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
16214        }
16215    }
16216
16217    #[test]
16218    fn target_view_pubsub_subject_passes_through_to_typed_view() {
16219        // The compounding theorem on the pub-sub axis: every
16220        // `WitTarget::PubSub { subject }` returned by `target()` carries
16221        // a NATS-server-accepted subject. Renderers downstream of
16222        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
16223        // NATS Stream/Consumer CR emitter, the future `feira app graph`
16224        // view's subject labeller) can rely on this without re-checking
16225        // — the type system carries the proof. Mirrors
16226        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
16227        // on the peer axes.
16228        let nats = WitContract {
16229            de: "a".into(),
16230            para: "b".into(),
16231            wit: "nats:pub-sub".into(),
16232            endpoint: None,
16233            subject: Some("orders.events.*.charged".into()),
16234            slot: None,
16235        };
16236        match nats.target().unwrap() {
16237            WitTarget::PubSub { subject } => {
16238                assert_eq!(subject, "orders.events.*.charged");
16239            }
16240            other => panic!("expected PubSub, got {other:?}"),
16241        }
16242    }
16243
16244    // ── :contratos :slot value-shape gate ────────────────────────────────
16245    //
16246    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
16247    // (63e18a0) value-shape suites on the peer payload axes. Until this
16248    // gate landed `WitContract::target()` only refused the empty string
16249    // for the Store arm; a structurally invalid slot (raw whitespace,
16250    // control character, non-ASCII byte, paste-from-binary multi-line
16251    // blob) silently passed validate and surfaced at runtime as a
16252    // per-backend kv write rejection or a silent next-read corruption,
16253    // far from the source caixa.lisp with no field naming which
16254    // `:contratos` edge carried the typo. Every authoring footgun the
16255    // kv backend intersection-floor would catch on write now becomes a
16256    // caixa-build-time `ContratoSlotInvalid` with the offending
16257    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
16258    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
16259    // peer payload axes; same shared predicate
16260    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
16261    // any two axes' rule enforcement is a build error at the
16262    // predicate, not piecemeal across renderers. Closes the typed
16263    // payload-axis value-shape trajectory across all three legs of the
16264    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
16265
16266    fn contrato_slot_err(slot: &str) -> AplicacaoError {
16267        // Fresh spec per call so the new contract doesn't collide on
16268        // identity with `three_member_spec`'s pre-existing entries
16269        // and doesn't close a synchronous cycle the cycle detector
16270        // would reject before the slot-shape gate fires. The new edge
16271        // uses `(payment, catalog)` — a pair the fixture doesn't
16272        // already declare in either direction (the fixture carries
16273        // `cart -> catalog` and `cart -> payment`, so `payment ->
16274        // catalog` doesn't form a cycle on the sync subgraph) — with
16275        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
16276        // slot-shape gate fires cleanly after the wit-shape gate
16277        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
16278        // peer `contrato_subject_err` helper uses (63e18a0).
16279        let mut s = three_member_spec();
16280        s.contratos.push(WitContract {
16281            de: "payment".into(),
16282            para: "catalog".into(),
16283            wit: "wasi:keyvalue/store".into(),
16284            endpoint: None,
16285            subject: None,
16286            slot: Some(slot.into()),
16287        });
16288        s.validate().unwrap_err()
16289    }
16290
16291    #[test]
16292    fn rejects_store_contrato_slot_with_whitespace() {
16293        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
16294        // silently landed at the kv backend with whitespace whose
16295        // runtime behavior varies unpredictably across backends (etcd
16296        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
16297        // rejects on write). Now caught at the source caixa.lisp.
16298        let err = contrato_slot_err("check out/$order");
16299        assert!(
16300            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16301                if slot == "check out/$order" && reason.contains("whitespace")),
16302            "got {err:?}"
16303        );
16304    }
16305
16306    #[test]
16307    fn rejects_store_contrato_slot_with_tab() {
16308        // Tab byte arm-pinned separately from the space arm so a
16309        // future relaxation that admits one but not the other surfaces
16310        // here.
16311        let err = contrato_slot_err("check\tout");
16312        assert!(
16313            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16314                if slot == "check\tout" && reason.contains("whitespace")),
16315            "got {err:?}"
16316        );
16317    }
16318
16319    #[test]
16320    fn rejects_store_contrato_slot_with_control_char() {
16321        // SOH (0x01) — distinct from the whitespace arm. Redis admits
16322        // and corrupts on RESP protocol framing; DynamoDB rejects on
16323        // write.
16324        let err = contrato_slot_err("checkout/\x01order");
16325        assert!(
16326            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16327                if slot == "checkout/\x01order" && reason.contains("control character")),
16328            "got {err:?}"
16329        );
16330    }
16331
16332    #[test]
16333    fn rejects_store_contrato_slot_with_newline() {
16334        // Embedded newline — the canonical "the paste-from-binary slug
16335        // spans multiple lines" footgun. Distinct from the whitespace
16336        // arm because `\n` is a control character (0x0A).
16337        let err = contrato_slot_err("checkout\norder");
16338        assert!(
16339            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16340                if slot == "checkout\norder" && reason.contains("control character")),
16341            "got {err:?}"
16342        );
16343    }
16344
16345    #[test]
16346    fn rejects_store_contrato_slot_with_non_ascii() {
16347        // Un-percent-encoded non-ASCII byte — the canonical "I copied
16348        // the slot from a doc with accented characters" footgun. Each
16349        // kv backend re-encodes non-ASCII differently (etcd preserves
16350        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
16351        // rejects), so the typed slot's value set is the intersection-
16352        // floor every backend admits identically (printable ASCII).
16353        let err = contrato_slot_err("ch\u{e9}ckout/$order");
16354        assert!(
16355            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16356                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
16357            "got {err:?}"
16358        );
16359    }
16360
16361    #[test]
16362    fn rejects_store_contrato_slot_too_long() {
16363        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
16364        // legitimate-shape arms all pass (a single all-`a` token, no
16365        // separators); only the cap arm fires. Surfaces the paste-
16366        // from-binary / accidental-multi-line-blob landing footgun.
16367        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
16368        // `rejects_http_contrato_endpoint_too_long` on the peer
16369        // payload axes.
16370        let big = "a".repeat(513);
16371        assert_eq!(big.len(), 513);
16372        let err = contrato_slot_err(&big);
16373        assert!(
16374            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
16375                if slot == &big && reason.contains("max length of 512")),
16376            "got {err:?}"
16377        );
16378    }
16379
16380    #[test]
16381    fn store_contrato_slot_max_length_validates() {
16382        // 512-byte slot — exactly the cap. Boundary pin: drift in the
16383        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
16384        // simultaneously, mirroring
16385        // `pubsub_contrato_subject_max_length_validates` and
16386        // `http_contrato_endpoint_max_length_validates` on the peer
16387        // payload axes.
16388        let big = "a".repeat(512);
16389        assert_eq!(big.len(), 512);
16390        let mut s = three_member_spec();
16391        s.contratos.push(WitContract {
16392            de: "payment".into(),
16393            para: "catalog".into(),
16394            wit: "wasi:keyvalue/store".into(),
16395            endpoint: None,
16396            subject: None,
16397            slot: Some(big),
16398        });
16399        s.validate().unwrap();
16400    }
16401
16402    #[test]
16403    fn store_contrato_slot_accepts_canonical_forms() {
16404        // Positive-set sweep: every canonical kv slot template the
16405        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
16406        // (single-token identifiers, path-namespaced `$`-templates,
16407        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
16408        // snake_case / kebab-case / MixedCase tokens, digit-bearing
16409        // tokens, percent-encoded fragments) must remain valid
16410        // contrato slots too. Drift between this list and the
16411        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
16412        // surfaces at the shared predicate — one source of truth.
16413        // Uses a fresh `(payment, catalog)` edge so none of the swept
16414        // slots collide with the pre-existing entries in
16415        // `three_member_spec`.
16416        for slot in [
16417            "checkout",
16418            "checkout/$orderId",
16419            "users:{tenant}/{id}",
16420            "session.<sid>",
16421            "session.tokens.<sid>",
16422            "snake_case_key",
16423            "kebab-case-key",
16424            "MixedCase",
16425            "shard0",
16426            "v2/key",
16427            "users/caf%C3%A9",
16428        ] {
16429            let mut s = three_member_spec();
16430            s.contratos.push(WitContract {
16431                de: "payment".into(),
16432                para: "catalog".into(),
16433                wit: "wasi:keyvalue/store".into(),
16434                endpoint: None,
16435                subject: None,
16436                slot: Some(slot.into()),
16437            });
16438            s.validate()
16439                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
16440        }
16441    }
16442
16443    #[test]
16444    fn contrato_slot_empty_takes_precedence_over_invalid() {
16445        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
16446        // diagnostic on `""` and must lead — the value-shape gate is
16447        // only reached after the empty-check fires. Mirrors
16448        // `contrato_subject_empty_takes_precedence_over_invalid` and
16449        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
16450        // the peer payload axes.
16451        let mut s = three_member_spec();
16452        s.contratos.push(WitContract {
16453            de: "payment".into(),
16454            para: "catalog".into(),
16455            wit: "wasi:keyvalue/store".into(),
16456            endpoint: None,
16457            subject: None,
16458            slot: Some(String::new()),
16459        });
16460        let err = s.validate().unwrap_err();
16461        assert!(
16462            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
16463            "got {err:?}"
16464        );
16465    }
16466
16467    #[test]
16468    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
16469        // Diagnostic-shape pin — the offending `:slot` + `:de` +
16470        // `:para` + a non-empty reason flow through verbatim so the
16471        // author can grep their caixa.lisp for the offending contrato
16472        // block and fix it in one edit. Same shape as
16473        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
16474        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
16475        // on the peer payload axes.
16476        let err = contrato_slot_err("check out/$order");
16477        match err {
16478            AplicacaoError::ContratoSlotInvalid {
16479                de,
16480                para,
16481                slot,
16482                reason,
16483            } => {
16484                assert_eq!(de, "payment");
16485                assert_eq!(para, "catalog");
16486                assert_eq!(slot, "check out/$order");
16487                assert!(!reason.is_empty(), "reason field must be non-empty");
16488            }
16489            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
16490        }
16491    }
16492
16493    #[test]
16494    fn target_view_store_slot_passes_through_to_typed_view() {
16495        // The compounding theorem on the store axis: every
16496        // `WitTarget::Store { slot }` returned by `target()` carries a
16497        // kv-backend-accepted slot template. Renderers downstream of
16498        // `typed_view()` (the future per-Servico `:capabilities
16499        // wasi:keyvalue/store` axis emitter, the future `feira app
16500        // graph` view's slot labeller, the future kv-provider CR
16501        // materializer) can rely on this without re-checking — the
16502        // type system carries the proof. Mirrors
16503        // `target_view_pubsub_subject_passes_through_to_typed_view` on
16504        // the peer payload axis.
16505        let store = WitContract {
16506            de: "a".into(),
16507            para: "b".into(),
16508            wit: "wasi:keyvalue/store".into(),
16509            endpoint: None,
16510            subject: None,
16511            slot: Some("checkout/$orderId".into()),
16512        };
16513        match store.target().unwrap() {
16514            WitTarget::Store { slot } => {
16515                assert_eq!(slot, "checkout/$orderId");
16516            }
16517            other => panic!("expected Store, got {other:?}"),
16518        }
16519    }
16520
16521    #[test]
16522    fn rejects_self_loop_in_synchronous_contratos() {
16523        // A synchronous self-edge (`cart → cart` over HTTP) is now
16524        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
16525        // "this edge is degenerate" diagnostic — rather than incidentally
16526        // by the cycle detector framing it as a `["cart", "cart"]`
16527        // multi-node deadlock.
16528        let mut s = three_member_spec();
16529        s.contratos.push(contract_http("cart", "cart", "/loop"));
16530        let err = s.validate().unwrap_err();
16531        match err {
16532            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
16533                assert_eq!(caixa, "cart");
16534                assert_eq!(wit, "wasi:http/proxy");
16535            }
16536            other => panic!("expected ContratoSelfLoop, got {other:?}"),
16537        }
16538    }
16539
16540    #[test]
16541    fn rejects_self_loop_in_pubsub_contratos() {
16542        // The cycle detector excludes pub-sub edges (acyclic by
16543        // construction), so before the explicit gate a `nats:pub-sub`
16544        // self-edge silently validated and rendered a self-allow CNP.
16545        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
16546        let mut s = three_member_spec();
16547        s.contratos.push(WitContract {
16548            de: "payment".into(),
16549            para: "payment".into(),
16550            wit: "nats:pub-sub".into(),
16551            endpoint: None,
16552            subject: Some("rio.events.payment".into()),
16553            slot: None,
16554        });
16555        let err = s.validate().unwrap_err();
16556        match err {
16557            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
16558                assert_eq!(caixa, "payment");
16559                assert_eq!(wit, "nats:pub-sub");
16560            }
16561            other => panic!("expected ContratoSelfLoop, got {other:?}"),
16562        }
16563    }
16564
16565    #[test]
16566    fn self_loop_fires_before_payload_shape_check() {
16567        // The structural "this edge can't exist" error precedes the
16568        // narrower payload-shape diagnostics: a self-edge carrying an
16569        // otherwise-malformed endpoint still reports ContratoSelfLoop,
16570        // not ContratoEndpointInvalid.
16571        let mut s = three_member_spec();
16572        s.contratos.push(WitContract {
16573            de: "cart".into(),
16574            para: "cart".into(),
16575            wit: "wasi:http/proxy".into(),
16576            endpoint: Some("not-absolute".into()),
16577            subject: None,
16578            slot: None,
16579        });
16580        match s.validate().unwrap_err() {
16581            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
16582            other => panic!("expected ContratoSelfLoop, got {other:?}"),
16583        }
16584    }
16585
16586    #[test]
16587    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
16588        // A self-edge naming a non-member reports the more fundamental
16589        // ContratoMemberMissing first (the member doesn't exist), so the
16590        // self-loop gate is reached only once both endpoints resolve.
16591        let mut s = three_member_spec();
16592        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
16593        match s.validate().unwrap_err() {
16594            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
16595            other => panic!("expected ContratoMemberMissing, got {other:?}"),
16596        }
16597    }
16598
16599    #[test]
16600    fn rejects_two_node_synchronous_cycle() {
16601        let mut s = three_member_spec();
16602        // existing edges: cart → catalog, cart → payment
16603        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
16604        s.contratos
16605            .push(contract_http("catalog", "cart", "/refresh"));
16606        let err = s.validate().unwrap_err();
16607        match err {
16608            AplicacaoError::ContratoCycle { cycle } => {
16609                // Cycle traversal should mention both endpoints, with
16610                // the back-edge target appearing as both first and last
16611                // element to close the loop.
16612                assert!(cycle.len() >= 3);
16613                assert_eq!(cycle.first(), cycle.last());
16614                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
16615                assert!(body.contains("cart"));
16616                assert!(body.contains("catalog"));
16617            }
16618            other => panic!("expected ContratoCycle, got {other:?}"),
16619        }
16620    }
16621
16622    #[test]
16623    fn rejects_three_node_synchronous_cycle() {
16624        let mut s = three_member_spec();
16625        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
16626        s.contratos = vec![
16627            contract_http("catalog", "cart", "/x"),
16628            contract_http("cart", "payment", "/y"),
16629            contract_http("payment", "catalog", "/z"),
16630        ];
16631        let err = s.validate().unwrap_err();
16632        match err {
16633            AplicacaoError::ContratoCycle { cycle } => {
16634                assert_eq!(cycle.first(), cycle.last());
16635                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
16636                assert_eq!(body.len(), 3);
16637                assert!(body.contains("cart"));
16638                assert!(body.contains("catalog"));
16639                assert!(body.contains("payment"));
16640            }
16641            other => panic!("expected ContratoCycle, got {other:?}"),
16642        }
16643    }
16644
16645    #[test]
16646    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
16647        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
16648        // "acyclic by construction" — so a cycle whose closing edge
16649        // is pub-sub should NOT raise ContratoCycle.
16650        let mut s = three_member_spec();
16651        s.contratos = vec![
16652            contract_http("catalog", "cart", "/x"),
16653            contract_http("cart", "payment", "/y"),
16654            // Closing edge is pub-sub — async; not a sync deadlock.
16655            WitContract {
16656                de: "payment".into(),
16657                para: "catalog".into(),
16658                wit: "nats:pub-sub".into(),
16659                endpoint: None,
16660                subject: Some("checkout.events.charge.completed".into()),
16661                slot: None,
16662            },
16663        ];
16664        s.validate().expect("pub-sub edge breaks the sync cycle");
16665    }
16666
16667    #[test]
16668    fn store_edge_counts_as_synchronous_for_cycle_detection() {
16669        // wasi:keyvalue/store is request/response; a cycle through one
16670        // *is* a sync deadlock, just like HTTP.
16671        let mut s = three_member_spec();
16672        s.contratos = vec![
16673            contract_http("catalog", "cart", "/x"),
16674            WitContract {
16675                de: "cart".into(),
16676                para: "catalog".into(),
16677                wit: "wasi:keyvalue/store".into(),
16678                endpoint: None,
16679                subject: None,
16680                slot: Some("session/$id".into()),
16681            },
16682        ];
16683        let err = s.validate().unwrap_err();
16684        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
16685    }
16686
16687    #[test]
16688    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
16689        // Capability-only edges (unknown WIT shape, no payload) default
16690        // to synchronous — safer; authors with truly async capability
16691        // semantics can model them as pub-sub explicitly.
16692        let mut s = three_member_spec();
16693        s.contratos = vec![
16694            contract_http("catalog", "cart", "/x"),
16695            WitContract {
16696                de: "cart".into(),
16697                para: "catalog".into(),
16698                wit: "custom:exchange".into(),
16699                endpoint: None,
16700                subject: None,
16701                slot: None,
16702            },
16703        ];
16704        let err = s.validate().unwrap_err();
16705        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
16706    }
16707
16708    #[test]
16709    fn long_acyclic_chain_validates() {
16710        // A long sync chain (no back-edges) must validate even when
16711        // every node is reachable from the first.
16712        let mut s = three_member_spec();
16713        s.membros = vec![
16714            membro("a", "^0.1"),
16715            membro("b", "^0.1"),
16716            membro("c", "^0.1"),
16717            membro("d", "^0.1"),
16718            membro("e", "^0.1"),
16719        ];
16720        s.contratos = vec![
16721            contract_http("a", "b", "/1"),
16722            contract_http("b", "c", "/2"),
16723            contract_http("c", "d", "/3"),
16724            contract_http("d", "e", "/4"),
16725        ];
16726        s.entrada.as_mut().unwrap().para = "a".into();
16727        s.validate().unwrap();
16728    }
16729
16730    #[test]
16731    fn diamond_acyclic_validates() {
16732        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
16733        let mut s = three_member_spec();
16734        s.membros = vec![
16735            membro("a", "^0.1"),
16736            membro("b", "^0.1"),
16737            membro("c", "^0.1"),
16738            membro("d", "^0.1"),
16739        ];
16740        s.contratos = vec![
16741            contract_http("a", "b", "/1"),
16742            contract_http("a", "c", "/2"),
16743            contract_http("b", "d", "/3"),
16744            contract_http("c", "d", "/4"),
16745        ];
16746        s.entrada.as_mut().unwrap().para = "a".into();
16747        s.validate().unwrap();
16748    }
16749
16750    // ── duplicate-`:contratos` build-error gate ──────────────────────────
16751
16752    #[test]
16753    fn rejects_duplicate_http_contrato() {
16754        // Fail-before-pass-after pin: the fixture's `cart → catalog`
16755        // HTTP edge appears once. Push an identical entry — same
16756        // (de, para, wit, endpoint) — and validate() must reject it.
16757        // Until this gate landed the typed surface accepted the
16758        // duplicate silently and caixa-mesh's `cilium_network_policies`
16759        // emitted two ``CiliumNetworkPolicy`` objects with identical
16760        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
16761        // admission rejects on `kubectl apply` far from the source.
16762        let mut s = three_member_spec();
16763        s.contratos
16764            .push(contract_http("cart", "catalog", "/products/:id"));
16765        let err = s.validate().unwrap_err();
16766        assert!(
16767            matches!(
16768                err,
16769                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
16770                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
16771            ),
16772            "got {err:?}"
16773        );
16774    }
16775
16776    #[test]
16777    fn rejects_duplicate_pubsub_contrato() {
16778        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
16779        // edges with identical (de, para, subject) are degenerate;
16780        // pin that the typed surface refuses both at validate time.
16781        let mut s = three_member_spec();
16782        let pubsub = WitContract {
16783            de: "payment".into(),
16784            para: "cart".into(),
16785            wit: "nats:pub-sub".into(),
16786            endpoint: None,
16787            subject: Some("checkout.events.charge.failed".into()),
16788            slot: None,
16789        };
16790        s.contratos.push(pubsub.clone());
16791        s.contratos.push(pubsub);
16792        let err = s.validate().unwrap_err();
16793        assert!(
16794            matches!(
16795                err,
16796                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
16797                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
16798            ),
16799            "got {err:?}"
16800        );
16801    }
16802
16803    #[test]
16804    fn rejects_duplicate_store_contrato() {
16805        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
16806        // edges with identical (de, para, slot) collapse to one mesh-
16807        // policy edge; pin the build error.
16808        let mut s = three_member_spec();
16809        let store = WitContract {
16810            de: "cart".into(),
16811            para: "payment".into(),
16812            wit: "wasi:keyvalue/store".into(),
16813            endpoint: None,
16814            subject: None,
16815            slot: Some("checkout/$orderId".into()),
16816        };
16817        // Drop the conflicting HTTP `cart → payment` edge from the
16818        // fixture so the duplicate-store pair is the only one
16819        // distinguishable on this pair.
16820        s.contratos
16821            .retain(|c| !(c.de == "cart" && c.para == "payment"));
16822        s.contratos.push(store.clone());
16823        s.contratos.push(store);
16824        let err = s.validate().unwrap_err();
16825        assert!(
16826            matches!(
16827                err,
16828                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
16829                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
16830            ),
16831            "got {err:?}"
16832        );
16833    }
16834
16835    #[test]
16836    fn rejects_duplicate_capability_contrato() {
16837        // Same gate on the pure-capability axis (no payload selector).
16838        // Two contracts with identical (de, para, wit) and no
16839        // endpoint/subject/slot are duplicate edges; pin so a future
16840        // `target_label` change can't accidentally collapse the
16841        // capability arm into a None-shaped key that compares equal
16842        // to a populated one.
16843        let mut s = three_member_spec();
16844        let capability = WitContract {
16845            de: "cart".into(),
16846            para: "catalog".into(),
16847            wit: "pleme:cap/audit".into(),
16848            endpoint: None,
16849            subject: None,
16850            slot: None,
16851        };
16852        s.contratos.push(capability.clone());
16853        s.contratos.push(capability);
16854        let err = s.validate().unwrap_err();
16855        match err {
16856            AplicacaoError::ContratoDuplicate {
16857                de,
16858                para,
16859                wit,
16860                target,
16861            } => {
16862                assert_eq!(de, "cart");
16863                assert_eq!(para, "catalog");
16864                assert_eq!(wit, "pleme:cap/audit");
16865                assert!(
16866                    target.contains("capability"),
16867                    "capability-edge duplicate diagnostic must surface the \
16868                     no-payload shape (got target = {target:?})"
16869                );
16870            }
16871            other => panic!("expected ContratoDuplicate, got {other:?}"),
16872        }
16873    }
16874
16875    #[test]
16876    fn accepts_distinct_http_paths_between_same_pair() {
16877        // Negative pin: two HTTP contracts cart → catalog at distinct
16878        // endpoints (`/products/:id` and `/search`) are *not*
16879        // duplicates — they're distinct typed edges differing on the
16880        // payload axis. The duplicate-gate must not over-match here,
16881        // since the cart-calls-catalog-on-multiple-paths shape is the
16882        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
16883        // example: cart calls catalog at /products/:id, payment at
16884        // /charge — same shape extends to two paths on one para).
16885        let mut s = three_member_spec();
16886        s.contratos
16887            .push(contract_http("cart", "catalog", "/search"));
16888        s.validate()
16889            .expect("distinct endpoints between same (de, para) must validate");
16890    }
16891
16892    #[test]
16893    fn accepts_same_endpoint_on_different_pairs() {
16894        // Negative pin: the same `/charge` endpoint reused on two
16895        // different (de, para) pairs is two distinct edges, not a
16896        // duplicate. Pinning this shape so the gate's identity key
16897        // includes both `de` and `para` (not just `(wit, endpoint)`).
16898        let mut s = three_member_spec();
16899        s.contratos
16900            .push(contract_http("payment", "catalog", "/charge"));
16901        s.validate()
16902            .expect("same endpoint reused on distinct (de, para) must validate");
16903    }
16904
16905    #[test]
16906    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
16907        // Pin the diagnostic shape: the duplicate-edge error names
16908        // *which* target field carried the conflict, so the author
16909        // doesn't have to re-grep the source caixa.lisp to find it.
16910        // Same self-locating diagnostic discipline as
16911        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
16912        let mut s = three_member_spec();
16913        s.contratos
16914            .push(contract_http("cart", "catalog", "/products/:id"));
16915        let err = s.validate().unwrap_err();
16916        let msg = format!("{err}");
16917        assert!(
16918            msg.contains("\"/products/:id\""),
16919            "duplicate-contrato diagnostic must name the offending \
16920             :endpoint payload (got: {msg:?})"
16921        );
16922        assert!(
16923            msg.contains("cart") && msg.contains("catalog"),
16924            "diagnostic must name both endpoints of the duplicate edge \
16925             (got: {msg:?})"
16926        );
16927    }
16928
16929    #[test]
16930    fn duplicate_contrato_gate_runs_after_membership_check() {
16931        // Order pin: a duplicate contract whose `:de` is *also* not in
16932        // `:membros` surfaces the membership error first — the
16933        // missing-member diagnostic is more locating than the
16934        // duplicate-edge one (the author has to fix the membership
16935        // before the duplicate is meaningful). Same ordering
16936        // discipline as `membros_validation_runs_before_contratos_membership_check`.
16937        let mut s = three_member_spec();
16938        s.contratos.push(contract_http("phantom", "catalog", "/x"));
16939        s.contratos.push(contract_http("phantom", "catalog", "/x"));
16940        let err = s.validate().unwrap_err();
16941        assert!(
16942            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
16943            "membership-missing must fire before duplicate-edge (got {err:?})"
16944        );
16945    }
16946
16947    #[test]
16948    fn duplicate_contrato_gate_runs_after_target_shape_check() {
16949        // Order pin: a contract with a malformed target (e.g. an HTTP
16950        // wit world with an empty :endpoint) surfaces the target-shape
16951        // error first, not the duplicate one. Even when two such
16952        // malformed entries are identical, the per-contract `target()`
16953        // check fires inside the loop *before* the duplicate-key
16954        // insert, so the diagnostic remains the most-locating one.
16955        let mut s = three_member_spec();
16956        let malformed = WitContract {
16957            de: "cart".into(),
16958            para: "catalog".into(),
16959            wit: "wasi:http/proxy".into(),
16960            endpoint: Some(String::new()),
16961            subject: None,
16962            slot: None,
16963        };
16964        s.contratos.push(malformed.clone());
16965        s.contratos.push(malformed);
16966        let err = s.validate().unwrap_err();
16967        assert!(
16968            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
16969            "endpoint-empty must fire before duplicate-edge (got {err:?})"
16970        );
16971    }
16972
16973    #[test]
16974    fn wit_target_label_pins_per_variant_format() {
16975        // Label format is the single source of truth every duplicate-
16976        // `:contratos` diagnostic + every future `feira app graph`
16977        // consumer routes through. Pin the shape per variant so a
16978        // future edit to `WitTarget::label` (e.g. a JSON emitter that
16979        // strips the leading `:`, or a rename from `endpoint` →
16980        // `path`) surfaces as a red-red test rather than as a silent
16981        // downstream diagnostic drift. Together with the exhaustive
16982        // `match` on `WitTarget` inside `label()`, adding a future
16983        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
16984        // peer, per-edge WIT registry variants) is a compile error at
16985        // the label site — not a fall-through into the `Capability`
16986        // "no payload" default the prior raw-field-probe helper
16987        // silently landed on.
16988        assert_eq!(
16989            WitTarget::Http {
16990                endpoint: "/charge",
16991            }
16992            .label(),
16993            "\
16994:endpoint \"/charge\""
16995        );
16996        assert_eq!(
16997            WitTarget::PubSub {
16998                subject: "events.checkout.paid",
16999            }
17000            .label(),
17001            "\
17002:subject \"events.checkout.paid\""
17003        );
17004        assert_eq!(
17005            WitTarget::Store {
17006                slot: "checkout/$order",
17007            }
17008            .label(),
17009            "\
17010:slot \"checkout/$order\""
17011        );
17012        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
17013        // Capability-arm label routes through the lifted
17014        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
17015        // declaration per arm, next to the variant" discipline the
17016        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
17017        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17018        // consts already carry extends to the payload-less arm; the
17019        // byte-string equality pin below plus this label-routes-
17020        // through-the-const pin make a future rebrand on either the
17021        // const declaration or the `label()` template a build error
17022        // here rather than a downstream consumer surprise.
17023        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
17024        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
17025    }
17026
17027    #[test]
17028    fn wit_target_display_routes_through_label_helper() {
17029        // Fail-before-pass-after pin on the fourth (and only remaining)
17030        // typed-shape-discriminator axis to converge onto the
17031        // three-path-convergence discipline the sibling M3
17032        // [`PlacementStrategy`] (0a2f653) and M2
17033        // [`crate::supervisor::RestartStrategy`] /
17034        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
17035        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
17036        // through [`WitTarget::label`], so every consumer reaching for
17037        // `format!("{v}")` on a typed payload target lands on the same
17038        // stable author-facing byte-string [`WitTarget::label`] returns
17039        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
17040        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
17041        // `:contratos` gate seeds via [`WitTarget::label`] at
17042        // aplicacao.rs:5491 already threads through.
17043        //
17044        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
17045        // through to the `Debug` derive's structural output
17046        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
17047        // rather than the [`WitTarget::label`] helper's stable byte-
17048        // string (`:endpoint "/charge"` — the author-facing `:contratos`
17049        // keyword form). Every future consumer that reaches for
17050        // `format!("{target}")` — the canonical shape every user-facing
17051        // pretty-print site on the sibling typed-enum axes
17052        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
17053        // [`crate::supervisor::RestartPolicy`]) already uses — would
17054        // silently land under a different byte-string than the
17055        // [`WitTarget::label`] callers that the duplicate-`:contratos`
17056        // diagnostic already threads through, with the mismatch
17057        // surfacing as a downstream diagnostic / graph / audit line
17058        // reading one spelling while the substrate's own gate emitted
17059        // another.
17060        //
17061        // Pin the routing here so a future
17062        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
17063        // that hand-rolls the per-arm formatting instead of delegating
17064        // to [`WitTarget::label`] fails at caixa-core build time.
17065        for variant in [
17066            WitTarget::Http {
17067                endpoint: "/charge",
17068            },
17069            WitTarget::PubSub {
17070                subject: "events.checkout.paid",
17071            },
17072            WitTarget::Store {
17073                slot: "checkout/$order",
17074            },
17075            WitTarget::Capability,
17076        ] {
17077            assert_eq!(
17078                variant.to_string(),
17079                variant.label(),
17080                "WitTarget::{variant:?} Display must route through \
17081                 WitTarget::label (single source of truth: the lifted \
17082                 payload_pair 4-arm dispatch the label helper already \
17083                 threads through)"
17084            );
17085        }
17086    }
17087
17088    #[test]
17089    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
17090        // Consumer-side pin on the three-path convergence:
17091        // [`std::fmt::Display`] agrees byte-for-byte with the
17092        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
17093        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
17094        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
17095        // Pre-lift the two paths were structurally independent — the
17096        // substrate-side gate reached for `target_view.label()` while a
17097        // future downstream diagnostic / graph / audit line reaching
17098        // for `format!("{target}")` would silently land on the `Debug`
17099        // derive's structural output. Pin the two paths byte-for-byte
17100        // here so any future variant addition (M4 `Rest`/`Grpc` split
17101        // of [`WitTarget::Http`], `Queue`-shaped peer of
17102        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
17103        // match error at [`WitTarget::payload_pair`] rather than a
17104        // silent per-consumer dispatch miss.
17105        for variant in [
17106            WitTarget::Http {
17107                endpoint: "/charge",
17108            },
17109            WitTarget::PubSub {
17110                subject: "events.checkout.paid",
17111            },
17112            WitTarget::Store {
17113                slot: "checkout/$order",
17114            },
17115            WitTarget::Capability,
17116        ] {
17117            assert_eq!(
17118                format!("{variant}"),
17119                variant.label(),
17120                "WitTarget::{variant:?} Display byte-string must match \
17121                 the AplicacaoError::ContratoDuplicate `target:` carrier \
17122                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
17123                 seeds via WitTarget::label — three-path convergence: \
17124                 Display + label + payload_pair all resolve to the same \
17125                 per-arm byte-string"
17126            );
17127        }
17128    }
17129
17130    #[test]
17131    fn wit_target_payload_pair_pins_per_variant() {
17132        // Pin the per-arm `(field-name, payload)` pair single-sourced
17133        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
17134        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
17135        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
17136        // and [`WitTarget::field_name`] (returns the first component)
17137        // route through. Until this lift landed [`WitTarget::label`]
17138        // dispatched on the same three arms with a per-arm
17139        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
17140        // paired [`WitTarget::HTTP_FIELD_NAME`] /
17141        // [`WitTarget::PUBSUB_FIELD_NAME`] /
17142        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
17143        // canonical "same shape, written N times" duplication
17144        // THEORY.md §I.3.5 promotes to a build-time concern. A future
17145        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
17146        // [`WitTarget::Http`], `Queue`-shaped peer of
17147        // [`WitTarget::Store`]) is one match-arm edit at
17148        // [`WitTarget::payload_pair`], visible here as a compile-time
17149        // exhaustiveness error on both this pin and the label-format
17150        // pin above.
17151        assert_eq!(
17152            WitTarget::Http {
17153                endpoint: "/charge"
17154            }
17155            .payload_pair(),
17156            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
17157        );
17158        assert_eq!(
17159            WitTarget::PubSub {
17160                subject: "events.x",
17161            }
17162            .payload_pair(),
17163            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
17164        );
17165        assert_eq!(
17166            WitTarget::Store {
17167                slot: "checkout/$order",
17168            }
17169            .payload_pair(),
17170            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
17171        );
17172        assert_eq!(WitTarget::Capability.payload_pair(), None);
17173    }
17174
17175    #[test]
17176    fn wit_target_field_name_pins_per_variant() {
17177        // Pin the per-arm author-facing `:contratos` payload field
17178        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
17179        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17180        // + returned by [`WitTarget::field_name`]. Every downstream
17181        // consumer (the [`WitContract::target`] gate's `expected:`
17182        // scalar, the [`WitTarget::label`] template's keyword prefix,
17183        // the `feira app graph` verb's `endpoint=…` prefix) routes
17184        // through the same three peer consts, so a rename on the
17185        // author-surface `(defcaixa … :contratos ((:de … :para …
17186        // :wit … :endpoint …)))` field lands in exactly one place.
17187        assert_eq!(
17188            WitTarget::Http {
17189                endpoint: "/charge"
17190            }
17191            .field_name(),
17192            Some(WitTarget::HTTP_FIELD_NAME),
17193        );
17194        assert_eq!(
17195            WitTarget::PubSub {
17196                subject: "events.x",
17197            }
17198            .field_name(),
17199            Some(WitTarget::PUBSUB_FIELD_NAME),
17200        );
17201        assert_eq!(
17202            WitTarget::Store {
17203                slot: "checkout/$order",
17204            }
17205            .field_name(),
17206            Some(WitTarget::STORE_FIELD_NAME),
17207        );
17208        // Capability arm carries no payload field — the diagnostic
17209        // never reports `expected: "capability"` because the gate's
17210        // Capability arm accepts no payload at all (it fires the
17211        // "expected: none" WrongTarget error instead), so the field-
17212        // name method returns None here rather than a placeholder.
17213        assert_eq!(WitTarget::Capability.field_name(), None);
17214
17215        // Peer const scalar values pinned so a rename on either side
17216        // (author-surface field name in the `(defcaixa …)` DSL, or
17217        // the diagnostic's `expected:` scalar) can't drift without
17218        // failing here first.
17219        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
17220        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
17221        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
17222    }
17223
17224    #[test]
17225    fn wit_target_payload_pins_per_variant() {
17226        // Pin the per-arm payload scalar single-sourced onto the
17227        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
17228        // [`WitTarget::payload`] — the peer per-half projection to
17229        // [`WitTarget::field_name`] on the paired sub-selector axis. The
17230        // three payload-carrying arms round-trip their author-declared
17231        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
17232        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
17233        // the payload-less [`WitTarget::Capability`] arm returns `None`.
17234        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
17235        // (c6ec2af) pin on the Component-0 projection axis, extended
17236        // onto the Component-1 projection axis so both per-half readers
17237        // on the paired dispatch carry their own byte-shape pin.
17238        assert_eq!(
17239            WitTarget::Http {
17240                endpoint: "/charge",
17241            }
17242            .payload(),
17243            Some("/charge"),
17244        );
17245        assert_eq!(
17246            WitTarget::PubSub {
17247                subject: "events.x",
17248            }
17249            .payload(),
17250            Some("events.x"),
17251        );
17252        assert_eq!(
17253            WitTarget::Store {
17254                slot: "checkout/$order",
17255            }
17256            .payload(),
17257            Some("checkout/$order"),
17258        );
17259        assert_eq!(WitTarget::Capability.payload(), None);
17260    }
17261
17262    #[test]
17263    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
17264        // Per-variant equivalence pin: for every arm of [`WitTarget`],
17265        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
17266        // byte-for-byte. Guards the drift surface where a future refactor
17267        // that split one accessor off the shared match onto its own
17268        // dispatch — a well-meaning "inline the pair back into per-half
17269        // fields for one crate-internal caller who only wanted one half"
17270        // or a scratch `impl` shadowing the derived projection — would
17271        // silently desynchronize [`WitTarget::payload`] from the
17272        // authoritative [`WitTarget::payload_pair`] dispatch, and every
17273        // downstream consumer that thinks "the payload half of the pair"
17274        // would drift from the diagnostic / graph consumers reading the
17275        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
17276        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
17277        // per-half projection pin (`gitrefspec_ref_pair_projects_
17278        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
17279        // FluxCD source-controller `spec.ref.<field>` axis — same "one
17280        // paired dispatch, both per-half projections agree byte-for-
17281        // byte" discipline extended onto the M3 `:contratos` payload-
17282        // arm surface.
17283        for variant in [
17284            WitTarget::Http {
17285                endpoint: "/charge",
17286            },
17287            WitTarget::PubSub {
17288                subject: "events.checkout.paid",
17289            },
17290            WitTarget::Store {
17291                slot: "checkout/$order",
17292            },
17293            WitTarget::Capability,
17294        ] {
17295            let via_projection = variant.payload();
17296            let via_pair = variant.payload_pair().map(|(_, p)| p);
17297            assert_eq!(
17298                via_projection, via_pair,
17299                "WitTarget::{variant:?} payload() must equal \
17300                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
17301                 regression that splits the two per-half projections off \
17302                 their shared match would silently desynchronize the \
17303                 payload accessor from the paired dispatch every \
17304                 diagnostic / graph consumer reads through",
17305            );
17306        }
17307    }
17308
17309    #[test]
17310    fn wit_target_http_endpoint_pins_per_variant() {
17311        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
17312        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
17313        // substrate-primitive per-arm post-projection accessor every
17314        // L7-HTTP-facing consumer routes through, sibling to the peer
17315        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
17316        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
17317        // arm round-trips its author-declared endpoint verbatim as
17318        // `Some("/charge")`; the three sibling arms
17319        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
17320        // [`WitTarget::Capability`]) each return `None` because they
17321        // carry no HTTP endpoint by definition. Same fail-before-pass-
17322        // after per-variant discipline as the sibling
17323        // `wit_target_payload_pins_per_variant` (5d6dc92) /
17324        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
17325        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
17326        // the peer pan-arm / per-half projection axes — extended onto
17327        // the per-arm HTTP-shape post-projection axis so a future
17328        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
17329        // [`WitTarget::Http`], a `Queue`-shaped peer of
17330        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
17331        // error on the sibling [`WitTarget::http_endpoint`] match arms
17332        // whose payload the L7-HTTP-shape accept-set is meant to bound.
17333        assert_eq!(
17334            WitTarget::Http {
17335                endpoint: "/charge",
17336            }
17337            .http_endpoint(),
17338            Some("/charge"),
17339        );
17340        assert_eq!(
17341            WitTarget::PubSub {
17342                subject: "events.checkout.paid",
17343            }
17344            .http_endpoint(),
17345            None,
17346        );
17347        assert_eq!(
17348            WitTarget::Store {
17349                slot: "checkout/$order",
17350            }
17351            .http_endpoint(),
17352            None,
17353        );
17354        assert_eq!(WitTarget::Capability.http_endpoint(), None);
17355    }
17356
17357    #[test]
17358    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
17359        // Per-variant coherence pin: for every arm of [`WitTarget`],
17360        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
17361        // arm (both project the same author-declared request-path
17362        // scalar), and returns `None` on every sibling arm regardless of
17363        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
17364        // Store carry their own payload the pan-arm accessor surfaces,
17365        // but that payload is not an HTTP endpoint — the per-arm
17366        // accessor must not leak it through the HTTP-shape channel).
17367        // Guards the drift surface where a future refactor that
17368        // conflated the per-arm HTTP projection with the pan-arm
17369        // [`WitTarget::payload`] projection — a well-meaning "one
17370        // accessor for the L7 branch, one for the graph" collapse that
17371        // routes both through the same 4-arm dispatch — would silently
17372        // widen the L7-HTTP-shape accept-set onto pub-sub / store
17373        // payloads at the caixa-mesh L7 emit branch, admitting a
17374        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
17375        // rule with the operator-side apply-time symptom (Cilium's
17376        // eBPF data-plane rejects every ingress edge whose L7 filter
17377        // doesn't match the wire-format HTTP request line) far from
17378        // the source refactor. Sibling to the peer
17379        // `wit_target_payload_matches_payload_pair_second_component_
17380        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
17381        // extended onto the per-arm HTTP specialization axis so both
17382        // the pan-arm and the per-arm projections carry their own
17383        // byte-shape coherence witness against the substrate's typed
17384        // arm-family accept-set.
17385        for variant in [
17386            WitTarget::Http {
17387                endpoint: "/charge",
17388            },
17389            WitTarget::PubSub {
17390                subject: "events.checkout.paid",
17391            },
17392            WitTarget::Store {
17393                slot: "checkout/$order",
17394            },
17395            WitTarget::Capability,
17396        ] {
17397            let per_arm = variant.http_endpoint();
17398            let pan_arm = variant.payload();
17399            if variant.is_http() {
17400                assert_eq!(
17401                    per_arm, pan_arm,
17402                    "WitTarget::{variant:?} http_endpoint() must equal \
17403                     payload() on the Http arm — a per-arm-vs-pan-arm \
17404                     split would silently drift the L7 emit branch's \
17405                     path-scalar source from the graph verb's payload \
17406                     scalar source",
17407                );
17408            } else {
17409                assert_eq!(
17410                    per_arm, None,
17411                    "WitTarget::{variant:?} http_endpoint() must return \
17412                     None on non-Http arms — a leak that surfaced a \
17413                     pub-sub :subject or a key/value :slot through the \
17414                     HTTP-endpoint accessor would silently widen the \
17415                     Cilium L7 HTTP `path:` rule accept-set onto \
17416                     protocol shapes Cilium's eBPF data-plane can't \
17417                     introspect",
17418                );
17419            }
17420        }
17421    }
17422
17423    #[test]
17424    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
17425        // Per-variant coherence pin: for every arm of [`WitTarget`],
17426        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
17427        // drift surface where a future extension of the
17428        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
17429        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
17430        // accessor to cover both peers) landed without a paired
17431        // extension of the [`gen_platform::IsVariant`]-derived
17432        // `is_http()` predicate's accept-set, or vice versa — a
17433        // regression that split the "which arms count as HTTP-shaped
17434        // for L7-path emission?" answer between two dispatch surfaces
17435        // the substrate ships. Sibling to the peer
17436        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
17437        // on the paired dispatch axis — extended onto the per-arm
17438        // predicate-vs-accessor coherence axis so the gen-platform
17439        // IsVariant predicate and the substrate-lifted per-arm
17440        // accessor carry one shared answer to "is this the HTTP arm?".
17441        for variant in [
17442            WitTarget::Http {
17443                endpoint: "/charge",
17444            },
17445            WitTarget::PubSub {
17446                subject: "events.checkout.paid",
17447            },
17448            WitTarget::Store {
17449                slot: "checkout/$order",
17450            },
17451            WitTarget::Capability,
17452        ] {
17453            assert_eq!(
17454                variant.http_endpoint().is_some(),
17455                variant.is_http(),
17456                "WitTarget::{variant:?} http_endpoint().is_some() must \
17457                 equal is_http() — a drift would split the L7 emit \
17458                 branch's arm-set gate from the substrate-derived \
17459                 shape-discrimination predicate on the same axis",
17460            );
17461        }
17462    }
17463
17464    #[test]
17465    fn wit_target_pubsub_subject_pins_per_variant() {
17466        // Fail-before-pass-after pin: the substrate-canonical per-arm
17467        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
17468        // is the single dispatch every future pub-sub-facing consumer
17469        // routes through, sibling to the peer [`WitContract::subject`]
17470        // (63e18a0) pre-projection scalar accessor on the raw-field
17471        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
17472        // post-projection per-arm accessor on the sibling HTTP-shape
17473        // axis. The [`WitTarget::PubSub`] arm round-trips its
17474        // author-declared subject verbatim as
17475        // `Some("events.checkout.paid")`; the three sibling arms each
17476        // return `None` because they carry no NATS-shaped subject by
17477        // definition. Same fail-before-pass-after per-variant discipline
17478        // as the sibling `wit_target_http_endpoint_pins_per_variant`
17479        // pin on the peer per-arm axis — extended onto the per-arm
17480        // pub-sub-shape post-projection axis so a future [`WitTarget`]
17481        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
17482        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
17483        // compile-time exhaustiveness error on the sibling
17484        // [`WitTarget::pubsub_subject`] match arms whose payload the
17485        // pub-sub-shape accept-set is meant to bound.
17486        assert_eq!(
17487            WitTarget::PubSub {
17488                subject: "events.checkout.paid",
17489            }
17490            .pubsub_subject(),
17491            Some("events.checkout.paid"),
17492        );
17493        assert_eq!(
17494            WitTarget::Http {
17495                endpoint: "/charge",
17496            }
17497            .pubsub_subject(),
17498            None,
17499        );
17500        assert_eq!(
17501            WitTarget::Store {
17502                slot: "checkout/$order",
17503            }
17504            .pubsub_subject(),
17505            None,
17506        );
17507        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
17508    }
17509
17510    #[test]
17511    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
17512        // Per-variant coherence pin: for every arm of [`WitTarget`],
17513        // `.pubsub_subject()` equals `.payload()` on the
17514        // [`WitTarget::PubSub`] arm (both project the same
17515        // author-declared subject scalar), and returns `None` on every
17516        // sibling arm regardless of whether [`WitTarget::payload`]
17517        // itself returns `Some` (Http / Store carry their own payload
17518        // the pan-arm accessor surfaces, but that payload is not a
17519        // pub-sub subject — the per-arm accessor must not leak it
17520        // through the pub-sub-shape channel). Sibling to the peer
17521        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
17522        // coherence pin on the per-arm HTTP-shape axis — extended onto
17523        // the per-arm pub-sub specialization axis so both per-arm
17524        // projections carry their own byte-shape coherence witness
17525        // against the substrate's typed arm-family accept-set.
17526        for variant in [
17527            WitTarget::Http {
17528                endpoint: "/charge",
17529            },
17530            WitTarget::PubSub {
17531                subject: "events.checkout.paid",
17532            },
17533            WitTarget::Store {
17534                slot: "checkout/$order",
17535            },
17536            WitTarget::Capability,
17537        ] {
17538            let per_arm = variant.pubsub_subject();
17539            let pan_arm = variant.payload();
17540            if variant.is_pubsub() {
17541                assert_eq!(
17542                    per_arm, pan_arm,
17543                    "WitTarget::{variant:?} pubsub_subject() must equal \
17544                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
17545                     split would silently drift the pub-sub-shape emit \
17546                     branch's subject-scalar source from the graph verb's \
17547                     payload scalar source",
17548                );
17549            } else {
17550                assert_eq!(
17551                    per_arm, None,
17552                    "WitTarget::{variant:?} pubsub_subject() must return \
17553                     None on non-PubSub arms — a leak that surfaced an \
17554                     HTTP :endpoint or a key/value :slot through the \
17555                     pub-sub-subject accessor would silently widen the \
17556                     downstream NATS-shape accept-set onto protocol \
17557                     shapes NATS servers can't route",
17558                );
17559            }
17560        }
17561    }
17562
17563    #[test]
17564    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
17565        // Per-variant coherence pin: for every arm of [`WitTarget`],
17566        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
17567        // drift surface where a future extension of the
17568        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
17569        // without a paired extension of the [`gen_platform::IsVariant`]-
17570        // derived `is_pubsub()` predicate's accept-set, or vice versa
17571        // — a regression that split the "which arms count as pub-sub-
17572        // shaped for subject emission?" answer between two dispatch
17573        // surfaces the substrate ships. Sibling to the peer
17574        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
17575        // pin on the per-arm HTTP-shape axis — extended onto the
17576        // per-arm pub-sub predicate-vs-accessor coherence axis so the
17577        // gen-platform IsVariant predicate and the substrate-lifted
17578        // per-arm accessor carry one shared answer to "is this the
17579        // PubSub arm?".
17580        for variant in [
17581            WitTarget::Http {
17582                endpoint: "/charge",
17583            },
17584            WitTarget::PubSub {
17585                subject: "events.checkout.paid",
17586            },
17587            WitTarget::Store {
17588                slot: "checkout/$order",
17589            },
17590            WitTarget::Capability,
17591        ] {
17592            assert_eq!(
17593                variant.pubsub_subject().is_some(),
17594                variant.is_pubsub(),
17595                "WitTarget::{variant:?} pubsub_subject().is_some() must \
17596                 equal is_pubsub() — a drift would split the pub-sub \
17597                 emit branch's arm-set gate from the substrate-derived \
17598                 shape-discrimination predicate on the same axis",
17599            );
17600        }
17601    }
17602
17603    #[test]
17604    fn wit_target_store_slot_pins_per_variant() {
17605        // Fail-before-pass-after pin: the substrate-canonical per-arm
17606        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
17607        // is the single dispatch every future store-facing consumer
17608        // routes through, sibling to the peer [`WitContract::slot`]
17609        // pre-projection scalar accessor on the raw-field axis and to
17610        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
17611        // [`WitTarget::pubsub_subject`] post-projection per-arm
17612        // accessors on the sibling per-payload-arm axes. The
17613        // [`WitTarget::Store`] arm round-trips its author-declared
17614        // slot verbatim as `Some("checkout/$order")`; the three
17615        // sibling arms each return `None` because they carry no
17616        // WASI-key/value slot by definition. Same fail-before-pass-
17617        // after per-variant discipline as the sibling
17618        // `wit_target_http_endpoint_pins_per_variant` +
17619        // `wit_target_pubsub_subject_pins_per_variant` pins on the
17620        // peer per-arm axes — extended onto the per-arm store-shape
17621        // post-projection axis so a future [`WitTarget`] variant
17622        // addition trips a compile-time exhaustiveness error on the
17623        // sibling [`WitTarget::store_slot`] match arms whose payload
17624        // the store-shape accept-set is meant to bound.
17625        assert_eq!(
17626            WitTarget::Store {
17627                slot: "checkout/$order",
17628            }
17629            .store_slot(),
17630            Some("checkout/$order"),
17631        );
17632        assert_eq!(
17633            WitTarget::Http {
17634                endpoint: "/charge",
17635            }
17636            .store_slot(),
17637            None,
17638        );
17639        assert_eq!(
17640            WitTarget::PubSub {
17641                subject: "events.checkout.paid",
17642            }
17643            .store_slot(),
17644            None,
17645        );
17646        assert_eq!(WitTarget::Capability.store_slot(), None);
17647    }
17648
17649    #[test]
17650    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
17651        // Per-variant coherence pin: for every arm of [`WitTarget`],
17652        // `.store_slot()` equals `.payload()` on the
17653        // [`WitTarget::Store`] arm (both project the same
17654        // author-declared slot scalar), and returns `None` on every
17655        // sibling arm regardless of whether [`WitTarget::payload`]
17656        // itself returns `Some`. Sibling to the peer
17657        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
17658        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
17659        // pins on the per-arm HTTP and PubSub axes — closes the
17660        // per-arm-vs-pan-arm byte-shape coherence trio across all
17661        // three payload arms.
17662        for variant in [
17663            WitTarget::Http {
17664                endpoint: "/charge",
17665            },
17666            WitTarget::PubSub {
17667                subject: "events.checkout.paid",
17668            },
17669            WitTarget::Store {
17670                slot: "checkout/$order",
17671            },
17672            WitTarget::Capability,
17673        ] {
17674            let per_arm = variant.store_slot();
17675            let pan_arm = variant.payload();
17676            if variant.is_store() {
17677                assert_eq!(
17678                    per_arm, pan_arm,
17679                    "WitTarget::{variant:?} store_slot() must equal \
17680                     payload() on the Store arm — a per-arm-vs-pan-arm \
17681                     split would silently drift the store-shape emit \
17682                     branch's slot-scalar source from the graph verb's \
17683                     payload scalar source",
17684                );
17685            } else {
17686                assert_eq!(
17687                    per_arm, None,
17688                    "WitTarget::{variant:?} store_slot() must return \
17689                     None on non-Store arms — a leak that surfaced an \
17690                     HTTP :endpoint or a NATS :subject through the \
17691                     key/value-slot accessor would silently widen the \
17692                     downstream WASI-key/value slot accept-set onto \
17693                     protocol shapes the kv backends can't route",
17694                );
17695            }
17696        }
17697    }
17698
17699    #[test]
17700    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
17701        // Per-variant coherence pin: for every arm of [`WitTarget`],
17702        // `.store_slot().is_some()` iff `.is_store()`. Guards the
17703        // drift surface where a future extension of the
17704        // [`WitTarget::store_slot`] accessor's accept-set landed
17705        // without a paired extension of the [`gen_platform::IsVariant`]-
17706        // derived `is_store()` predicate's accept-set. Sibling to the
17707        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
17708        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
17709        // pins — closes the per-arm predicate-vs-accessor coherence
17710        // trio across all three payload arms so the gen-platform
17711        // IsVariant predicate and the substrate-lifted per-arm
17712        // accessor carry one shared answer to "is this the Store arm?".
17713        for variant in [
17714            WitTarget::Http {
17715                endpoint: "/charge",
17716            },
17717            WitTarget::PubSub {
17718                subject: "events.checkout.paid",
17719            },
17720            WitTarget::Store {
17721                slot: "checkout/$order",
17722            },
17723            WitTarget::Capability,
17724        ] {
17725            assert_eq!(
17726                variant.store_slot().is_some(),
17727                variant.is_store(),
17728                "WitTarget::{variant:?} store_slot().is_some() must \
17729                 equal is_store() — a drift would split the store-shape \
17730                 emit branch's arm-set gate from the substrate-derived \
17731                 shape-discrimination predicate on the same axis",
17732            );
17733        }
17734    }
17735
17736    #[test]
17737    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
17738        // Fail-before-pass-after cross-axis pin on the trio
17739        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
17740        // payload-carrying arm of [`WitTarget`], exactly one per-arm
17741        // accessor returns `Some(payload)` and the two peers return
17742        // `None`; and on the payload-less [`WitTarget::Capability`]
17743        // arm, all three return `None`. Guards the drift surface where
17744        // a future extension of one per-arm accessor's accept-set (e.g.
17745        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
17746        // that widened `http_endpoint` to cover both peers without
17747        // narrowing the peer `pubsub_subject` / `store_slot` accept-
17748        // sets to keep the partition mutually exclusive) landed without
17749        // threading through the peer per-arm accessors — the resulting
17750        // silent overlap would land the same edge's payload on two
17751        // downstream per-shape emit branches at once, or leak a
17752        // pub-sub subject through the store-slot channel, at renderer
17753        // emit time far from the substrate primitive's arm-widening
17754        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
17755        // 3-way pin on the payload-field-name axis — extended onto the
17756        // per-arm-accessor payload-projection axis so the substrate-
17757        // owned partition invariant is load-bearing at every per-arm
17758        // consumer's read site.
17759        let payload_variants = [
17760            (
17761                WitTarget::Http {
17762                    endpoint: "/charge",
17763                },
17764                "http",
17765            ),
17766            (
17767                WitTarget::PubSub {
17768                    subject: "events.checkout.paid",
17769                },
17770                "pubsub",
17771            ),
17772            (
17773                WitTarget::Store {
17774                    slot: "checkout/$order",
17775                },
17776                "store",
17777            ),
17778        ];
17779        for (variant, own_arm_label) in payload_variants {
17780            let own_arm_hit = match own_arm_label {
17781                "http" => variant.is_http(),
17782                "pubsub" => variant.is_pubsub(),
17783                "store" => variant.is_store(),
17784                other => panic!("unknown own-arm label {other:?}"),
17785            };
17786            let per_arm_results = [
17787                ("http_endpoint", variant.http_endpoint()),
17788                ("pubsub_subject", variant.pubsub_subject()),
17789                ("store_slot", variant.store_slot()),
17790            ];
17791            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
17792            assert_eq!(
17793                some_count, 1,
17794                "WitTarget::{variant:?} must land exactly one per-arm \
17795                 post-projection accessor's Some result — the trio \
17796                 (http_endpoint, pubsub_subject, store_slot) must \
17797                 partition the payload arm-set; got {per_arm_results:?}",
17798            );
17799            assert!(
17800                own_arm_hit,
17801                "WitTarget::{variant:?} own-arm gen-platform predicate \
17802                 must return true on its own arm — a partition failure \
17803                 upstream of this pin",
17804            );
17805            assert!(
17806                variant.payload().is_some(),
17807                "WitTarget::{variant:?} pan-arm payload() must return \
17808                 Some on every payload-carrying arm the trio partitions",
17809            );
17810        }
17811        // The payload-less Capability arm must return None on every
17812        // per-arm accessor — the partition's terminal-fallback shape.
17813        let cap = WitTarget::Capability;
17814        assert_eq!(cap.http_endpoint(), None);
17815        assert_eq!(cap.pubsub_subject(), None);
17816        assert_eq!(cap.store_slot(), None);
17817        assert_eq!(
17818            cap.payload(),
17819            None,
17820            "WitTarget::Capability pan-arm payload() must return None — \
17821             the trio's payload-less-arm coherence witness",
17822        );
17823    }
17824
17825    #[test]
17826    fn wit_target_field_names_are_pairwise_distinct() {
17827        // Distinctness pin: if any two of the three payload-field-name
17828        // scalars ever collapse (e.g. an accidental `endpoint` copy-
17829        // paste over the `subject` const), the [`WitContract::target`]
17830        // gate's diagnostic would point authors at the wrong field —
17831        // an "expected `:endpoint`" error on a pub-sub edge would
17832        // silently misroute the fix. Same cross-axis-distinctness
17833        // discipline as the peer M3 `:placement :estrategia` variant-
17834        // discriminator scalar-value pins (cc8f749) applied to the
17835        // payload-field-name axis.
17836        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
17837        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
17838        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
17839    }
17840
17841    #[test]
17842    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
17843        // Fail-before-pass-after pin: the graph-verb payload column's
17844        // per-arm `{field}={payload}` byte-string is derived through the
17845        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
17846        // payload-carrying arms, not through a hand-rolled per-arm match
17847        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
17848        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17849        // inline. A future variant addition — the M4-and-later per-edge
17850        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
17851        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
17852        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
17853        // and both [`WitTarget::label`] (duplicate-`:contratos`
17854        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
17855        // payload column) pick up the new arm from the same dispatch.
17856        // Prior to this lift the graph verb open-coded the 4-arm match
17857        // in caixa-feira, so a variant addition would have to be threaded
17858        // through both projections in lockstep or the graph verb would
17859        // silently drop the new arm to `(capability-only)`.
17860        for variant in [
17861            WitTarget::Http {
17862                endpoint: "/charge",
17863            },
17864            WitTarget::PubSub {
17865                subject: "events.checkout.paid",
17866            },
17867            WitTarget::Store {
17868                slot: "checkout/$order",
17869            },
17870        ] {
17871            let (field, payload) = variant
17872                .payload_pair()
17873                .expect("payload arm must expose (field, payload)");
17874            assert_eq!(
17875                variant.graph_label(),
17876                format!("{field}={payload}"),
17877                "WitTarget::{variant:?} graph_label must route the \
17878                 `{{field}}={{payload}}` template through payload_pair — \
17879                 a regression to a hand-rolled per-arm match at the graph \
17880                 verb would silently disagree with a future variant \
17881                 addition landed only at payload_pair"
17882            );
17883        }
17884    }
17885
17886    #[test]
17887    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
17888        // Fail-before-pass-after pin on the payload-less arm: the graph
17889        // verb's `(capability-only)` byte-string routes through the
17890        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
17891        // [`WitTarget::Capability`] arm, not through an inline
17892        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
17893        // per-`:contratos` payload column. Peer of the sibling
17894        // [`wit_target_label_pins_per_variant_format`] Capability-arm
17895        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
17896        // extended here onto the third payload-less-arm consumer axis
17897        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
17898        // axis and the wrong-target diagnostic axis).
17899        assert_eq!(
17900            WitTarget::Capability.graph_label(),
17901            WitTarget::CAPABILITY_GRAPH_LABEL,
17902        );
17903        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
17904    }
17905
17906    #[test]
17907    fn wit_target_capability_graph_label_distinct_from_capability_label() {
17908        // Cross-consumer-axis distinctness pin: the graph-verb
17909        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
17910        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
17911        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
17912        // payload)`) surface the payload-less arm on two distinct
17913        // consumer axes; a collapse (an accidental rebrand that lands
17914        // one spelling on both consts, a copy-paste that unifies them
17915        // "for consistency") would silently merge the two byte-strings
17916        // and lose the vocabulary distinction the graph verb's
17917        // compact-column form and the diagnostic's descriptive-clause
17918        // form each carry on purpose. Peer of the sibling 4-way
17919        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
17920        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
17921        // extended here onto the cross-consumer-axis distinctness of the
17922        // two payload-less-arm consts.
17923        assert_ne!(
17924            WitTarget::CAPABILITY_GRAPH_LABEL,
17925            WitTarget::CAPABILITY_LABEL,
17926            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
17927             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
17928             diagnostic) must remain distinct — a collapse would silently \
17929             merge two consumer axes onto one spelling"
17930        );
17931    }
17932
17933    #[test]
17934    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
17935        // 4-way distinctness pin extending the sibling
17936        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
17937        // (which covers only the HTTP / PubSub / Store payload arms)
17938        // onto the fourth scalar the shared
17939        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
17940        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
17941        // (`"none"`), the payload-less Capability-arm rejection scalar.
17942        //
17943        // All four [`WitTarget::HTTP_FIELD_NAME`] /
17944        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17945        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
17946        // dispatch surface [`WitContract::target`] writes onto the
17947        // `ContratoWrongTarget::expected` field — the same `&'static
17948        // str` axis authors read as "this WIT world's shape admits
17949        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
17950        // downstream consumers rely on: an `expected: "endpoint"`
17951        // diagnostic on a Capability-shaped edge tells the author to
17952        // add a `:endpoint "…"` slot to a WIT world that admits none,
17953        // silently misrouting the fix. Until this pin landed the three
17954        // payload-arm consts were distinctness-guarded by the sibling
17955        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
17956        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
17957        // author-facing vocabulary shift from `"none"` to `"endpoint"`
17958        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
17959        // into per-shape peers) would have silently landed one
17960        // Capability-arm rejection on a payload-arm's `expected:` byte-
17961        // string and desynchronized the diagnostic from the author's
17962        // typed shape.
17963        //
17964        // Same 4-way pairwise-distinctness pin discipline as the peer
17965        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
17966        // (cc8f749) applies on the sibling M3 closed-set typed-enum
17967        // scalar-value dispatch axis; extends the pin trajectory the
17968        // sibling `wit_target_field_names_are_pairwise_distinct`
17969        // 3-way pin opened to cover the last unguarded corner on the
17970        // `ContratoWrongTarget::expected` scalar-value axis.
17971        //
17972        // Fail-before-pass-after locally verified by mutating
17973        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
17974        // — this pin fires as expected; restoring passes.
17975        let all = [
17976            WitTarget::HTTP_FIELD_NAME,
17977            WitTarget::PUBSUB_FIELD_NAME,
17978            WitTarget::STORE_FIELD_NAME,
17979            WitTarget::CAPABILITY_EXPECTED,
17980        ];
17981        for (i, a) in all.iter().enumerate() {
17982            for (j, b) in all.iter().enumerate() {
17983                if i != j {
17984                    assert_ne!(
17985                        a, b,
17986                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
17987                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
17988                         pairwise distinct — got duplicate {a:?} at indices \
17989                         {i} and {j}; all four scalars thread through the \
17990                         shared `AplicacaoError::ContratoWrongTarget::expected` \
17991                         &'static str axis, so a collapse silently misdirects \
17992                         the diagnostic on which typed shape the WIT world admits",
17993                    );
17994                }
17995            }
17996        }
17997    }
17998
17999    #[test]
18000    fn wit_target_is_variant_predicates_partition_the_arm_set() {
18001        // Fail-before-pass-after pin on the
18002        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
18003        // each of the four variants exactly one of the generated
18004        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
18005        // predicates returns `true` and the other three return
18006        // `false`. Prior to this derive the only production
18007        // arm-discriminator on [`WitTarget`] — the sync-cycle
18008        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
18009        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
18010        // the variant that expressed no compile-time link back to
18011        // the closed-set typed dispatch a future fifth
18012        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
18013        // split of [`WitTarget::PubSub`] into shape-specific peers,
18014        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
18015        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
18016        // to thread through in lockstep or the DFS exclusion would
18017        // silently disagree with the peer diagnostic templates on
18018        // which arms carry sync-versus-async semantics. Peer of the
18019        // sibling [`crate::CaixaKind`] (f5bba80),
18020        // [`PlacementStrategy`] (766ec63),
18021        // [`crate::supervisor::RestartStrategy`],
18022        // [`crate::supervisor::RestartPolicy`], and
18023        // [`crate::upgrade::UpgradeInstruction`] (915a934)
18024        // `IsVariant` derives on the sibling closed-set typed-enum
18025        // discriminator axes — extends the same one-typed-dispatch-
18026        // per-variant discipline onto the last unlifted closed-set
18027        // typed-enum discriminator on the caixa surface (the M3
18028        // mesh-slot per-`:contratos` target-arm axis), closing the
18029        // arm-discriminator convergence trajectory across every
18030        // closed-set typed enum in caixa-core.
18031        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
18032            (
18033                WitTarget::Http { endpoint: "/x" },
18034                [true, false, false, false],
18035            ),
18036            (
18037                WitTarget::PubSub {
18038                    subject: "events.x",
18039                },
18040                [false, true, false, false],
18041            ),
18042            (
18043                WitTarget::Store { slot: "kv/x" },
18044                [false, false, true, false],
18045            ),
18046            (WitTarget::Capability, [false, false, false, true]),
18047        ];
18048        for (variant, expected) in rows {
18049            let observed = [
18050                variant.is_http(),
18051                variant.is_pubsub(),
18052                variant.is_store(),
18053                variant.is_capability(),
18054            ];
18055            assert_eq!(
18056                observed, expected,
18057                "WitTarget::{variant:?} is_* predicates must partition \
18058                 the arm set (http, pubsub, store, capability); got {observed:?}"
18059            );
18060        }
18061    }
18062
18063    #[test]
18064    fn wit_target_is_variant_predicates_are_const_fn() {
18065        // The [`gen_platform::IsVariant`] derive emits `const fn`
18066        // predicates on the peer [`crate::CaixaKind`] +
18067        // [`crate::upgrade::UpgradeInstruction`] +
18068        // [`crate::supervisor::RestartStrategy`] +
18069        // [`crate::supervisor::RestartPolicy`] +
18070        // [`PlacementStrategy`] closed-set typed enums — pin the
18071        // same posture on [`WitTarget`] so a future accidental
18072        // downgrade to non-`const` (an added runtime helper reachable
18073        // only from a non-`const` context, a manual hand-rolled
18074        // `impl` that shadows the derive-generated method) trips at
18075        // caixa-core build time rather than surfacing as a downstream
18076        // `const`-context regression far from the derive declaration.
18077        //
18078        // Unlike the peer unit-variant enums (`CaixaKind` /
18079        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
18080        // whose `const` constructors need no arguments, the three
18081        // payload-carrying [`WitTarget`] arms are const-constructed
18082        // through `&'static str` payloads — the same `'static`
18083        // lifetime the closed-set typed enum's four-arm partition
18084        // pin above already threads through.
18085        //
18086        // The pin lives inside a `const { assert!(..) }` block so the
18087        // compiler enforces both halves (arm predicate is `const`-
18088        // callable AND returns `true` for the matching arm) at
18089        // caixa-core compile time — peer to the sibling
18090        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
18091        // typed enum arm-predicate const-callability axis.
18092        const {
18093            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
18094            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
18095            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
18096            assert!(WitTarget::Capability.is_capability());
18097        }
18098    }
18099
18100    #[test]
18101    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
18102        // Consumer-side pin on the sole production converge site:
18103        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
18104        // edges from the synchronous-subgraph DFS via the lifted
18105        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
18106        // predicate (rebound from the prior raw
18107        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
18108        // variant). Byte-equivalent today (`is_pubsub` is the
18109        // derive-generated `matches!(self, Self::PubSub { .. })` by
18110        // construction, the `#[is_variant(name = "pubsub")]` override
18111        // aliasing the auto-derived `is_pub_sub` back to the sibling
18112        // [`WitContract::is_pubsub`] name); pin the behavior so a
18113        // future accidental drift (a rebind onto a peer arm
18114        // predicate, a manual hand-rolled `impl` that shadows the
18115        // derive-generated method with different semantics, a peer
18116        // arm rename that shifts which variant carries sync-versus-
18117        // async semantics) trips at caixa-core test time rather than
18118        // at some downstream operator's runtime dispatch far from the
18119        // rebind commit.
18120        //
18121        // The fixture constructs a two-Servico Aplicacao with one
18122        // pub-sub edge that would close a sync-cycle if the DFS did
18123        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
18124        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
18125        // edge, which is not a cycle. A regression in the converge
18126        // (a rebind that reads the pub-sub arm as sync) would report
18127        // `AplicacaoError::ContratoCycle`.
18128        let s = AplicacaoSpec {
18129            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
18130            contratos: vec![
18131                // Pub-sub edge: DFS must skip via is_pubsub().
18132                WitContract {
18133                    de: "a".into(),
18134                    para: "b".into(),
18135                    wit: "nats:pub-sub".into(),
18136                    endpoint: None,
18137                    subject: Some("events.x".into()),
18138                    slot: None,
18139                },
18140                // HTTP edge: DFS must include.
18141                WitContract {
18142                    de: "b".into(),
18143                    para: "a".into(),
18144                    wit: "wasi:http/proxy".into(),
18145                    endpoint: Some("/x".into()),
18146                    subject: None,
18147                    slot: None,
18148                },
18149            ],
18150            politicas: MeshPolicy::default(),
18151            placement: Placement {
18152                estrategia: PlacementStrategy::Replicated,
18153                clusters: vec!["rio".into()],
18154                affinity: None,
18155                shard_key: None,
18156            },
18157            entrada: None,
18158        };
18159        s.validate()
18160            .expect("pub-sub edge must be excluded from sync-cycle DFS");
18161    }
18162
18163    #[test]
18164    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
18165        // Consumer-side pin: the same three peer consts thread through
18166        // both the [`WitTarget::label`] template (leading-`:` keyword
18167        // prefix in the duplicate-`:contratos` diagnostic) and the
18168        // [`WitContract::target`] gate's [`AplicacaoError::
18169        // ContratoMissingTarget`] `expected:` scalar (the field the
18170        // author needs to add). Pin both routes at once so a future
18171        // refactor can't accidentally split them onto separate string
18172        // literals — the "one place, everywhere reaches for it"
18173        // invariant the peer const set carries.
18174        let http_label = WitTarget::Http { endpoint: "/x" }.label();
18175        assert!(
18176            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
18177            "label must lead with :{} keyword (got {http_label:?})",
18178            WitTarget::HTTP_FIELD_NAME,
18179        );
18180
18181        let mut s = three_member_spec();
18182        s.contratos.push(WitContract {
18183            de: "cart".into(),
18184            para: "catalog".into(),
18185            wit: "kafka:topic".into(),
18186            endpoint: None,
18187            subject: None,
18188            slot: None,
18189        });
18190        match s.validate().unwrap_err() {
18191            AplicacaoError::ContratoMissingTarget { expected, .. } => {
18192                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
18193            }
18194            other => panic!("expected ContratoMissingTarget, got {other:?}"),
18195        }
18196    }
18197
18198    #[test]
18199    fn duplicate_pubsub_diagnostic_names_offending_subject() {
18200        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
18201        // on the pub-sub target axis: the duplicate-edge diagnostic
18202        // must name the `:subject` payload verbatim (not just the
18203        // `(de, para, wit)` triple). Prior to lifting the label onto
18204        // [`WitTarget::label`] the diagnostic derived the label from
18205        // raw [`WitContract`] `Option<String>` probes — a future
18206        // `WitTarget` variant addition (M4 per-edge WIT registry)
18207        // would silently fall through to the `Capability` "no
18208        // payload" default without a compiler warning. Pinning the
18209        // pub-sub arm's format closes the second of three
18210        // payload-carrying `WitTarget` arms this diagnostic threads
18211        // through.
18212        let mut s = three_member_spec();
18213        let pubsub = WitContract {
18214            de: "payment".into(),
18215            para: "cart".into(),
18216            wit: "nats:pub-sub".into(),
18217            endpoint: None,
18218            subject: Some("events.checkout.paid".into()),
18219            slot: None,
18220        };
18221        s.contratos.push(pubsub.clone());
18222        s.contratos.push(pubsub);
18223        let err = s.validate().unwrap_err();
18224        let msg = format!("{err}");
18225        assert!(
18226            msg.contains(":subject \"events.checkout.paid\""),
18227            "duplicate-pubsub diagnostic must name the offending \
18228             :subject payload (got: {msg:?})"
18229        );
18230    }
18231
18232    #[test]
18233    fn duplicate_store_diagnostic_names_offending_slot() {
18234        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
18235        // key-value target axis: the diagnostic must name the `:slot`
18236        // payload verbatim. Third of three payload-carrying
18237        // `WitTarget` arms this diagnostic threads through, closing
18238        // the per-arm label pin trilogy (`Http` — 6841,
18239        // `PubSub` + `Store` — this test + peer above).
18240        let mut s = three_member_spec();
18241        let store = WitContract {
18242            de: "cart".into(),
18243            para: "payment".into(),
18244            wit: "wasi:keyvalue/store".into(),
18245            endpoint: None,
18246            subject: None,
18247            slot: Some("checkout/$orderId".into()),
18248        };
18249        s.contratos
18250            .retain(|c| !(c.de == "cart" && c.para == "payment"));
18251        s.contratos.push(store.clone());
18252        s.contratos.push(store);
18253        let err = s.validate().unwrap_err();
18254        let msg = format!("{err}");
18255        assert!(
18256            msg.contains(":slot \"checkout/$orderId\""),
18257            "duplicate-store diagnostic must name the offending :slot \
18258             payload (got: {msg:?})"
18259        );
18260    }
18261
18262    #[test]
18263    fn rejects_entrada_path_without_leading_slash() {
18264        let mut s = three_member_spec();
18265        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
18266        let err = s.validate().unwrap_err();
18267        assert!(
18268            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
18269            "got {err:?}"
18270        );
18271    }
18272
18273    #[test]
18274    fn rejects_empty_entrada_path() {
18275        let mut s = three_member_spec();
18276        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
18277        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
18278    }
18279
18280    #[test]
18281    fn rejects_duplicate_entrada_paths() {
18282        let mut s = three_member_spec();
18283        s.entrada.as_mut().unwrap().paths = vec![
18284            "/api/cart".into(),
18285            "/api/products".into(),
18286            "/api/cart".into(),
18287        ];
18288        let err = s.validate().unwrap_err();
18289        assert!(
18290            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
18291            "got {err:?}"
18292        );
18293    }
18294
18295    #[test]
18296    fn rejects_zero_entrada_port() {
18297        let mut s = three_member_spec();
18298        s.entrada.as_mut().unwrap().port = 0;
18299        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
18300    }
18301
18302    // ── :entrada :paths value-shape gate ─────────────────────────────
18303    //
18304    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
18305    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
18306    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
18307    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
18308    // time now becomes a caixa-build-time `EntradaPathInvalid` with
18309    // the offending `:paths` entry named verbatim.
18310
18311    #[test]
18312    fn rejects_entrada_path_with_query() {
18313        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
18314        // silently passed validate and the Gateway API webhook
18315        // rejected it at apply time with no source citation.
18316        let mut s = three_member_spec();
18317        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
18318        let err = s.validate().unwrap_err();
18319        assert!(
18320            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18321                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
18322            "got {err:?}"
18323        );
18324    }
18325
18326    #[test]
18327    fn rejects_entrada_path_with_fragment() {
18328        let mut s = three_member_spec();
18329        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
18330        let err = s.validate().unwrap_err();
18331        assert!(
18332            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18333                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
18334            "got {err:?}"
18335        );
18336    }
18337
18338    #[test]
18339    fn rejects_entrada_path_with_space() {
18340        let mut s = three_member_spec();
18341        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
18342        let err = s.validate().unwrap_err();
18343        assert!(
18344            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18345                if path == "/api/my cart" && reason.contains("whitespace")),
18346            "got {err:?}"
18347        );
18348    }
18349
18350    #[test]
18351    fn rejects_entrada_path_with_tab() {
18352        let mut s = three_member_spec();
18353        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
18354        let err = s.validate().unwrap_err();
18355        assert!(
18356            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18357                if path == "/api/\tcart" && reason.contains("whitespace")),
18358            "got {err:?}"
18359        );
18360    }
18361
18362    #[test]
18363    fn rejects_entrada_path_with_control_char() {
18364        // 0x01 (SOH) — a non-whitespace control char surfaces the
18365        // distinct "control character" reason arm, separate from
18366        // the whitespace arm. Pinned so a future refactor that
18367        // collapses the two arms can't accidentally drop the more
18368        // self-locating diagnostic.
18369        let mut s = three_member_spec();
18370        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
18371        let err = s.validate().unwrap_err();
18372        assert!(
18373            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18374                if path == "/api/\x01cart" && reason.contains("control character")),
18375            "got {err:?}"
18376        );
18377    }
18378
18379    #[test]
18380    fn rejects_entrada_path_with_non_ascii() {
18381        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
18382        // unreserved-set rule rejects. The Gateway API webhook
18383        // rejects literal non-ASCII bytes; percent-encoding is the
18384        // only way to author non-ASCII in a path.
18385        let mut s = three_member_spec();
18386        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
18387        let err = s.validate().unwrap_err();
18388        assert!(
18389            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18390                if path == "/api/café" && reason.contains("non-ASCII")),
18391            "got {err:?}"
18392        );
18393    }
18394
18395    #[test]
18396    fn rejects_entrada_path_with_consecutive_slashes() {
18397        let mut s = three_member_spec();
18398        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
18399        let err = s.validate().unwrap_err();
18400        assert!(
18401            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18402                if path == "/api//cart" && reason.contains("consecutive `/`")),
18403            "got {err:?}"
18404        );
18405    }
18406
18407    #[test]
18408    fn rejects_entrada_path_with_dot_segment() {
18409        let mut s = three_member_spec();
18410        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
18411        let err = s.validate().unwrap_err();
18412        assert!(
18413            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18414                if path == "/api/./cart" && reason.contains("`.` segment")),
18415            "got {err:?}"
18416        );
18417    }
18418
18419    #[test]
18420    fn rejects_entrada_path_with_trailing_dot_segment() {
18421        // The bare `/.` and the trailing `/foo/.` are both rejected
18422        // by the Gateway API webhook; pinned separately so a future
18423        // narrowing that catches only the inner form surfaces here.
18424        let mut s = three_member_spec();
18425        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
18426        let err = s.validate().unwrap_err();
18427        assert!(
18428            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18429                if path == "/api/." && reason.contains("`.` segment")),
18430            "got {err:?}"
18431        );
18432    }
18433
18434    #[test]
18435    fn rejects_entrada_path_with_parent_segment() {
18436        let mut s = three_member_spec();
18437        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
18438        let err = s.validate().unwrap_err();
18439        assert!(
18440            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18441                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
18442            "got {err:?}"
18443        );
18444    }
18445
18446    #[test]
18447    fn rejects_entrada_path_with_trailing_parent_segment() {
18448        // Trailing `/..` — symmetric arm of the parent-segment rule,
18449        // pinned separately so a future relaxation that only checks
18450        // the inner form (`/../`) surfaces here.
18451        let mut s = three_member_spec();
18452        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
18453        let err = s.validate().unwrap_err();
18454        assert!(
18455            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18456                if path == "/api/.." && reason.contains("`..` parent-segment")),
18457            "got {err:?}"
18458        );
18459    }
18460
18461    #[test]
18462    fn rejects_entrada_path_too_long() {
18463        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
18464        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
18465        // ASCII-alphanumeric body so only the length rule fires.
18466        let mut s = three_member_spec();
18467        let big = format!("/api/{}", "a".repeat(1020));
18468        assert_eq!(big.len(), 1025);
18469        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
18470        let err = s.validate().unwrap_err();
18471        assert!(
18472            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18473                if path == &big && reason.contains("max length of 1024")),
18474            "got {err:?}"
18475        );
18476    }
18477
18478    #[test]
18479    fn entrada_path_max_length_validates() {
18480        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
18481        // maxLength cap. Boundary pin: drift in the cap surfaces here
18482        // and at `rejects_entrada_path_too_long` simultaneously.
18483        let mut s = three_member_spec();
18484        let big = format!("/api/{}", "a".repeat(1019));
18485        assert_eq!(big.len(), 1024);
18486        s.entrada.as_mut().unwrap().paths = vec![big];
18487        s.validate().unwrap();
18488    }
18489
18490    #[test]
18491    fn entrada_accepts_canonical_paths() {
18492        // Positive-control sweep — every form the Gateway API
18493        // apiserver accepts must round-trip through validate. Covers
18494        // the root catch-all, plain paths, dot-prefixed segments
18495        // (hidden-file-style, distinct from `.` and `..` segments
18496        // which are rejected), digit-bearing segments, the canonical
18497        // route-template `:param` form (`:` is RFC 3986 reserved-set
18498        // valid in paths), trailing-slash form, percent-encoded
18499        // segments, and an interior `..` *substring* (`/foo..bar` is
18500        // not the `..` segment and is allowed).
18501        for path in [
18502            "/",
18503            "/api/cart",
18504            "/healthz",
18505            "/api/.config",
18506            "/v1/products",
18507            "/products/:id",
18508            "/api/cart/",
18509            "/api/caf%C3%A9",
18510            "/foo..bar",
18511            "/...",
18512        ] {
18513            let mut s = three_member_spec();
18514            s.entrada.as_mut().unwrap().paths = vec![path.into()];
18515            s.validate()
18516                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
18517        }
18518    }
18519
18520    #[test]
18521    fn entrada_path_empty_takes_precedence_over_invalid() {
18522        // Ordering pin: `EntradaPathEmpty` is the more self-locating
18523        // diagnostic on `""` and must lead — `validate_entrada_path`
18524        // is only reached after the empty-check fires at the call
18525        // site. (The predicate itself defends against direct
18526        // invocation by returning the same error on `""`.)
18527        let mut s = three_member_spec();
18528        s.entrada.as_mut().unwrap().paths = vec![String::new()];
18529        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
18530    }
18531
18532    #[test]
18533    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
18534        // Ordering pin: a path without a leading `/` surfaces the
18535        // narrower `EntradaPathNotAbsolute` diagnostic first; the
18536        // value-shape gate is only consulted on paths that already
18537        // satisfy the absolute-prefix invariant.
18538        let mut s = three_member_spec();
18539        // `bad path` would fire the whitespace rule under the
18540        // value-shape gate, but missing-leading-`/` is the more
18541        // self-locating diagnostic.
18542        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
18543        let err = s.validate().unwrap_err();
18544        assert!(
18545            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
18546            "got {err:?}"
18547        );
18548    }
18549
18550    #[test]
18551    fn entrada_path_invalid_fires_before_duplicate_check() {
18552        // Ordering pin: a malformed path on the *first* entry of a
18553        // would-be duplicate pair fires the value-shape gate before
18554        // the duplicate gate, mirroring the
18555        // `placement_cluster_invalid_fires_before_duplicate_check`
18556        // (6cbb900) pattern on the peer axis.
18557        let mut s = three_member_spec();
18558        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
18559        let err = s.validate().unwrap_err();
18560        assert!(
18561            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
18562            "got {err:?}"
18563        );
18564    }
18565
18566    #[test]
18567    fn entrada_path_diagnostic_carries_offending_path() {
18568        // Diagnostic-shape pin — the offending path + a non-empty
18569        // reason flow through verbatim so the author can grep their
18570        // caixa.lisp for `:paths` and fix it in one edit. Same shape
18571        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
18572        let mut s = three_member_spec();
18573        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
18574        let err = s.validate().unwrap_err();
18575        match err {
18576            AplicacaoError::EntradaPathInvalid { path, reason } => {
18577                assert_eq!(path, "/api?q=1");
18578                assert!(!reason.is_empty(), "reason field must be non-empty");
18579            }
18580            other => panic!("expected EntradaPathInvalid, got {other:?}"),
18581        }
18582    }
18583
18584    #[test]
18585    fn rejects_entrada_path_with_curly_brace_template_form() {
18586        // Per-axis pin on the shared `is_gateway_api_http_path`
18587        // reserved-byte arm: the canonical "I wrote an OpenAPI
18588        // path-template `{id}` instead of the Gateway API `:id` form"
18589        // footgun the K8s apiserver would otherwise catch at admission
18590        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
18591        // landing site, far from the caixa.lisp. Surfaces as
18592        // `EntradaPathInvalid` carrying the offending path verbatim
18593        // plus the canonical `%7B`/`%7D` percent-encoding remediation
18594        // — the substrate-side `gateway_api_http_path_rejects_every_
18595        // reserved_printable_ascii_byte` predicate-level sweep pins the
18596        // full eleven-byte set; this per-axis pin confirms the
18597        // diagnostic flows through to the `EntradaPathInvalid` variant.
18598        let mut s = three_member_spec();
18599        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
18600        let err = s.validate().unwrap_err();
18601        assert!(
18602            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
18603                if path == "/api/cart/{id}"
18604                    && reason.contains("reserved character")
18605                    && reason.contains("'{'")
18606                    && reason.contains("%7B")),
18607            "got {err:?}"
18608        );
18609    }
18610
18611    #[test]
18612    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
18613        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
18614        // template_form` on the sibling `:contratos :endpoint` axis.
18615        // Same shared `is_gateway_api_http_path` reserved-byte arm
18616        // fires through `ContratoEndpointInvalid`, with the offending
18617        // endpoint + `:de` + `:para` + reason flowing through verbatim.
18618        // Pins that the lifted predicate's tightening lands on both
18619        // caller axes simultaneously — one source of truth for the
18620        // Gateway API HTTPPathMatch.value accepted set.
18621        let err = contrato_endpoint_err("/api/cart/{id}");
18622        assert!(
18623            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
18624                if endpoint == "/api/cart/{id}"
18625                    && reason.contains("reserved character")
18626                    && reason.contains("'{'")
18627                    && reason.contains("%7B")),
18628            "got {err:?}"
18629        );
18630    }
18631
18632    // ── :entrada :host value-shape gate ──────────────────────────────
18633    //
18634    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
18635    // the sibling `:host` axis. Every authoring footgun the K8s
18636    // Gateway API v1 apiserver would catch at admission time becomes
18637    // a caixa-build-time `EntradaHostInvalid` with the offending
18638    // `:host` named verbatim. Same diagnostic shape as
18639    // `MembroVersaoInvalid` (9888b13).
18640
18641    #[test]
18642    fn rejects_entrada_host_with_scheme() {
18643        // Fail-before-pass-after pin — pre-gate codebases silently
18644        // accepted `https://…` and the apiserver rejected it at apply
18645        // time with no source citation.
18646        let mut s = three_member_spec();
18647        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
18648        let err = s.validate().unwrap_err();
18649        assert!(
18650            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
18651                if host == "https://checkout.quero.cloud"),
18652            "got {err:?}"
18653        );
18654    }
18655
18656    #[test]
18657    fn rejects_entrada_host_with_port() {
18658        // The `:8080` port suffix is the canonical "I forgot the port
18659        // belongs in `:entrada :port`" footgun. The top-level `:` arm
18660        // (introduced after the per-label loop-only impl silently
18661        // surfaced a deep "label \"cloud:8080\" contains invalid
18662        // character ':'" leak) names the canonical fix verbatim — the
18663        // `:entrada :port` slot.
18664        let mut s = three_member_spec();
18665        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
18666        let err = s.validate().unwrap_err();
18667        assert!(
18668            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
18669                if host == "checkout.quero.cloud:8080"
18670                && reason.contains(":entrada :port")),
18671            "got {err:?}"
18672        );
18673    }
18674
18675    #[test]
18676    fn rejects_entrada_host_with_trailing_colon() {
18677        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
18678        // edit) — the per-label loop would land it as a deep
18679        // "label \"com:\" must start and end with an alphanumeric"
18680        // / "contains invalid character ':'" leak. The top-level
18681        // `:` arm pre-empts with the canonical `:port` slot
18682        // diagnostic.
18683        let mut s = three_member_spec();
18684        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
18685        let err = s.validate().unwrap_err();
18686        assert!(
18687            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
18688                if host == "checkout.quero.cloud:"
18689                && reason.contains(":entrada :port")),
18690            "got {err:?}"
18691        );
18692    }
18693
18694    #[test]
18695    fn rejects_entrada_host_unbracketed_ipv6_literal() {
18696        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
18697        // literals across the board (peer with `rejects_entrada_host_
18698        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
18699        // Before this top-level `:` arm landed the per-label loop
18700        // surfaced a single-label byte-class diagnostic that named the
18701        // `:` byte but not the IP-literal prohibition. The top-level
18702        // `:` arm names both the `:port` slot and the IP-literal
18703        // prohibition verbatim, so an author whose `:host "2001:..."`
18704        // value lands here gets a self-locating fix either way.
18705        let mut s = three_member_spec();
18706        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
18707        let err = s.validate().unwrap_err();
18708        assert!(
18709            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
18710                if host == "2001:db8::1"
18711                && reason.contains("IPv6")),
18712            "got {err:?}"
18713        );
18714    }
18715
18716    #[test]
18717    fn rejects_entrada_host_wildcard_with_port() {
18718        // Wildcard host with port suffix — the `*.` strip and the
18719        // per-label loop on `["foo", "quero", "cloud:8080"]` would
18720        // surface the deep byte-class leak. The top-level `:` arm sits
18721        // upstream of the `*.` strip, so it names the canonical `:port`
18722        // fix verbatim regardless of whether the host is wildcard-led.
18723        let mut s = three_member_spec();
18724        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
18725        let err = s.validate().unwrap_err();
18726        assert!(
18727            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
18728                if host == "*.quero.cloud:8080"
18729                && reason.contains(":entrada :port")),
18730            "got {err:?}"
18731        );
18732    }
18733
18734    #[test]
18735    fn rejects_entrada_host_with_path() {
18736        let mut s = three_member_spec();
18737        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
18738        let err = s.validate().unwrap_err();
18739        assert!(
18740            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
18741                if host == "checkout.quero.cloud/api"),
18742            "got {err:?}"
18743        );
18744    }
18745
18746    #[test]
18747    fn rejects_entrada_host_with_uppercase() {
18748        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
18749        // rejected, not silently lower-cased.
18750        let mut s = three_member_spec();
18751        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
18752        let err = s.validate().unwrap_err();
18753        assert!(
18754            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18755                if reason.contains("uppercase")),
18756            "got {err:?}"
18757        );
18758    }
18759
18760    #[test]
18761    fn rejects_entrada_host_with_underscore() {
18762        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
18763        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
18764        let mut s = three_member_spec();
18765        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
18766        let err = s.validate().unwrap_err();
18767        assert!(
18768            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18769                if reason.contains('_')),
18770            "got {err:?}"
18771        );
18772    }
18773
18774    #[test]
18775    fn rejects_entrada_host_ipv4_literal() {
18776        // Gateway API v1 explicitly forbids IP literals as Hostnames.
18777        let mut s = three_member_spec();
18778        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
18779        let err = s.validate().unwrap_err();
18780        assert!(
18781            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18782                if reason.contains("IPv4")),
18783            "got {err:?}"
18784        );
18785    }
18786
18787    #[test]
18788    fn rejects_entrada_host_with_trailing_dot() {
18789        // The Gateway API regex anchors at end-of-string with no
18790        // trailing `.` allowance — the FQDN root-dot form is rejected.
18791        let mut s = three_member_spec();
18792        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
18793        let err = s.validate().unwrap_err();
18794        assert!(
18795            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
18796                if host == "checkout.quero.cloud."),
18797            "got {err:?}"
18798        );
18799    }
18800
18801    #[test]
18802    fn rejects_entrada_host_with_leading_dot() {
18803        let mut s = three_member_spec();
18804        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
18805        let err = s.validate().unwrap_err();
18806        assert!(
18807            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18808                if reason.contains("empty label")),
18809            "got {err:?}"
18810        );
18811    }
18812
18813    #[test]
18814    fn rejects_entrada_host_with_consecutive_dots() {
18815        let mut s = three_member_spec();
18816        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
18817        let err = s.validate().unwrap_err();
18818        assert!(
18819            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18820                if reason.contains("empty label")),
18821            "got {err:?}"
18822        );
18823    }
18824
18825    #[test]
18826    fn rejects_entrada_host_with_leading_hyphen_label() {
18827        let mut s = three_member_spec();
18828        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
18829        let err = s.validate().unwrap_err();
18830        assert!(
18831            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18832                if reason.contains("alphanumeric")),
18833            "got {err:?}"
18834        );
18835    }
18836
18837    #[test]
18838    fn rejects_entrada_host_with_trailing_hyphen_label() {
18839        let mut s = three_member_spec();
18840        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
18841        let err = s.validate().unwrap_err();
18842        assert!(
18843            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18844                if reason.contains("alphanumeric")),
18845            "got {err:?}"
18846        );
18847    }
18848
18849    #[test]
18850    fn rejects_entrada_host_with_inner_wildcard() {
18851        // Gateway API allows `*` only as the first label (`*.foo`);
18852        // any inner or trailing `*` is rejected.
18853        let mut s = three_member_spec();
18854        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
18855        let err = s.validate().unwrap_err();
18856        assert!(
18857            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18858                if reason.contains("wildcard")),
18859            "got {err:?}"
18860        );
18861    }
18862
18863    #[test]
18864    fn rejects_entrada_host_bare_wildcard() {
18865        // `*.` with no domain is meaningless; Gateway API rejects it.
18866        let mut s = three_member_spec();
18867        s.entrada.as_mut().unwrap().host = "*.".into();
18868        let err = s.validate().unwrap_err();
18869        assert!(
18870            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18871                if reason.contains("wildcard")),
18872            "got {err:?}"
18873        );
18874    }
18875
18876    #[test]
18877    fn rejects_entrada_host_with_whitespace() {
18878        let mut s = three_member_spec();
18879        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
18880        let err = s.validate().unwrap_err();
18881        assert!(
18882            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18883                if reason.contains("whitespace")),
18884            "got {err:?}"
18885        );
18886    }
18887
18888    #[test]
18889    fn rejects_entrada_host_space_names_offending_byte() {
18890        // Embedded space in the `:entrada :host` axis surfaces the
18891        // byte-naming diagnostic through the lifted
18892        // `find_ascii_whitespace_byte` predicate. Peer with the
18893        // sibling `parse_rejects_leading_whitespace` pins on
18894        // `supervisor::duration_codec` (a7ae622) — same "the
18895        // diagnostic carries the offending byte's `0x{b:02x}` shape"
18896        // discipline extended from the shared duration codec to the
18897        // Gateway API v1 Hostname axis.
18898        let mut s = three_member_spec();
18899        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
18900        let err = s.validate().unwrap_err();
18901        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18902            panic!("expected EntradaHostInvalid, got {err:?}");
18903        };
18904        assert!(
18905            reason.contains("ASCII whitespace byte"),
18906            "expected byte-naming diagnostic, got {reason:?}"
18907        );
18908        assert!(
18909            reason.contains("0x20"),
18910            "expected offending space byte 0x20, got {reason:?}"
18911        );
18912    }
18913
18914    #[test]
18915    fn rejects_entrada_host_tab_names_offending_byte() {
18916        // Embedded tab byte in the `:entrada :host` axis — the
18917        // canonical paste-from-YAML-block-scalar / paste-from-
18918        // indented-doc footgun. Pins that the lifted predicate covers
18919        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
18920        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
18921        // not just the leading-space case the pre-lift `.bytes().any`
18922        // arm's opaque "must not contain whitespace" reason already
18923        // covered. Peer with `parse_rejects_tab_byte` on
18924        // `supervisor::duration_codec` (a7ae622).
18925        let mut s = three_member_spec();
18926        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
18927        let err = s.validate().unwrap_err();
18928        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18929            panic!("expected EntradaHostInvalid, got {err:?}");
18930        };
18931        assert!(
18932            reason.contains("ASCII whitespace byte"),
18933            "expected byte-naming diagnostic, got {reason:?}"
18934        );
18935        assert!(
18936            reason.contains("0x09"),
18937            "expected offending tab byte 0x09, got {reason:?}"
18938        );
18939    }
18940
18941    #[test]
18942    fn rejects_entrada_host_lf_names_offending_byte() {
18943        // Embedded LF byte in the `:entrada :host` axis — the
18944        // canonical paste-from-shell-heredoc / paste-from-multiline-
18945        // doc footgun the caixa-mesh YAML emitter would silently
18946        // reinterpret at the Gateway API v1 HTTPRoute admission
18947        // layer (an embedded LF byte in a YAML plain scalar either
18948        // truncates the value at the emitter or crashes the parser
18949        // on the k8s-apiserver side). Pins the third representative
18950        // of the full ASCII-whitespace set through the shared
18951        // predicate.
18952        let mut s = three_member_spec();
18953        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
18954        let err = s.validate().unwrap_err();
18955        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18956            panic!("expected EntradaHostInvalid, got {err:?}");
18957        };
18958        assert!(
18959            reason.contains("ASCII whitespace byte"),
18960            "expected byte-naming diagnostic, got {reason:?}"
18961        );
18962        assert!(
18963            reason.contains("0x0a"),
18964            "expected offending LF byte 0x0a, got {reason:?}"
18965        );
18966    }
18967
18968    #[test]
18969    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
18970        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
18971        // axis — the canonical paste-from-typography /
18972        // paste-from-word-processor footgun. Before the non-ASCII
18973        // Unicode `White_Space` scan lifted through the shared
18974        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
18975        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
18976        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
18977        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
18978        // with the far-from-source `label "…" must start and end
18979        // with an alphanumeric` diagnostic — burying the
18980        // paste-from-typography origin under a label-shape leak.
18981        // Peer with the sibling non-ASCII-whitespace pins at
18982        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
18983        // — 1b75b38), `limits::parse_duration`,
18984        // `limits::parse_millicores`, and the shared duration codec
18985        // — same "the diagnostic carries the offending Unicode
18986        // codepoint's `U+XXXX` shape" discipline extended from every
18987        // typed-magnitude codec to the Gateway API v1 Hostname axis.
18988        let mut s = three_member_spec();
18989        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
18990        let err = s.validate().unwrap_err();
18991        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18992            panic!("expected EntradaHostInvalid, got {err:?}");
18993        };
18994        assert!(
18995            reason.contains("non-ASCII Unicode whitespace character"),
18996            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
18997        );
18998        assert!(
18999            reason.contains("U+00A0"),
19000            "expected offending NBSP codepoint U+00A0, got {reason:?}"
19001        );
19002    }
19003
19004    #[test]
19005    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
19006        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
19007        // `:entrada :host` axis — the canonical paste-from-web-doc /
19008        // paste-from-published-HTML footgun. `char::is_whitespace`
19009        // returns true for `U+2028` per the Unicode `White_Space`
19010        // property, so `str::trim` at any downstream site would
19011        // silently strip it — same drift class as NBSP but on a
19012        // different codepoint region. Pins the second representative
19013        // (non-Latin-1 `char::is_whitespace` member) through the
19014        // shared predicate. Peer with
19015        // `parse_byte_size_rejects_internal_line_separator` on
19016        // `limits::parse_byte_size` (1b75b38).
19017        let mut s = three_member_spec();
19018        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
19019        let err = s.validate().unwrap_err();
19020        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19021            panic!("expected EntradaHostInvalid, got {err:?}");
19022        };
19023        assert!(
19024            reason.contains("non-ASCII Unicode whitespace character"),
19025            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
19026        );
19027        assert!(
19028            reason.contains("U+2028"),
19029            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
19030        );
19031    }
19032
19033    #[test]
19034    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
19035        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
19036        // labels in the `:entrada :host` axis — the canonical
19037        // paste-from-CJK-typography footgun (CJK IMEs default to
19038        // full-width whitespace when the space bar is pressed in
19039        // Japanese / Chinese input modes). Pins the third
19040        // representative of the non-ASCII Unicode `White_Space` set
19041        // through the shared predicate: the CJK block, distinct from
19042        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
19043        // SEPARATOR `U+2028` — covering the same axis breadth the
19044        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
19045        // (1b75b38) pins on `limits::parse_byte_size`.
19046        let mut s = three_member_spec();
19047        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
19048        let err = s.validate().unwrap_err();
19049        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19050            panic!("expected EntradaHostInvalid, got {err:?}");
19051        };
19052        assert!(
19053            reason.contains("non-ASCII Unicode whitespace character"),
19054            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
19055        );
19056        assert!(
19057            reason.contains("U+3000"),
19058            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
19059        );
19060    }
19061
19062    #[test]
19063    fn rejects_entrada_host_too_long() {
19064        // Total length cap = 253; build a 254-byte host out of two
19065        // 63-byte labels + one 62-byte label + dots.
19066        let mut s = three_member_spec();
19067        let big = format!(
19068            "{}.{}.{}.{}",
19069            "a".repeat(63),
19070            "b".repeat(63),
19071            "c".repeat(63),
19072            "d".repeat(254 - 63 * 3 - 3)
19073        );
19074        assert_eq!(big.len(), 254);
19075        s.entrada.as_mut().unwrap().host = big;
19076        let err = s.validate().unwrap_err();
19077        assert!(
19078            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19079                if reason.contains("max length of 253")),
19080            "got {err:?}"
19081        );
19082    }
19083
19084    #[test]
19085    fn rejects_entrada_host_label_too_long() {
19086        let mut s = three_member_spec();
19087        // 64-byte label — one over the per-label cap.
19088        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
19089        let err = s.validate().unwrap_err();
19090        assert!(
19091            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19092                if reason.contains("label max length of 63")),
19093            "got {err:?}"
19094        );
19095    }
19096
19097    #[test]
19098    fn entrada_host_diagnostic_carries_offending_host() {
19099        // Diagnostic-shape pin — the offending host + a non-empty
19100        // reason flow through verbatim so the author can grep their
19101        // caixa.lisp for `:host "<host>"` and fix it in one edit.
19102        let mut s = three_member_spec();
19103        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
19104        let err = s.validate().unwrap_err();
19105        match err {
19106            AplicacaoError::EntradaHostInvalid { host, reason } => {
19107                assert_eq!(host, "checkout.quero.cloud:8080");
19108                assert!(!reason.is_empty(), "reason field must be non-empty");
19109            }
19110            other => panic!("expected EntradaHostInvalid, got {other:?}"),
19111        }
19112    }
19113
19114    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
19115    // substrate primitive that folds the fourteen
19116    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
19117    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
19118    // one dispatch — peer with the sixteen equivalence pins the
19119    // [`crate::LayoutError`] `_violation` constructor family carries in
19120    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
19121    // fixture host + reason are fixed `&'static str`s so both fields of
19122    // both constructed variants pin verbatim: the `host` axis is pinned
19123    // through the shared `host.to_string()` wrap (the ctor's uniform
19124    // one-slot construction) and the `reason` axis is pinned through
19125    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
19126    // routing). Any future regression on the lift (an extra field
19127    // introduced without updating the ctor, a diverging string
19128    // conversion at either arm) surfaces at this pin's diagnostic
19129    // rather than at a per-wire-up struct-literal reintroduction.
19130    #[test]
19131    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
19132        let host = "checkout.quero.cloud:8080";
19133        let reason = "sample reason text";
19134        assert_eq!(
19135            AplicacaoError::entrada_host_invalid(host, reason),
19136            AplicacaoError::EntradaHostInvalid {
19137                host: host.to_string(),
19138                reason: reason.to_string(),
19139            },
19140            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
19141        );
19142    }
19143
19144    // Routing pin — the ctor's `host: &str` argument threads through
19145    // `.to_string()` verbatim on the `host` field, so the constructed
19146    // variant carries the offending host bytes without any wrapper-
19147    // side transformation (no `.to_ascii_lowercase()` normalization,
19148    // no `.trim()` strip, no truncation) — the same "diagnostic carries
19149    // the offending value verbatim so the author can grep their
19150    // caixa.lisp" discipline every peer typed-slot ctor at this
19151    // altitude carries.
19152    #[test]
19153    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
19154        // Uppercase + trailing whitespace + port suffix — three
19155        // wrapper-side transformations the ctor must *not* apply.
19156        let host = " Checkout.quero.CLOUD:8080 ";
19157        let err = AplicacaoError::entrada_host_invalid(host, "sample");
19158        match err {
19159            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
19160                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
19161            }
19162            other => panic!("expected EntradaHostInvalid, got {other:?}"),
19163        }
19164    }
19165
19166    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
19167    // `&str` literals and `format!(…)` outputs identically and both
19168    // route through `Into::into` verbatim onto the `reason` field.
19169    // Pins both codepaths against the same host to prove the two
19170    // shapes the fourteen wire-up sites use at their per-arm diagnostic
19171    // (ten `&str` literals — some with `.to_string()` at the caller,
19172    // some without — plus four `format!(…)` outputs) each produce
19173    // byte-equal `reason` fields against the same offending host.
19174    #[test]
19175    fn entrada_host_invalid_ctor_routes_reason_through_into() {
19176        let host = "checkout.quero.cloud";
19177        // `&str` literal — the ctor's `impl Into<String>` accepts it
19178        // without a caller-side `.to_string()`.
19179        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
19180        // Owned `String` from `format!` — the peer `format!(…)`-shaped
19181        // wire-up arm.
19182        let from_format =
19183            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
19184        // `String` from `.to_string()` on a literal — the peer
19185        // `"literal".to_string()`-shaped wire-up arm the pre-lift
19186        // sites carried.
19187        let from_to_string =
19188            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
19189        match (&from_literal, &from_format, &from_to_string) {
19190            (
19191                AplicacaoError::EntradaHostInvalid {
19192                    reason: r_lit,
19193                    host: h_lit,
19194                },
19195                AplicacaoError::EntradaHostInvalid {
19196                    reason: r_fmt,
19197                    host: h_fmt,
19198                },
19199                AplicacaoError::EntradaHostInvalid {
19200                    reason: r_ts,
19201                    host: h_ts,
19202                },
19203            ) => {
19204                assert_eq!(r_lit, "literal reason text");
19205                assert_eq!(r_fmt, "literal reason text");
19206                assert_eq!(r_ts, "literal reason text");
19207                assert_eq!(h_lit, host);
19208                assert_eq!(h_fmt, host);
19209                assert_eq!(h_ts, host);
19210            }
19211            _ => panic!("expected three EntradaHostInvalid variants"),
19212        }
19213        // Cross-arm equivalence — the three shapes must produce
19214        // byte-equal `AplicacaoError` values, so the fourteen wire-up
19215        // sites' mixed per-arm shapes fold onto one canonical form.
19216        assert_eq!(from_literal, from_format);
19217        assert_eq!(from_literal, from_to_string);
19218    }
19219
19220    // Equivalence pins for the six sibling
19221    // [`aplicacao_field_reason_ctors!`]-generated constructors that
19222    // fold the peer `{ <field>: String, reason: String }` variants
19223    // onto the same substrate-primitive family
19224    // `entrada_host_invalid` (17dd504) already carries pins for.
19225    // Each ctor's fixture pair (a fixed `&'static str` value and a
19226    // fixed `&'static str` reason) pins both fields verbatim so any
19227    // future regression on the macro (an extra field introduced
19228    // without updating the macro, a diverging string conversion at
19229    // either arm, a field-name typo on one variant that dropped it
19230    // off the shared shape) surfaces at the affected variant's pin
19231    // rather than at a per-wire-up struct-literal reintroduction. Peer
19232    // discipline of the sixteen `LayoutError` _violation ctor pins in
19233    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
19234    // and the paired
19235    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
19236    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
19237    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
19238    // (8580068) equivalence pins on the sibling `AplicacaoError`
19239    // ctor macros.
19240    #[test]
19241    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
19242        let caixa = "cart-svc";
19243        let reason = "sample reason text";
19244        assert_eq!(
19245            AplicacaoError::membro_caixa_invalid(caixa, reason),
19246            AplicacaoError::MembroCaixaInvalid {
19247                caixa: caixa.to_string(),
19248                reason: reason.to_string(),
19249            },
19250        );
19251    }
19252
19253    #[test]
19254    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
19255        let para = "checkout";
19256        let reason = "sample reason text";
19257        assert_eq!(
19258            AplicacaoError::entrada_para_invalid(para, reason),
19259            AplicacaoError::EntradaParaInvalid {
19260                para: para.to_string(),
19261                reason: reason.to_string(),
19262            },
19263        );
19264    }
19265
19266    #[test]
19267    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
19268        let path = "/api/cart";
19269        let reason = "sample reason text";
19270        assert_eq!(
19271            AplicacaoError::entrada_path_invalid(path, reason),
19272            AplicacaoError::EntradaPathInvalid {
19273                path: path.to_string(),
19274                reason: reason.to_string(),
19275            },
19276        );
19277    }
19278
19279    #[test]
19280    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
19281        let cluster = "rio";
19282        let reason = "sample reason text";
19283        assert_eq!(
19284            AplicacaoError::placement_cluster_invalid(cluster, reason),
19285            AplicacaoError::PlacementClusterInvalid {
19286                cluster: cluster.to_string(),
19287                reason: reason.to_string(),
19288            },
19289        );
19290    }
19291
19292    #[test]
19293    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
19294        let affinity = "data-locality";
19295        let reason = "sample reason text";
19296        assert_eq!(
19297            AplicacaoError::placement_affinity_invalid(affinity, reason),
19298            AplicacaoError::PlacementAffinityInvalid {
19299                affinity: affinity.to_string(),
19300                reason: reason.to_string(),
19301            },
19302        );
19303    }
19304
19305    #[test]
19306    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
19307        let shard_key = "tenantId";
19308        let reason = "sample reason text";
19309        assert_eq!(
19310            AplicacaoError::shard_key_invalid(shard_key, reason),
19311            AplicacaoError::ShardKeyInvalid {
19312                shard_key: shard_key.to_string(),
19313                reason: reason.to_string(),
19314            },
19315        );
19316    }
19317
19318    // Pin the three-slot per-`:contratos <slot>` sibling of the
19319    // two-slot `aplicacao_field_reason_ctors!` family — the sole
19320    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
19321    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
19322    // canonical author-side slot tags through the ctor and asserts
19323    // byte-equality against the pre-lift struct-literal shape so no
19324    // per-arm wrapper transformation drifts in against the sole
19325    // in-crate wire-up.
19326    #[test]
19327    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
19328        let caixa = "cart-svc";
19329        let reason = "sample reason text";
19330        for slot in [
19331            crate::render::CONTRATO_AUTHOR_KEY_DE,
19332            crate::render::CONTRATO_AUTHOR_KEY_PARA,
19333        ] {
19334            assert_eq!(
19335                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
19336                AplicacaoError::ContratoCaixaInvalid {
19337                    slot,
19338                    caixa: caixa.to_string(),
19339                    reason: reason.to_string(),
19340                },
19341            );
19342        }
19343    }
19344
19345    // The `reason: impl Into<String>` bound accepts both a `&str`
19346    // literal and a `format!(…)` owned-`String` output verbatim,
19347    // matching the peer `aplicacao_field_reason_ctors!` family's
19348    // reason-axis invariance so the sole in-crate wire-up's
19349    // `require_valid_dns_1123_label`-delivered owned-`String` return
19350    // and any future `&str` literal caller land on the same variant.
19351    #[test]
19352    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
19353        let via_literal = "literal reason text";
19354        let via_format = format!("{} reason text", "literal");
19355        for slot in [
19356            crate::render::CONTRATO_AUTHOR_KEY_DE,
19357            crate::render::CONTRATO_AUTHOR_KEY_PARA,
19358        ] {
19359            assert_eq!(
19360                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
19361                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
19362            );
19363        }
19364    }
19365
19366    // Pin the paired one-slot empty-arm sibling of the three-slot
19367    // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
19368    // closure-form empty-arm on the shared
19369    // [`crate::render::require_valid_dns_1123_label`] two-closure
19370    // cascade at [`validate_contrato_caixa`], carrying the same
19371    // `slot: &'static str` axis-tag that distinguishes the two-arm
19372    // `:de` / `:para` cascade. Sweeps both canonical author-side slot
19373    // tags through the ctor and asserts byte-equality against the
19374    // pre-lift struct-literal shape so no per-arm wrapper transformation
19375    // drifts in against the sole in-crate wire-up. Peer of the sibling
19376    // [`crate::behavior::BehaviorError::empty_path`] one-slot
19377    // `{ slot: &'static str }` equivalence pin on the paired
19378    // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
19379    // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
19380    // onto the sibling `AplicacaoError` envelope's two-arm
19381    // DNS-1123-label cascade so both empty-arm axes carry a
19382    // substrate-primitive equivalence pin rather than the pre-lift
19383    // hand-open struct-literal.
19384    #[test]
19385    fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
19386        for slot in [
19387            crate::render::CONTRATO_AUTHOR_KEY_DE,
19388            crate::render::CONTRATO_AUTHOR_KEY_PARA,
19389        ] {
19390            assert_eq!(
19391                AplicacaoError::contrato_caixa_empty(slot),
19392                AplicacaoError::ContratoCaixaEmpty { slot },
19393                "generated contrato_caixa_empty ctor must produce \
19394                 byte-equal AplicacaoError to the open-coded \
19395                 struct-literal wrap on the same &'static str fixture \
19396                 (slot = {slot:?})",
19397            );
19398        }
19399    }
19400
19401    // Cross-axis pin: sweep the constructor's single input axis (`slot:
19402    // &'static str`) through every canonical
19403    // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
19404    // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
19405    // / trim / truncate / re-order / fixed-slot substitution on the
19406    // one-field construction surfaces here rather than at a downstream
19407    // diagnostic-shape mismatch. The non-canonical arm proves the
19408    // constructor does not silently clamp `slot` to the `:de` /
19409    // `:para` roster (a future third `:contratos <slot>` axis lands on
19410    // this ctor without a per-arm rewrite), matching the discipline the
19411    // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
19412    // establishes at
19413    // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
19414    // (18114) on the paired three-slot invalid-arm envelope.
19415    #[test]
19416    fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
19417        for slot in [
19418            crate::render::CONTRATO_AUTHOR_KEY_DE,
19419            crate::render::CONTRATO_AUTHOR_KEY_PARA,
19420            ":phantom",
19421        ] {
19422            assert_eq!(
19423                AplicacaoError::contrato_caixa_empty(slot),
19424                AplicacaoError::ContratoCaixaEmpty { slot },
19425            );
19426        }
19427    }
19428
19429    // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
19430    // `:contratos :de` value must surface a diagnostic byte-equal to
19431    // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
19432    // output on the same slot fixture. Proves the sole in-crate
19433    // closure-form wire-up inside [`validate_contrato_caixa`]'s
19434    // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
19435    // through the ctor rather than the pre-lift open-coded
19436    // struct-literal block, matching the sibling per-arm
19437    // `end_to_end_wire_up_routes_through_ctor` discipline the peer
19438    // per-envelope ctor pins the recent
19439    // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
19440    // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
19441    // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
19442    // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
19443    // cross-axis Policy* variants carry. Complements the two axis-tag
19444    // arms already pinned above the `:contratos` value-shape gate
19445    // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
19446    // which anchor via the shape; this pin additionally verifies the
19447    // ctor is the exclusive construction path.
19448    #[test]
19449    fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
19450        // Empty `:de` — the sole in-crate wire-up hits the empty-arm
19451        // closure at the first `:contratos` value-shape gate, threading
19452        // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
19453        let mut s_de = three_member_spec();
19454        s_de.contratos.push(contract_http("", "catalog", "/x"));
19455        assert_eq!(
19456            s_de.validate().unwrap_err(),
19457            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
19458        );
19459        // Symmetric arm: an empty `:para` on a valid `:de` fires the
19460        // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
19461        let mut s_para = three_member_spec();
19462        s_para.contratos.push(contract_http("cart", "", "/x"));
19463        assert_eq!(
19464            s_para.validate().unwrap_err(),
19465            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
19466        );
19467    }
19468
19469    // Cross-family invariance pin — the six sibling ctors and
19470    // `entrada_host_invalid` all route `reason: impl Into<String>` +
19471    // `<field>: &str` verbatim onto their respective typed variants
19472    // through the shared [`aplicacao_field_reason_ctors!`] macro.
19473    // Sweeps a fixture pair (`&str` literal, `format!` output) against
19474    // every ctor to pin that no per-arm wrapper transformation drifted
19475    // in against the uniform macro-generated body.
19476    #[test]
19477    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
19478        let via_literal = "literal reason text";
19479        let via_format = format!("{} reason text", "literal");
19480        assert_eq!(
19481            AplicacaoError::membro_caixa_invalid("m", via_literal),
19482            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
19483        );
19484        assert_eq!(
19485            AplicacaoError::entrada_para_invalid("p", via_literal),
19486            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
19487        );
19488        assert_eq!(
19489            AplicacaoError::entrada_path_invalid("/a", via_literal),
19490            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
19491        );
19492        assert_eq!(
19493            AplicacaoError::placement_cluster_invalid("c", via_literal),
19494            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
19495        );
19496        assert_eq!(
19497            AplicacaoError::placement_affinity_invalid("a", via_literal),
19498            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
19499        );
19500        assert_eq!(
19501            AplicacaoError::shard_key_invalid("k", via_literal),
19502            AplicacaoError::shard_key_invalid("k", via_format.clone()),
19503        );
19504        assert_eq!(
19505            AplicacaoError::entrada_host_invalid("h", via_literal),
19506            AplicacaoError::entrada_host_invalid("h", via_format),
19507        );
19508    }
19509
19510    #[test]
19511    fn entrada_host_empty_takes_precedence_over_invalid() {
19512        // Ordering pin: `EmptyEntradaHost` is the more self-locating
19513        // diagnostic on `""` and must lead — `validate_entrada_host`
19514        // is only reached after the empty-check fires at the call
19515        // site. (The predicate itself defends against direct
19516        // invocation by returning the same error on `""`.)
19517        let mut s = three_member_spec();
19518        s.entrada.as_mut().unwrap().host = String::new();
19519        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
19520    }
19521
19522    #[test]
19523    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
19524        // Ordering pin: a missing :para member is the more
19525        // self-locating diagnostic and fires before the host gate.
19526        let mut s = three_member_spec();
19527        let e = s.entrada.as_mut().unwrap();
19528        e.para = "ghost".into();
19529        e.host = "BAD HOST".into();
19530        let err = s.validate().unwrap_err();
19531        assert!(
19532            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
19533            "got {err:?}"
19534        );
19535    }
19536
19537    #[test]
19538    fn entrada_host_invalid_fires_before_port_zero() {
19539        // Ordering pin: the host gate fires before the port gate so
19540        // a malformed host is named even when the port is also wrong.
19541        let mut s = three_member_spec();
19542        let e = s.entrada.as_mut().unwrap();
19543        e.host = "Checkout.quero.cloud".into();
19544        e.port = 0;
19545        let err = s.validate().unwrap_err();
19546        assert!(
19547            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
19548                if host == "Checkout.quero.cloud"),
19549            "got {err:?}"
19550        );
19551    }
19552
19553    #[test]
19554    fn entrada_accepts_canonical_hosts() {
19555        // Positive-control sweep — every form the Gateway API
19556        // apiserver accepts must round-trip through validate. Covers
19557        // a plain DNS subdomain, a leading wildcard, a single-label
19558        // host (cluster-internal), a max-length-edge label, a
19559        // hyphen-bearing label, and a Punycode IDN label.
19560        for host in [
19561            "checkout.quero.cloud",
19562            "*.quero.cloud",
19563            "checkout",
19564            // 63-byte label — exactly the per-label cap.
19565            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
19566            "foo-bar.quero.cloud",
19567            // Punycode IDN — valid because the author pre-encoded.
19568            "xn--bcher-kva.example.com",
19569        ] {
19570            let mut s = three_member_spec();
19571            s.entrada.as_mut().unwrap().host = host.into();
19572            s.validate()
19573                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
19574        }
19575    }
19576
19577    #[test]
19578    fn entrada_host_max_length_validates() {
19579        // 253-byte host is the cap exactly — must validate. Build a
19580        // 253-byte host out of three 63-byte labels + one 61-byte
19581        // label + 3 dots = 252 bytes, then pad one byte to 253.
19582        let mut s = three_member_spec();
19583        let host = format!(
19584            "{}.{}.{}.{}",
19585            "a".repeat(63),
19586            "b".repeat(63),
19587            "c".repeat(63),
19588            "d".repeat(253 - 63 * 3 - 3)
19589        );
19590        assert_eq!(host.len(), 253);
19591        s.entrada.as_mut().unwrap().host = host;
19592        s.validate().unwrap();
19593    }
19594
19595    #[test]
19596    fn entrada_host_total_length_cap_threads_lifted_render_const() {
19597        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
19598        // total-length gate now reads the K8s Gateway API v1 Hostname
19599        // `maxLength: 253` cap from the lifted
19600        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
19601        // of truth — the same constant every future Gateway-API-Hostname
19602        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
19603        // materializer's per-host validator, the future per-`Certificate`
19604        // SAN emitter for cert-manager, the multi-`:entrada`
19605        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
19606        // from. Before the lift, the aplicacao-side reader consumed a
19607        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
19608        // 253-byte value as the peer render-side canonical bounds
19609        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
19610        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
19611        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
19612        // module boundary — a future 253-byte drift on either side would
19613        // silently split into two axes' worth of admission-schema mismatch
19614        // without a build-time signal. Pin the cap through a fresh 254-
19615        // byte host that hits the total-length arm, then read the reason
19616        // for the exact byte count the shared constant carries: any future
19617        // regression on the lift (a private alias reintroduced, a hard-
19618        // coded literal at the arm, a mismatch between the aplicacao-side
19619        // and render-side canonicals) surfaces as this pin's diagnostic
19620        // failing to match, not as a per-cluster admission rejection far
19621        // from the caixa.lisp source line.
19622        let mut s = three_member_spec();
19623        let over_cap = format!(
19624            "{}.{}.{}.{}",
19625            "a".repeat(63),
19626            "b".repeat(63),
19627            "c".repeat(63),
19628            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
19629        );
19630        assert_eq!(
19631            over_cap.len(),
19632            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
19633        );
19634        s.entrada.as_mut().unwrap().host = over_cap;
19635        let err = s.validate().unwrap_err();
19636        match err {
19637            AplicacaoError::EntradaHostInvalid { reason, .. } => {
19638                let needle = format!(
19639                    "max length of {} bytes",
19640                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
19641                );
19642                assert!(
19643                    reason.contains(&needle),
19644                    "diagnostic must name the lifted \
19645                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
19646                );
19647            }
19648            other => panic!("expected EntradaHostInvalid, got {other:?}"),
19649        }
19650    }
19651
19652    #[test]
19653    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
19654        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
19655        // on the per-label-cap axis. Before the lift, the aplicacao-side
19656        // per-label arm consumed a private const alias
19657        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
19658        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
19659        // split from it at the module boundary — every `.`-separated
19660        // label in a Gateway API v1 Hostname is a DNS-1123 label under
19661        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
19662        // so the private alias's 63 and the canonical const's 63 were
19663        // pinning the same underlying rule twice. Pin the cap through a
19664        // 64-byte label that hits the per-label arm, then read the reason
19665        // for the exact byte count the shared constant carries: any
19666        // future drift on either side (a private alias reintroduced, a
19667        // hard-coded literal at the arm, a mismatch between the two
19668        // 63-byte pins) surfaces at this pin's diagnostic rather than at
19669        // a per-cluster admission rejection whose "field is invalid"
19670        // opacity misframes the root cause.
19671        let mut s = three_member_spec();
19672        let over_cap_label = format!(
19673            "{}.quero.cloud",
19674            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
19675        );
19676        s.entrada.as_mut().unwrap().host = over_cap_label;
19677        let err = s.validate().unwrap_err();
19678        match err {
19679            AplicacaoError::EntradaHostInvalid { reason, .. } => {
19680                let needle = format!(
19681                    "label max length of {} bytes",
19682                    crate::render::DNS_1123_LABEL_MAX_LEN,
19683                );
19684                assert!(
19685                    reason.contains(&needle),
19686                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
19687                     cap verbatim on the per-label arm, got: {reason:?}",
19688                );
19689            }
19690            other => panic!("expected EntradaHostInvalid, got {other:?}"),
19691        }
19692    }
19693
19694    #[test]
19695    fn entrada_with_empty_paths_validates() {
19696        // Empty `:paths` is the documented "match every path" form;
19697        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
19698        let mut s = three_member_spec();
19699        s.entrada.as_mut().unwrap().paths = vec![];
19700        s.validate().unwrap();
19701    }
19702
19703    #[test]
19704    fn entrada_root_path_validates() {
19705        // The author-supplied bare-root `:entrada :paths` entry is the
19706        // same byte-shape the peer emit-side catch-all constant
19707        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
19708        // the author's `:paths` list is empty — sweeping the test-side
19709        // probe literal onto the lifted const closes the two-axis pin
19710        // (author-side admit + emit-side canonical fallback) around
19711        // one `&'static str`, so a future rebrand of the catch-all
19712        // reaches both consumers by construction. Peer to
19713        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
19714        // on the canonical-literal pin surface.
19715        let mut s = three_member_spec();
19716        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
19717        s.validate().unwrap();
19718    }
19719
19720    #[test]
19721    fn placement_strategy_variants_round_trip() {
19722        for s in [
19723            PlacementStrategy::SingleNode,
19724            PlacementStrategy::Replicated,
19725            PlacementStrategy::Sharded,
19726        ] {
19727            let p = Placement {
19728                estrategia: s,
19729                clusters: vec!["rio".into()],
19730                affinity: None,
19731                // Route the paired `:shard-key` fixture-builder through the
19732                // typed cross-slot invariant predicate
19733                // [`PlacementStrategy::requires_shard_key`] rather than the
19734                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
19735                // arm-identity predicate — the two answer the same
19736                // question under today's closed accept-set but a future
19737                // arm addition that consumed `:shard-key` under a
19738                // non-`Sharded` name would silently mis-attach the
19739                // fixture's `:shard-key` if the builder read through the
19740                // arm-identity predicate. The cross-slot-invariant
19741                // predicate migrates through one caixa-core edit on any
19742                // future arm addition; the fixture keeps producing a
19743                // `validate()`-passing round-trip by construction.
19744                shard_key: if s.requires_shard_key() {
19745                    Some("$key".into())
19746                } else {
19747                    None
19748                },
19749            };
19750            let json = serde_json::to_string(&p).unwrap();
19751            let back: Placement = serde_json::from_str(&json).unwrap();
19752            assert_eq!(back, p);
19753        }
19754    }
19755
19756    #[test]
19757    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
19758        // The fail-before-pass-after pin: pre-lift there was no
19759        // single-source binding between the [`PlacementStrategy`]
19760        // variant name the `Serialize` derive emits and the byte-
19761        // string every downstream cluster-side dispatcher (the
19762        // `lareira-fleet-programs` aggregator's per-entry strategy
19763        // branch, the future `app-operator` reconciler, the M3
19764        // Adaptive compression pass's per-strategy weighting) probes
19765        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
19766        // future `#[serde(rename_all = "kebab-case")]` attribute on
19767        // the enum — or a variant rename in the source — would
19768        // silently rebrand the emitted scalar under one spelling
19769        // while every downstream dispatcher still probed the other,
19770        // with the failure surfacing at the aggregator's dispatch
19771        // step or the operator's reconcile posture (workloads coming
19772        // up under the `default()` `Replicated` arm rather than the
19773        // typed slot's declared strategy) far from the source
19774        // rebrand commit and with no field naming the drift. Pinning
19775        // the two paths (the `Serialize` derive's serialized string
19776        // AND the [`PlacementStrategy::as_str`] helper) to the same
19777        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
19778        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
19779        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
19780        // makes any future drift on either endpoint fail here at
19781        // caixa-core build time.
19782        for (variant, expected) in [
19783            (
19784                PlacementStrategy::SingleNode,
19785                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19786            ),
19787            (
19788                PlacementStrategy::Replicated,
19789                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19790            ),
19791            (
19792                PlacementStrategy::Sharded,
19793                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19794            ),
19795        ] {
19796            let json = serde_json::to_string(&variant).unwrap();
19797            assert_eq!(
19798                json,
19799                format!("\"{expected}\""),
19800                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
19801            );
19802            assert_eq!(
19803                variant.as_str(),
19804                expected,
19805                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
19806                 M3_PLACEMENT_ESTRATEGIA_* constant"
19807            );
19808        }
19809    }
19810
19811    #[test]
19812    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
19813        // Cross-arm drift-detection pin on the M3
19814        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
19815        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
19816        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
19817        // scalar-value pentad: a future collapse of two canonical
19818        // variant byte-strings onto the same value (an accidental
19819        // copy-paste flip of
19820        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
19821        // read `"SingleNode"`, a per-arm rebrand that lands one const
19822        // without touching its paired peer) would silently reroute
19823        // every downstream operator's per-strategy dispatch onto the
19824        // sibling arm's reconcile branch and pass every
19825        // propagation-probe test that expected only the stale arm's
19826        // value — a `Replicated`-declared Aplicacao would come up
19827        // under the `SingleNode` primary-and-standby reconcile
19828        // posture, so every-cluster active-active workload would
19829        // silently collapse onto one-cluster-runs-at-a-time takeover
19830        // semantics against its declared strategy, with no field
19831        // naming the strategy-value drift root cause. Peer of the
19832        // sibling
19833        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
19834        // (09ffb2d) /
19835        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
19836        // (ccdf955) /
19837        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
19838        // (d739850) distinctness pins on the sibling OTP-shape /
19839        // caixa-kind closed-set typed-enum discriminator axes — the
19840        // fourth (and structurally the M3 mesh-primitive-defining)
19841        // closed-set typed-enum axis to converge on the same
19842        // "pairwise-distinct-by-construction" discipline.
19843        //
19844        // Fail-before-pass-after locally verified by mutating
19845        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
19846        // also read `"SingleNode"` — this pin fires as expected;
19847        // restoring passes.
19848        let all = [
19849            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19850            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19851            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19852        ];
19853        for (i, a) in all.iter().enumerate() {
19854            for (j, b) in all.iter().enumerate() {
19855                if i != j {
19856                    assert_ne!(
19857                        a, b,
19858                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
19859                         distinct — got duplicate {a:?} at indices {i} and {j}",
19860                    );
19861                }
19862            }
19863        }
19864    }
19865
19866    #[test]
19867    fn placement_strategy_display_routes_through_as_str_helper() {
19868        // The fail-before-pass-after pin: pre-lift the sibling
19869        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
19870        // / [`crate::supervisor::RestartPolicy`] both carried a stable
19871        // [`std::fmt::Display`] surface via their
19872        // `#[discriminant(also_display)]` gen-platform derive, but
19873        // [`PlacementStrategy`] did not — every consumer reaching for
19874        // a strategy byte-string past the wire format had to pick
19875        // between three paths ([`PlacementStrategy::as_str`], the
19876        // `Serialize` derive's serialized string, or `format!("{v:?}")`
19877        // on the `Debug` derive), any two of which a future variant
19878        // rename or `#[serde(rename_all = "kebab-case")]` attribute
19879        // would silently desynchronize. Wiring [`std::fmt::Display`]
19880        // through [`PlacementStrategy::as_str`] closes the third path:
19881        // every `format!("{v}")` call reaches the same lifted
19882        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
19883        // and the [`PlacementStrategy::as_str`] helper already route
19884        // through, so a future variant rename lands at exactly one
19885        // place. Pin the routing here so a future
19886        // `impl std::fmt::Display for PlacementStrategy` reimplementation
19887        // that hand-rolls the arms instead of delegating to
19888        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
19889        for variant in [
19890            PlacementStrategy::SingleNode,
19891            PlacementStrategy::Replicated,
19892            PlacementStrategy::Sharded,
19893        ] {
19894            assert_eq!(
19895                variant.to_string(),
19896                variant.as_str(),
19897                "PlacementStrategy::{variant:?} Display must route through \
19898                 PlacementStrategy::as_str (single source of truth: the lifted \
19899                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
19900            );
19901        }
19902    }
19903
19904    #[test]
19905    fn placement_strategy_display_matches_serialized_wire_byte_string() {
19906        // The fail-before-pass-after pin on the second half of the
19907        // three-path convergence: `Display` (user-facing text) agrees
19908        // byte-for-byte with the `Serialize` derive's wire format
19909        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
19910        // scalar) on every variant. Pre-lift the two paths were
19911        // structurally independent — a future
19912        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
19913        // would silently rebrand the emitted wire scalar
19914        // (`single-node`, `replicated`, `sharded`) while every consumer
19915        // that pretty-prints the strategy (the M3 diagnostic templates,
19916        // the future `feira app graph` per-Aplicacao strategy line,
19917        // the future M4 CR materializer's admission-webhook rejection
19918        // body) would still emit the TitleCase form the `as_str` /
19919        // `Display` route returns, with the mismatch surfacing at
19920        // consumer parse time / operator dispatch time far from the
19921        // source rebrand commit. Pin the two paths byte-for-byte here
19922        // so any future serde-attribute or variant-rename drift is a
19923        // caixa-core-build-time test failure at this call, not a
19924        // silent per-consumer dispatch miss.
19925        for variant in [
19926            PlacementStrategy::SingleNode,
19927            PlacementStrategy::Replicated,
19928            PlacementStrategy::Sharded,
19929        ] {
19930            let wire = serde_json::to_string(&variant).unwrap();
19931            // Strip the outer `"…"` the JSON string form carries — the
19932            // wire scalar the K8s / YAML apiserver consumes is the
19933            // enclosed byte-string, not the quote wrapper.
19934            let unquoted = wire
19935                .strip_prefix('"')
19936                .and_then(|s| s.strip_suffix('"'))
19937                .expect("serialized PlacementStrategy is a JSON string");
19938            assert_eq!(
19939                variant.to_string(),
19940                unquoted,
19941                "PlacementStrategy::{variant:?} Display byte-string must match the \
19942                 Serialize derive's wire byte-string (three-path convergence: \
19943                 Display + as_str + Serialize all resolve to the same \
19944                 M3_PLACEMENT_ESTRATEGIA_* const)"
19945            );
19946        }
19947    }
19948
19949    #[test]
19950    fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
19951        // Fail-before-pass-after byte-parity pin on the lifted
19952        // `impl AsRef<str> for PlacementStrategy` — asserts the
19953        // standard-library trait impl and the substrate-primitive
19954        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
19955        // to the same `&str` per instance across the three-arm closed
19956        // set, so any future silent detour that routes the impl through
19957        // a divergent projection (a per-arm inline
19958        // `match self { PlacementStrategy::Sharded => "Sharded", … }`
19959        // re-inlining that opens a compile-time link to the un-lifted
19960        // arm-literal, a swap onto the kebab-case
19961        // [`gen_platform::Discriminant`] catalog identity that would
19962        // collide the wire axis with the dispatcher-catalog axis) trips
19963        // at caixa-core test time under `PartialEq` rather than at a
19964        // downstream `impl AsRef<str>`-bound consumer's silent split.
19965        // Sweeps every one of the three arms [`PlacementStrategy::ALL`]
19966        // carries so no arm's projection is covered only by the sibling
19967        // wire-format `Serialize` derive path. Peer of the sibling
19968        // [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
19969        // (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
19970        // (63eb1a4) on the paired M2 per-supervisor closed-set typed
19971        // enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
19972        // (16d5c7e) pin on the paired top-level `:versao` typed newtype
19973        // — the four pins together close the substrate primitive's
19974        // `AsRef<str>` projection axis on every closed-set typed enum
19975        // /newtype on the M2/M3 mesh + supervision + version surface.
19976        for &variant in PlacementStrategy::ALL {
19977            assert_eq!(
19978                <PlacementStrategy as AsRef<str>>::as_ref(&variant),
19979                variant.as_str(),
19980                "AsRef<str> impl on PlacementStrategy::{variant:?} must \
19981                 byte-equal PlacementStrategy::as_str on the same instance \
19982                 — divergence signals a silent detour off the substrate-\
19983                 primitive accessor"
19984            );
19985        }
19986    }
19987
19988    #[test]
19989    fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
19990        // Fail-before-pass-after byte-parity pin on the three-path
19991        // convergence discipline the M3 per-Aplicacao distribution-
19992        // strategy primitive now carries on the `&str`-projection axis:
19993        // `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
19994        // lifted impl), `format!("{v}")` (the pre-existing
19995        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
19996        // primitive `pub const fn` accessor both trait impls delegate
19997        // through) must resolve to the same byte-string on every
19998        // instance across the three-arm closed set. Refuses any future
19999        // divergence between the two trait impls (a stray
20000        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
20001        // than delegating through the shared accessor; a hypothetical
20002        // `AsRef<str>` rewrite that inlines a per-arm literal cascade)
20003        // that would silently split the two projection paths of the
20004        // same closed-set typed enum. Mirrors the sibling three-path-
20005        // convergence discipline the peer
20006        // [`crate::supervisor::RestartPolicy`] typed enum carries on its
20007        // `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
20008        // `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
20009        // 419ea81), the peer [`crate::supervisor::RestartStrategy`]
20010        // triple (supervisor.rs pin
20011        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
20012        // 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
20013        // triple (version.rs pin
20014        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
20015        // 16d5c7e).
20016        for &variant in PlacementStrategy::ALL {
20017            let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
20018            let via_display: String = format!("{variant}");
20019            let via_accessor: &str = variant.as_str();
20020            assert_eq!(via_as_ref, via_accessor);
20021            assert_eq!(via_display, via_accessor);
20022            assert_eq!(via_as_ref, via_display.as_str());
20023        }
20024    }
20025
20026    #[test]
20027    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
20028        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20029        // derive on [`PlacementStrategy`]: for each of the three variants
20030        // exactly one of the generated `is_single_node` / `is_replicated`
20031        // / `is_sharded` predicates returns `true` and the other two
20032        // return `false`. Prior to this derive the three per-arm
20033        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
20034        // (the `placement_strategy_variants_round_trip` fixture, the
20035        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
20036        // fixture, and the
20037        // `validate_placement_reads_through_lifted_estrategia_accessor`
20038        // fixture) each open-coded a per-arm PartialEq compare against
20039        // the enum variant — three sites that expressed no compile-time
20040        // link back to the closed-set typed dispatch a future fourth
20041        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
20042        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
20043        // would have to thread through in lockstep or one fixture would
20044        // silently disagree with the others on which arms consume the
20045        // `:shard-key` axis. Peer of the sibling
20046        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
20047        // / [`crate::supervisor::RestartPolicy`] /
20048        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
20049        // the sibling closed-set typed-enum discriminator axes — extends
20050        // the same one-typed-dispatch-per-variant discipline onto the
20051        // fifth (and only remaining) closed-set typed-enum discriminator
20052        // on the caixa surface, closing the axis on the M3 mesh-slot
20053        // family.
20054        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
20055            (PlacementStrategy::SingleNode, [true, false, false]),
20056            (PlacementStrategy::Replicated, [false, true, false]),
20057            (PlacementStrategy::Sharded, [false, false, true]),
20058        ];
20059        for (variant, expected) in rows {
20060            let observed = [
20061                variant.is_single_node(),
20062                variant.is_replicated(),
20063                variant.is_sharded(),
20064            ];
20065            assert_eq!(
20066                observed, expected,
20067                "PlacementStrategy::{variant:?} is_* predicates must partition \
20068                 the arm set (single_node, replicated, sharded); got {observed:?}"
20069            );
20070        }
20071    }
20072
20073    #[test]
20074    fn placement_strategy_is_variant_predicates_are_const_fn() {
20075        // The [`gen_platform::IsVariant`] derive emits `const fn`
20076        // predicates on the peer [`crate::CaixaKind`] +
20077        // [`crate::upgrade::UpgradeInstruction`] +
20078        // [`crate::supervisor::RestartStrategy`] +
20079        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
20080        // pin the same posture on [`PlacementStrategy`] so a future
20081        // accidental downgrade to non-`const` (an added runtime helper
20082        // reachable only from a non-`const` context, a manual hand-rolled
20083        // `impl` that shadows the derive-generated method) trips at
20084        // caixa-core build time rather than surfacing as a downstream
20085        // `const`-context regression far from the derive declaration.
20086        //
20087        // The pin lives inside a `const { assert!(..) }` block so the
20088        // compiler enforces both halves (arm predicate is `const`-
20089        // callable AND returns `true` for the matching arm) at
20090        // caixa-core compile time — peer to the sibling
20091        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
20092        // pins on the closed-set typed enum arm-predicate const-
20093        // callability axis.
20094        const {
20095            assert!(PlacementStrategy::SingleNode.is_single_node());
20096            assert!(PlacementStrategy::Replicated.is_replicated());
20097            assert!(PlacementStrategy::Sharded.is_sharded());
20098        }
20099    }
20100
20101    #[test]
20102    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
20103        // Fail-before-pass-after pin on the substrate-lifted
20104        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
20105        // per-arm predicate: for each variant in the closed accept-set the
20106        // predicate returns `true` iff the variant consumes the paired
20107        // [`Placement::shard_key`] axis under
20108        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
20109        // partition. Today the accept-set is the singleton `{Sharded}` —
20110        // `Sharded` is the Akka-style hash-keyed distribution arm
20111        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
20112        // §II.1) and `Replicated` (active-active) refuse the axis through
20113        // [`AplicacaoError::ShardKeyOnNonSharded`].
20114        //
20115        // Pins the per-arm truth-table so a future arm addition (an
20116        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
20117        // roadmap names, a `WeightedShard` promotion the future M5
20118        // adaptive-placement engine acknowledges) that landed a variant
20119        // without extending this predicate's arm-set would surface as a
20120        // caixa-core build-time exhaustiveness error at the
20121        // `match self { … }` arm-fan below rather than a silent per-consumer
20122        // mis-classification at renderer emit time. The paired
20123        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
20124        // predicate stays a distinct question — arm-identity (which the
20125        // sibling
20126        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
20127        // pin already locks) is not cross-slot-invariant consumption; today
20128        // they trip on the same singleton but the pair migrates through
20129        // one caixa-core edit on any future arm addition.
20130        //
20131        // Peer of the sibling per-arm classifier pins
20132        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
20133        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
20134        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
20135        // derived paired predicate on the post-projection typed-view axis
20136        // — same "per-arm semantic-classification predicate paired with
20137        // the arm-identity predicate the derive already emits" discipline
20138        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
20139        // `:placement :shard-key` cross-slot-invariant axis.
20140        let rows: [(PlacementStrategy, bool); 3] = [
20141            (PlacementStrategy::SingleNode, false),
20142            (PlacementStrategy::Replicated, false),
20143            (PlacementStrategy::Sharded, true),
20144        ];
20145        for (variant, expected) in rows {
20146            assert_eq!(
20147                variant.requires_shard_key(),
20148                expected,
20149                "PlacementStrategy::{variant:?}.requires_shard_key() must \
20150                 be {expected} (the substrate-canonical cross-slot invariant \
20151                 on the :placement :shard-key axis; today `Sharded` is the \
20152                 singleton consuming arm — MESH-COMPOSITION §II.4)",
20153            );
20154        }
20155    }
20156
20157    #[test]
20158    fn placement_strategy_requires_shard_key_is_const_fn() {
20159        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
20160        // invariant per-arm predicate is declared `#[must_use] pub const
20161        // fn` — pin the `const`-eval posture here so a future accidental
20162        // downgrade to non-`const` (an added runtime helper reachable
20163        // only from a non-`const` context, a manual hand-rolled `impl`
20164        // that shadows the current three-arm `match self { … }` dispatch)
20165        // trips at caixa-core build time rather than surfacing as a
20166        // downstream `const`-context regression far from the declaration.
20167        // Same shape as the sibling
20168        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
20169        // the peer [`gen_platform::IsVariant`]-derived arm-identity
20170        // predicate axis, but here the load-bearing assertions live in
20171        // module-scope `const _: () = assert!(…)` items so a violation
20172        // fails at compile time (const-eval trip) rather than test time —
20173        // strictly stronger than the runtime `assert!(CONST)` pattern the
20174        // sibling pin uses, and side-steps the
20175        // `clippy::assertions_on_constants` lint the runtime pattern
20176        // otherwise accumulates on the module baseline.
20177        //
20178        // The test body simply witnesses that the module-scope items
20179        // compiled and the runtime dispatch agrees with the const-eval
20180        // dispatch on every arm — the runtime read gives the test a
20181        // failure surface (rather than an empty test body clippy would
20182        // flag as a no-op).
20183        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
20184        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
20185        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
20186        assert_eq!(
20187            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
20188            [
20189                PlacementStrategy::SingleNode.requires_shard_key(),
20190                PlacementStrategy::Replicated.requires_shard_key(),
20191                PlacementStrategy::Sharded.requires_shard_key(),
20192            ],
20193            "runtime and const-eval dispatch on \
20194             PlacementStrategy::requires_shard_key must agree on every arm",
20195        );
20196    }
20197
20198    #[test]
20199    fn placement_estrategia_accessor_is_const_fn() {
20200        // The [`Placement::estrategia`] per-`:placement` distribution-
20201        // strategy `Copy`-return scalar accessor is declared
20202        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
20203        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
20204        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
20205        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
20206        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
20207        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
20208        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
20209        // [`RateLimit`], every one a `pub const fn`). Pin the
20210        // `const`-eval posture here so a future accidental downgrade to
20211        // non-`const` (an added runtime helper reachable only from a
20212        // non-`const` context, a slot promotion to a non-`Copy` return
20213        // that would silently drop the `const` qualifier, a manual
20214        // hand-rolled shadow) trips at caixa-core build time rather
20215        // than surfacing as a downstream `const`-context regression far
20216        // from the declaration.
20217        //
20218        // Same shape as the sibling
20219        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
20220        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
20221        // predicate axis — the load-bearing witness lives in the
20222        // module-scope `const fn` wrapper `estrategia_via_const_fn`
20223        // below: a body that calls [`Placement::estrategia`] under a
20224        // `const fn` signature is well-formed only when the callee is
20225        // itself `const fn`, so any future accidental downgrade of
20226        // [`Placement::estrategia`] to non-`const` fails at caixa-core
20227        // build time (const-eval E0015 / E0658 depending on the arm),
20228        // strictly stronger than a runtime `assert!(CONST)` and
20229        // side-stepping the destructor-in-const restriction that
20230        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
20231        // items on `Placement`'s `Vec<String>` / `Option<String>`
20232        // carriers.
20233        //
20234        // The runtime body witnesses that the const-eval-shaped
20235        // wrapper agrees with a direct call on every closed-set arm.
20236        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
20237            p.estrategia()
20238        }
20239        for estrategia in [
20240            PlacementStrategy::SingleNode,
20241            PlacementStrategy::Replicated,
20242            PlacementStrategy::Sharded,
20243        ] {
20244            let placement = Placement {
20245                estrategia,
20246                clusters: Vec::new(),
20247                affinity: None,
20248                shard_key: None,
20249            };
20250            assert_eq!(
20251                estrategia_via_const_fn(&placement),
20252                placement.estrategia(),
20253                "const-fn-wrapped and direct dispatch on \
20254                 Placement::estrategia must agree for {estrategia:?}",
20255            );
20256        }
20257    }
20258
20259    #[test]
20260    fn entrada_port_accessor_is_const_fn() {
20261        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
20262        // scalar accessor is declared `#[must_use] pub const fn` —
20263        // matching the peer M3 mesh-slot `Copy`-return accessor family
20264        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
20265        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
20266        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
20267        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
20268        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
20269        // [`RateLimit::window`] on the sibling [`RateLimit`], the
20270        // sibling per-`:placement` [`Placement::estrategia`] pinned by
20271        // [`placement_estrategia_accessor_is_const_fn`] above — every
20272        // one a `pub const fn`). Pin the `const`-eval posture here so
20273        // a future accidental downgrade to non-`const` (an added
20274        // runtime helper reachable only from a non-`const` context, an
20275        // `Option<u16>`-shape migration once the substrate grows
20276        // per-`:membros` heterogeneous listener ports that would
20277        // silently drop the `const` qualifier, a manual hand-rolled
20278        // shadow) trips at caixa-core build time rather than surfacing
20279        // as a downstream `const`-context regression far from the
20280        // declaration.
20281        //
20282        // Same shape as the sibling
20283        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
20284        // load-bearing witness lives in the module-scope `const fn`
20285        // wrapper `port_via_const_fn`: a body that calls
20286        // [`Entrada::port`] under a `const fn` signature is well-formed
20287        // only when the callee is itself `const fn`, side-stepping the
20288        // destructor-in-const restriction that would otherwise block a
20289        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
20290        // `String` / `Vec<String>` carriers.
20291        //
20292        // The runtime body sweeps a representative port set spanning
20293        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
20294        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
20295        // ceiling — the const-fn-wrapped call must agree with a direct
20296        // call on every fixture (a violation trips the test) and every
20297        // returned scalar must byte-equal the input `port` (a violation
20298        // means the accessor stopped being a raw field-return copy).
20299        const fn port_via_const_fn(e: &Entrada) -> u16 {
20300            e.port()
20301        }
20302        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
20303            let entrada = Entrada {
20304                host: String::new(),
20305                para: String::new(),
20306                port,
20307                paths: Vec::new(),
20308            };
20309            assert_eq!(
20310                port_via_const_fn(&entrada),
20311                entrada.port(),
20312                "const-fn-wrapped and direct dispatch on Entrada::port \
20313                 must agree for port={port}",
20314            );
20315            assert_eq!(
20316                entrada.port(),
20317                port,
20318                "Entrada::port must return the storage-side u16 verbatim \
20319                 for port={port}",
20320            );
20321        }
20322    }
20323
20324    #[test]
20325    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
20326        // Load-bearing cross-slot-partition pin closing the loop between
20327        // the substrate-lifted
20328        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
20329        // the closed-set typed enum and the actual
20330        // [`AplicacaoSpec::validate_placement`] runtime behavior across
20331        // the paired `:placement :shard-key` axis: every validated
20332        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
20333        // satisfies `placement.shard_key().is_some() ==
20334        // placement.estrategia().requires_shard_key()`. The four-cell
20335        // shape witness sweeps every combination of (variant in the
20336        // closed accept-set, `:shard-key` Some/None) and pins:
20337        //
20338        //   * variant.requires_shard_key() && shard_key.is_some() →
20339        //     validate() passes; the paired shape is the sole
20340        //     `requires_shard_key` arm-family accepted shape.
20341        //   * variant.requires_shard_key() && shard_key.is_none() →
20342        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
20343        //     the paired shape is the refused missing-key shape on
20344        //     Sharded-family arms.
20345        //   * !variant.requires_shard_key() && shard_key.is_some() →
20346        //     validate() fails with
20347        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
20348        //     is the refused declared-but-inert shape on non-Sharded-
20349        //     family arms.
20350        //   * !variant.requires_shard_key() && shard_key.is_none() →
20351        //     validate() passes; the paired shape is the sole
20352        //     non-`requires_shard_key` arm-family accepted shape.
20353        //
20354        // The compile-time-exhaustive `match p.estrategia()` dispatch at
20355        // [`AplicacaoSpec::validate_placement`] preserves its structural
20356        // arm-fan (a future arm addition still surfaces a build-time
20357        // exhaustiveness error there); this pin closes the semantic loop
20358        // between the arm-fan's shape-gate cascades and the substrate-
20359        // canonical predicate every downstream consumer of the paired
20360        // shape reads through. Fail-before-pass-after locally verified by
20361        // mutating the predicate's `Sharded => true` arm to `false` — the
20362        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
20363        // `validate() must pass` assertion; restoring passes. Same "close
20364        // the loop between the typed predicate and the runtime behavior"
20365        // discipline as the sibling
20366        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
20367        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
20368        // per-arm classifier axis.
20369        for variant in [
20370            PlacementStrategy::SingleNode,
20371            PlacementStrategy::Replicated,
20372            PlacementStrategy::Sharded,
20373        ] {
20374            for present in [false, true] {
20375                let mut spec = three_member_spec();
20376                spec.placement.estrategia = variant;
20377                spec.placement.shard_key = present.then(|| "tenantId".into());
20378                let expects_ok = variant.requires_shard_key() == present;
20379                let result = spec.validate();
20380                match (expects_ok, &result) {
20381                    (true, Ok(())) => {}
20382                    (false, Err(err)) => {
20383                        // Cross-check the refusal diagnostic names the
20384                        // right cell of the four-cell shape witness — the
20385                        // `requires_shard_key && !present` cell must trip
20386                        // [`AplicacaoError::ShardedWithoutKey`]; the
20387                        // `!requires_shard_key && present` cell must trip
20388                        // [`AplicacaoError::ShardKeyOnNonSharded`].
20389                        match (variant.requires_shard_key(), present, err) {
20390                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
20391                            (
20392                                false,
20393                                true,
20394                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
20395                            ) => {
20396                                assert_eq!(
20397                                    *e, variant,
20398                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
20399                                     the paired PlacementStrategy",
20400                                );
20401                            }
20402                            _ => panic!(
20403                                "unexpected refusal for estrategia={variant:?} \
20404                                 present={present}: {err:?}"
20405                            ),
20406                        }
20407                    }
20408                    (true, Err(err)) => panic!(
20409                        "validate() must pass for estrategia={variant:?} \
20410                         present={present} (requires_shard_key={} == present={present}), \
20411                         got {err:?}",
20412                        variant.requires_shard_key(),
20413                    ),
20414                    (false, Ok(())) => panic!(
20415                        "validate() must fail for estrategia={variant:?} \
20416                         present={present} (requires_shard_key={} != present={present})",
20417                        variant.requires_shard_key(),
20418                    ),
20419                }
20420            }
20421        }
20422    }
20423
20424    #[test]
20425    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
20426        // Pin the M3 diagnostic template routes through the typed
20427        // [`PlacementStrategy`] Display byte-string (rebound from the
20428        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
20429        // routes emitted identical bytes (the `Debug` derive on a
20430        // unit variant emits the variant name verbatim, exactly what
20431        // `as_str` returns), but the two paths were structurally
20432        // independent — a future `#[serde(rename_all = "…")]`
20433        // attribute or variant rename would coordinate the wire /
20434        // `Display` / `as_str` triple through the lifted const but
20435        // leave the `Debug` route on the compiler-derived variant name,
20436        // silently desynchronizing the diagnostic byte-string from the
20437        // wire byte-string. Rebinding the template onto `Display`
20438        // ties the diagnostic to the same lifted
20439        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
20440        // emits — drift becomes structurally impossible. Pin the
20441        // byte-string here so a future edit that reverts the template
20442        // to `{estrategia:?}` is caught at caixa-core test time, not
20443        // at consumer dispatch time.
20444        for (variant, expected_scalar) in [
20445            (
20446                PlacementStrategy::SingleNode,
20447                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
20448            ),
20449            (
20450                PlacementStrategy::Replicated,
20451                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
20452            ),
20453            (
20454                PlacementStrategy::Sharded,
20455                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
20456            ),
20457        ] {
20458            let err = AplicacaoError::PlacementWithoutClusters {
20459                estrategia: variant,
20460            };
20461            let msg = err.to_string();
20462            assert!(
20463                msg.starts_with(&format!(":placement {expected_scalar} requires")),
20464                "PlacementWithoutClusters diagnostic for {variant:?} must open \
20465                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
20466            );
20467        }
20468    }
20469
20470    #[test]
20471    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
20472        // Peer of
20473        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
20474        // on the second M3 diagnostic that carries the typed
20475        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
20476        // diagnostics now route the strategy scalar through the same
20477        // [`std::fmt::Display`] surface, tying the diagnostic
20478        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
20479        // const set the wire format also emits. The two non-Sharded
20480        // arms are exercised here (the diagnostic exists to flag a
20481        // `:shard-key` slot the current strategy will never consume);
20482        // the peer `Sharded` arm never reaches this diagnostic (the
20483        // `Sharded` strategy consumes `:shard-key` — the
20484        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
20485        // slot instead).
20486        for (variant, expected_scalar) in [
20487            (
20488                PlacementStrategy::SingleNode,
20489                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
20490            ),
20491            (
20492                PlacementStrategy::Replicated,
20493                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
20494            ),
20495        ] {
20496            let err = AplicacaoError::ShardKeyOnNonSharded {
20497                estrategia: variant,
20498                shard_key: "$tenantId".into(),
20499            };
20500            let msg = err.to_string();
20501            assert!(
20502                msg.starts_with(&format!(":placement {expected_scalar} carries")),
20503                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
20504                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
20505            );
20506        }
20507    }
20508
20509    #[test]
20510    fn placement_strategy_all_enumerates_every_variant_once() {
20511        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
20512        // exhaustive-iteration surface: every variant appears exactly
20513        // once, and the slice length matches the arm count of the
20514        // closed set. Every consumer that walks the accepted-strategy
20515        // set (a future `feira app placement --list` CLI-side surfacing,
20516        // a future M4 admission-webhook's rejection body naming the
20517        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
20518        // reverse-projection consumers that iterate the accept-set for
20519        // a "did you mean" hint) reads through this slice, so a future
20520        // variant addition (an `Anycast` mesh-anycast arm the
20521        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
20522        // grows the enum but forgets to grow [`Self::ALL`] silently
20523        // truncates every downstream consumer's accept-set at the same
20524        // pre-addition boundary — this pin fails at caixa-core build
20525        // time on the pairwise-distinct + arm-count invariants.
20526        //
20527        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
20528        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
20529        // pins on the peer closed-set typed-enum axes.
20530        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
20531        assert_eq!(
20532            all.len(),
20533            3,
20534            "PlacementStrategy::ALL must enumerate every variant of the \
20535             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
20536        );
20537        for (i, a) in all.iter().enumerate() {
20538            for (j, b) in all.iter().enumerate() {
20539                if i != j {
20540                    assert_ne!(
20541                        a, b,
20542                        "PlacementStrategy::ALL must carry every variant exactly \
20543                         once — got duplicate {a:?} at indices {i} and {j}"
20544                    );
20545                }
20546            }
20547        }
20548        for variant in [
20549            PlacementStrategy::SingleNode,
20550            PlacementStrategy::Replicated,
20551            PlacementStrategy::Sharded,
20552        ] {
20553            assert!(
20554                all.contains(&variant),
20555                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
20556                 addition that grows the enum but forgets to grow the ALL slice \
20557                 silently truncates every downstream consumer's accept-set at the \
20558                 pre-addition boundary"
20559            );
20560        }
20561    }
20562
20563    #[test]
20564    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
20565        // Fail-before-pass-after pin on the forward accept-set of the
20566        // [`PlacementStrategy::from_wire`] reverse projection: every
20567        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
20568        // constant the [`PlacementStrategy::as_str`] emitter walks
20569        // parses back to its paired variant. Any future arm addition
20570        // that grows the emitter's `as_str` match but forgets to grow
20571        // the parser's `from_str` match silently splits the two halves
20572        // of the round-trip — the wire byte-string one non-serde
20573        // consumer parses from the one the emitter wrote — with the
20574        // failure surfacing at parse time far from the rebrand commit.
20575        // Pinning the three-arm accept-set here catches the drift at
20576        // caixa-core build time.
20577        //
20578        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
20579        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
20580        // closed-set typed-enum `str → Self` axes.
20581        for (wire, expected) in [
20582            (
20583                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
20584                PlacementStrategy::SingleNode,
20585            ),
20586            (
20587                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
20588                PlacementStrategy::Replicated,
20589            ),
20590            (
20591                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
20592                PlacementStrategy::Sharded,
20593            ),
20594        ] {
20595            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
20596                panic!(
20597                    "PlacementStrategy::from_wire({wire:?}) must accept every \
20598                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
20599                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
20600                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
20601                )
20602            });
20603            assert_eq!(
20604                parsed, expected,
20605                "PlacementStrategy::from_wire({wire:?}) must return \
20606                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
20607            );
20608        }
20609    }
20610
20611    #[test]
20612    fn placement_strategy_from_wire_round_trips_through_as_str() {
20613        // Fail-before-pass-after pin on the closed round-trip between
20614        // the forward [`PlacementStrategy::as_str`] emitter and the
20615        // reverse [`PlacementStrategy::from_wire`] parser: for every
20616        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
20617        // output must return exactly the same variant. Any per-arm
20618        // divergence — a future arm added to `as_str` but not
20619        // `from_str`, an accidental copy-paste flip in one but not the
20620        // other — silently splits the emit and parse halves and the
20621        // failure surfaces at consumer parse time far from the drift
20622        // site. The `ALL`-iterating shape means a future variant
20623        // addition picks up the coverage by construction.
20624        //
20625        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
20626        // [`crate::CaixaKind::from_wire`] and the
20627        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
20628        // sibling round-trip pin on [`RateLimitUnit`].
20629        for &variant in PlacementStrategy::ALL {
20630            let wire = variant.as_str();
20631            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
20632                panic!(
20633                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
20634                     must be Some({variant:?}) — the two halves of the round-trip \
20635                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
20636                     got None on wire byte-string {wire:?}"
20637                )
20638            });
20639            assert_eq!(
20640                parsed, variant,
20641                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
20642                 must round-trip to the same variant; got {parsed:?}"
20643            );
20644        }
20645    }
20646
20647    #[test]
20648    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
20649        // Fail-before-pass-after pin on the closed-set refusal
20650        // discipline of [`PlacementStrategy::from_wire`]: every
20651        // byte-string outside the three-arm accept-set returns `None`
20652        // rather than silently collapsing onto the [`Default`]
20653        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
20654        // exercised here sweeps the load-bearing drift shapes: the
20655        // empty string (a stripped serde-attribute drift), an all-
20656        // whitespace string (the canonical text-editor accidental
20657        // padding shape), the lowercased kebab-case forms a future
20658        // `#[serde(rename_all = "kebab-case")]` attribute would emit
20659        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
20660        // coincidentally match the accepted canonical scalars, so only
20661        // `"single-node"` fires as a refusal, but pinning the case-
20662        // sensitivity of the accepted arms via the peer [`SingleNode`]
20663        // assertion in the round-trip pin makes the discipline
20664        // structurally clear), the lowercased single-word forms
20665        // (`"singlenode"`), the padded canonical scalar
20666        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
20667        // (`"Sharded\n"`), and a pointer-different `&'static str` that
20668        // happens to alias a canonical byte-string by content but not
20669        // by identity (validated implicitly by the emitter's routing
20670        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
20671        // identity a paired [`crate::assert_str_reexport_identity`] pin
20672        // in caixa-core's per-const declaration surface would catch).
20673        //
20674        // Peer of the sibling
20675        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
20676        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
20677        for bad in [
20678            "",
20679            " ",
20680            "\n",
20681            "\t",
20682            "single-node",
20683            "singlenode",
20684            "SingleNodes",
20685            "single_node",
20686            "single node",
20687            "SINGLENODE",
20688            "SingleNode ",
20689            " SingleNode",
20690            " Sharded ",
20691            "Sharded\n",
20692            "replicated ",
20693            "sharded",
20694            "REPLICATED",
20695            "Anycast",
20696            "Global",
20697            "?",
20698        ] {
20699            assert!(
20700                PlacementStrategy::from_wire(bad).is_none(),
20701                "PlacementStrategy::from_wire({bad:?}) must return None — the \
20702                 parser's accept-set is exactly the three PlacementStrategy::as_str \
20703                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
20704                 is outside that closed set"
20705            );
20706        }
20707    }
20708
20709    #[test]
20710    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
20711        // Fail-before-pass-after pin on the third path of the four-path
20712        // convergence: `from_str` (the reverse projection) inverts the
20713        // `Serialize` derive's wire byte-string on every variant.
20714        // Together with the pre-existing three-path convergence
20715        // (`Display` + `as_str` + `Serialize` all resolve to the same
20716        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
20717        // the peer
20718        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
20719        // this closes the round-trip: the wire byte-string the
20720        // `Serialize` derive emits parses back to the same variant
20721        // through `from_str`, so any future serde-attribute or variant-
20722        // rename drift on the emit half now surfaces as a matched drift
20723        // on the parse half at caixa-core build time — the two halves
20724        // migrate as a unit through the lifted consts on any future
20725        // rename, and the round-trip cannot silently split.
20726        //
20727        // Peer of the sibling
20728        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
20729        // wire-format pin — extends the three-path convergence
20730        // (`Display` + `as_str` + `Serialize`) onto the fourth path
20731        // (`from_str`), closing the `str ↔ Self` round-trip on the
20732        // M3 `:placement :estrategia` closed-set axis.
20733        for &variant in PlacementStrategy::ALL {
20734            let wire = serde_json::to_string(&variant).unwrap();
20735            let unquoted = wire
20736                .strip_prefix('"')
20737                .and_then(|s| s.strip_suffix('"'))
20738                .expect("serialized PlacementStrategy is a JSON string");
20739            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
20740                panic!(
20741                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
20742                     Serialize derive's wire byte-string for \
20743                     PlacementStrategy::{variant:?} — the four-path convergence \
20744                     (Display + as_str + Serialize + from_str) resolves through \
20745                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
20746                )
20747            });
20748            assert_eq!(
20749                parsed, variant,
20750                "PlacementStrategy::from_wire of the Serialize derive's wire \
20751                 byte-string for PlacementStrategy::{variant:?} must round-trip \
20752                 to the same variant; got {parsed:?}"
20753            );
20754        }
20755    }
20756
20757    #[test]
20758    fn rejects_zero_policy_timeout() {
20759        let mut s = three_member_spec();
20760        s.politicas.timeout = Some(Duration::ZERO);
20761        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
20762    }
20763
20764    #[test]
20765    fn rejects_zero_policy_retries() {
20766        let mut s = three_member_spec();
20767        s.politicas.retries = Some(0);
20768        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
20769    }
20770
20771    #[test]
20772    fn rejects_policy_retries_above_cap() {
20773        // The fail-before-pass-after pin: `Some(11)` is structurally
20774        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
20775        // passed validate on every pre-gate codebase because the
20776        // typed slot's only check was the zero-floor arm. The
20777        // thundering-herd amplification vector only surfaced at the
20778        // runtime substrate (Envoy / Cilium L7 retry overlay)
20779        // far from the source caixa.lisp with no field naming the
20780        // offending policy.
20781        let mut s = three_member_spec();
20782        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
20783        assert_eq!(
20784            s.validate().unwrap_err(),
20785            AplicacaoError::PolicyRetriesExceedsCap {
20786                retries: POLICY_RETRIES_MAX + 1
20787            }
20788        );
20789    }
20790
20791    #[test]
20792    fn rejects_policy_retries_far_above_cap() {
20793        // The `u32::MAX` worst case — the four-billion-retry policy
20794        // a typo (`(:retries 4294967295)`) or struct-literal
20795        // copy-paste lands in the slot. Pin the cap arm's coverage
20796        // explicitly across the full `u32` overflow so a future
20797        // relaxation that drops the upper bound surfaces here.
20798        let mut s = three_member_spec();
20799        s.politicas.retries = Some(u32::MAX);
20800        assert_eq!(
20801            s.validate().unwrap_err(),
20802            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
20803        );
20804    }
20805
20806    #[test]
20807    fn accepts_policy_retries_at_cap() {
20808        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
20809        // must validate. The cap is inclusive on the top edge,
20810        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
20811        // discipline on the sibling [`crate::LimitsSpec::memory`]
20812        // axis. Pin the boundary explicitly so a future off-by-one
20813        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
20814        // surfaces here as a test failure rather than a silent
20815        // contract narrowing.
20816        let mut s = three_member_spec();
20817        s.politicas.retries = Some(POLICY_RETRIES_MAX);
20818        s.validate()
20819            .expect("retries == POLICY_RETRIES_MAX must validate");
20820    }
20821
20822    #[test]
20823    fn accepts_policy_retries_typical_values() {
20824        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
20825        // every value in the validated set must pass. The
20826        // Envoy / Istio production-playbook recommendation band
20827        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
20828        // (`maxRetries ≤ 10`) both lie within this set.
20829        for r in 1..=POLICY_RETRIES_MAX {
20830            let mut s = three_member_spec();
20831            s.politicas.retries = Some(r);
20832            s.validate()
20833                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
20834        }
20835    }
20836
20837    #[test]
20838    fn policy_retries_zero_takes_precedence_over_cap() {
20839        // The cross-arm ordering pin: `Some(0)` is structurally
20840        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
20841        // (cap), but the zero-floor diagnostic is the more
20842        // self-locating one (it directly names the omit-axis
20843        // remediation), so the validate gate must fire on zero
20844        // first. Pin the order so a future refactor that reorders
20845        // the arms surfaces here as a test failure rather than a
20846        // silent diagnostic regression. Same shape every other
20847        // zero-then-shape ordering on this surface uses
20848        // ([`AplicacaoError::PolicyTimeoutZero`] then
20849        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
20850        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
20851        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
20852        let mut s = three_member_spec();
20853        s.politicas.retries = Some(0);
20854        assert_eq!(
20855            s.validate().unwrap_err(),
20856            AplicacaoError::PolicyRetriesZero,
20857            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
20858        );
20859    }
20860
20861    #[test]
20862    fn policy_retries_cap_diagnostic_carries_offending_value() {
20863        // The diagnostic-shape pin: the offending `u32` is carried
20864        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
20865        // variant so the surfaced error message names the value the
20866        // author wrote (`":politicas :retries (47) exceeds the
20867        // mesh-policy ceiling …"`), not just the cap. Same
20868        // self-locating diagnostic shape every other typed-cap arm
20869        // on this surface carries
20870        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
20871        // offending byte count verbatim).
20872        let mut s = three_member_spec();
20873        s.politicas.retries = Some(47);
20874        let err = s.validate().unwrap_err();
20875        assert!(
20876            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
20877            "got {err:?}"
20878        );
20879        let msg = err.to_string();
20880        assert!(
20881            msg.contains("47"),
20882            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
20883        );
20884    }
20885
20886    #[test]
20887    fn policy_retries_cap_is_aws_app_mesh_aligned() {
20888        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
20889        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
20890        // schema cap — the only upstream mesh-policy schema that
20891        // documents an explicit hard cap. Pinning the literal value
20892        // here surfaces a future drift (a relaxation to 20, a
20893        // tightening to 5) as a deliberate test edit, not a silent
20894        // contract narrowing.
20895        assert_eq!(POLICY_RETRIES_MAX, 10);
20896    }
20897
20898    #[test]
20899    fn rejects_circuit_breaker_zero_max_failures() {
20900        let mut s = three_member_spec();
20901        s.politicas.circuit_breaker = Some(CircuitBreaker {
20902            max_failures: 0,
20903            window: Duration::from_secs(60),
20904        });
20905        assert_eq!(
20906            s.validate().unwrap_err(),
20907            AplicacaoError::PolicyBreakerZeroFailures
20908        );
20909    }
20910
20911    #[test]
20912    fn rejects_circuit_breaker_max_failures_above_cap() {
20913        // The fail-before-pass-after pin: `1001` is structurally one
20914        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
20915        // silently passed validate on every pre-gate codebase
20916        // because the typed slot's only check was the zero-floor
20917        // arm. The breaker-no-op vector only surfaced at the runtime
20918        // substrate (Envoy / Cilium L7 outlier-detection overlay)
20919        // far from the source caixa.lisp with no field naming the
20920        // offending policy.
20921        let mut s = three_member_spec();
20922        s.politicas.circuit_breaker = Some(CircuitBreaker {
20923            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20924            window: Duration::from_secs(60),
20925        });
20926        assert_eq!(
20927            s.validate().unwrap_err(),
20928            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20929                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20930            }
20931        );
20932    }
20933
20934    #[test]
20935    fn rejects_circuit_breaker_max_failures_far_above_cap() {
20936        // The `u32::MAX` worst case — the four-billion-failure
20937        // threshold a typo (`(:max-failures 4294967295)`) or a
20938        // struct-literal copy-paste lands in the slot. Pin the cap
20939        // arm's coverage explicitly across the full `u32` overflow
20940        // so a future relaxation that drops the upper bound surfaces
20941        // here.
20942        let mut s = three_member_spec();
20943        s.politicas.circuit_breaker = Some(CircuitBreaker {
20944            max_failures: u32::MAX,
20945            window: Duration::from_secs(60),
20946        });
20947        assert_eq!(
20948            s.validate().unwrap_err(),
20949            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20950                max_failures: u32::MAX,
20951            }
20952        );
20953    }
20954
20955    #[test]
20956    fn accepts_circuit_breaker_max_failures_at_cap() {
20957        // The boundary value — exactly
20958        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
20959        // cap is inclusive on the top edge, matching the
20960        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
20961        // discipline on the sibling capped axes. Pin the boundary
20962        // explicitly so a future off-by-one tightening
20963        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
20964        // surfaces here as a test failure rather than a silent
20965        // contract narrowing.
20966        let mut s = three_member_spec();
20967        s.politicas.circuit_breaker = Some(CircuitBreaker {
20968            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
20969            window: Duration::from_secs(60),
20970        });
20971        s.validate()
20972            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
20973    }
20974
20975    #[test]
20976    fn accepts_circuit_breaker_max_failures_typical_values() {
20977        // The documented production-playbook band positive-control
20978        // sweep — every value Hystrix / Istio / Envoy / Polly /
20979        // Resilience4j recommend (5..=50) must pass, plus a sweep
20980        // through the hyperscale band (100, 500, 1000) the cap
20981        // accepts. Pin the inclusive validated set explicitly so a
20982        // future tightening of the ceiling surfaces here.
20983        //
20984        // Clears the fixture's `:retries` (which is `Some(3)`) so this
20985        // per-axis sweep is pure: the sibling cross-axis
20986        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
20987        // gate rejects any `max_failures <= retries` pair, so the
20988        // `max_failures = 1` boundary at the head of the sweep would
20989        // otherwise trip on the fixture-inherited retry policy rather
20990        // than the per-axis boundary this test names. Same discipline
20991        // the sibling per-axis `accepts_circuit_breaker_window_*`
20992        // sweeps take against the fixture's `:timeout` for the
20993        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
20994        // cross-axis arm.
20995        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
20996            let mut s = three_member_spec();
20997            s.politicas.retries = None;
20998            s.politicas.circuit_breaker = Some(CircuitBreaker {
20999                max_failures: n,
21000                window: Duration::from_secs(60),
21001            });
21002            s.validate()
21003                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
21004        }
21005    }
21006
21007    #[test]
21008    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
21009        // The cross-arm ordering pin: `0` is structurally outside
21010        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
21011        // (cap), but the zero-floor diagnostic is the more
21012        // self-locating one (it directly names the omit-axis
21013        // remediation), so the validate gate must fire on zero
21014        // first. Same shape every other zero-then-shape ordering on
21015        // this surface uses
21016        // ([`AplicacaoError::PolicyRetriesZero`] then
21017        // [`AplicacaoError::PolicyRetriesExceedsCap`];
21018        // [`AplicacaoError::PolicyTimeoutZero`] then
21019        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
21020        let mut s = three_member_spec();
21021        s.politicas.circuit_breaker = Some(CircuitBreaker {
21022            max_failures: 0,
21023            window: Duration::from_secs(60),
21024        });
21025        assert_eq!(
21026            s.validate().unwrap_err(),
21027            AplicacaoError::PolicyBreakerZeroFailures,
21028            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
21029        );
21030    }
21031
21032    #[test]
21033    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
21034        // The cross-arm ordering pin between the cap and the
21035        // sibling `:window` gates (zero-window, canonical-window).
21036        // A breaker carrying both an over-cap `max_failures` AND a
21037        // structurally invalid window (zero, sub-ms) must surface
21038        // the cap diagnostic first — the cap arm is wired
21039        // immediately after the zero-failure arm and strictly
21040        // before the window arms, so the offending value the
21041        // diagnostic names matches the order the author would
21042        // discover the gates by reading top-to-bottom through
21043        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
21044        // future refactor that reorders the arms surfaces here as a
21045        // test failure rather than a silent diagnostic regression.
21046        let mut s = three_member_spec();
21047        s.politicas.circuit_breaker = Some(CircuitBreaker {
21048            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
21049            window: Duration::ZERO,
21050        });
21051        assert_eq!(
21052            s.validate().unwrap_err(),
21053            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
21054                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
21055            },
21056            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
21057        );
21058    }
21059
21060    #[test]
21061    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
21062        // The diagnostic-shape pin: the offending `u32` is carried
21063        // verbatim into the
21064        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
21065        // variant so the surfaced error message names the value the
21066        // author wrote (`":politicas :circuit-breaker :max-failures
21067        // (50000) exceeds the mesh-policy ceiling …"`), not just
21068        // the cap. Same self-locating diagnostic shape every other
21069        // typed-cap arm on this surface carries
21070        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
21071        // offending retry count verbatim,
21072        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
21073        // offending byte count verbatim).
21074        let mut s = three_member_spec();
21075        s.politicas.circuit_breaker = Some(CircuitBreaker {
21076            max_failures: 50_000,
21077            window: Duration::from_secs(60),
21078        });
21079        let err = s.validate().unwrap_err();
21080        assert!(
21081            matches!(
21082                err,
21083                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
21084                    max_failures: 50_000
21085                }
21086            ),
21087            "got {err:?}"
21088        );
21089        let msg = err.to_string();
21090        assert!(
21091            msg.contains("50000"),
21092            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
21093        );
21094    }
21095
21096    #[test]
21097    fn policy_breaker_max_failures_cap_pins_canonical_value() {
21098        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
21099        // value at 1000 — an order of magnitude above every
21100        // documented production-playbook recommendation band
21101        // (Hystrix `requestVolumeThreshold` default 20, Istio
21102        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
21103        // `outlier_detection.consecutive_5xx` default 5, Polly /
21104        // Resilience4j typical 5..=50) and below the
21105        // clearly-pathological "effectively no protection" floor
21106        // (10_000, 100_000, u32::MAX). Pinning the literal value
21107        // here surfaces a future drift (a relaxation to 10_000, a
21108        // tightening to 100) as a deliberate test edit, not a
21109        // silent contract narrowing.
21110        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
21111    }
21112
21113    #[test]
21114    fn rejects_circuit_breaker_zero_window() {
21115        let mut s = three_member_spec();
21116        s.politicas.circuit_breaker = Some(CircuitBreaker {
21117            max_failures: 5,
21118            window: Duration::ZERO,
21119        });
21120        assert_eq!(
21121            s.validate().unwrap_err(),
21122            AplicacaoError::PolicyBreakerZeroWindow
21123        );
21124    }
21125
21126    #[test]
21127    fn rejects_zero_rate_limit() {
21128        let mut s = three_member_spec();
21129        s.politicas.rate_limit = Some(RateLimit {
21130            rate: 0,
21131            window: Duration::from_secs(1),
21132        });
21133        assert_eq!(
21134            s.validate().unwrap_err(),
21135            AplicacaoError::PolicyRateLimitZero
21136        );
21137    }
21138
21139    #[test]
21140    fn rejects_rate_limit_zero_window() {
21141        // `RateLimit { rate: 100, window: Duration::ZERO }` is
21142        // constructible programmatically (the typed `Duration` field
21143        // imposes no nonzero invariant) but renders through
21144        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
21145        // codec's `parse` rejects as `unknown rate-limit window unit
21146        // "0s"`. Until this validate-time gate landed the typed slot
21147        // accepted the value silently and the round-trip break only
21148        // surfaced at deserialize time (potentially in a downstream
21149        // consumer that never re-validates). Pin the rejection at
21150        // `AplicacaoSpec::validate` so the typed slot's valid set
21151        // matches the codec's round-trippable set structurally.
21152        let mut s = three_member_spec();
21153        s.politicas.rate_limit = Some(RateLimit {
21154            rate: 100,
21155            window: Duration::ZERO,
21156        });
21157        assert_eq!(
21158            s.validate().unwrap_err(),
21159            AplicacaoError::PolicyRateLimitWindowNotCanonical {
21160                window: Duration::ZERO
21161            }
21162        );
21163    }
21164
21165    #[test]
21166    fn rejects_rate_limit_arbitrary_seconds_window() {
21167        // 45 seconds is a valid `Duration` but not one of the three
21168        // canonical rate-limit windows the codec round-trips
21169        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
21170        // refuses on round-trip — same round-trip-break shape the
21171        // zero-window arm above pins, with a non-zero magnitude to
21172        // guard against a future "reject only zero" half-measure.
21173        let mut s = three_member_spec();
21174        let window = Duration::from_secs(45);
21175        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
21176        assert_eq!(
21177            s.validate().unwrap_err(),
21178            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
21179        );
21180    }
21181
21182    #[test]
21183    fn rejects_rate_limit_two_minute_window() {
21184        // 120 seconds = 2 minutes is a "looks-canonical" but
21185        // not-canonical window: it's a clean integer multiple of the
21186        // minute unit, but the codec only round-trips the
21187        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
21188        // A `Duration::from_secs(120)` window renders as `"100/120s"`
21189        // which the parser rejects. Pinning this case rules out a
21190        // future "accept any clean multiple of s/m/h" relaxation
21191        // that would silently break the codec contract.
21192        let mut s = three_member_spec();
21193        let window = Duration::from_secs(120);
21194        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
21195        assert_eq!(
21196            s.validate().unwrap_err(),
21197            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
21198        );
21199    }
21200
21201    #[test]
21202    fn rejects_rate_limit_subsecond_window() {
21203        // A sub-second window (e.g. 500ms) is a valid `Duration` but
21204        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
21205        // Pin the rejection so a future relaxation can't silently
21206        // admit fractional-second windows that the codec can't
21207        // round-trip.
21208        let mut s = three_member_spec();
21209        let window = Duration::from_millis(500);
21210        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
21211        assert_eq!(
21212            s.validate().unwrap_err(),
21213            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
21214        );
21215    }
21216
21217    #[test]
21218    fn rejects_policy_rate_limit_above_cap() {
21219        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
21220        // is structurally one past the cap and silently passed
21221        // validate on every pre-gate codebase because the typed slot's
21222        // only `rate` check was the zero-floor arm. The no-op-limiter
21223        // shape only surfaced at the runtime substrate (Envoy's
21224        // `local_rate_limit.token_bucket.max_tokens`, the future
21225        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
21226        // with no field naming the offending policy.
21227        let mut s = three_member_spec();
21228        s.politicas.rate_limit = Some(RateLimit {
21229            rate: POLICY_RATE_LIMIT_MAX + 1,
21230            window: Duration::from_secs(1),
21231        });
21232        assert_eq!(
21233            s.validate().unwrap_err(),
21234            AplicacaoError::PolicyRateLimitExceedsCap {
21235                rate: POLICY_RATE_LIMIT_MAX + 1
21236            }
21237        );
21238    }
21239
21240    #[test]
21241    fn rejects_policy_rate_limit_far_above_cap() {
21242        // The `u32::MAX` worst case — the four-billion-token rate-limit
21243        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
21244        // copy-paste lands in the slot. Pin the cap arm's coverage
21245        // explicitly across the full `u32` overflow so a future
21246        // relaxation that drops the upper bound surfaces here. Peer to
21247        // `rejects_policy_retries_far_above_cap` on the sibling
21248        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
21249        // on the sibling `:max-failures` axis.
21250        let mut s = three_member_spec();
21251        s.politicas.rate_limit = Some(RateLimit {
21252            rate: u32::MAX,
21253            window: Duration::from_secs(1),
21254        });
21255        assert_eq!(
21256            s.validate().unwrap_err(),
21257            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
21258        );
21259    }
21260
21261    #[test]
21262    fn accepts_policy_rate_limit_at_cap() {
21263        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
21264        // must validate. The cap is inclusive on the top edge, matching
21265        // every other typed upper bound in this crate
21266        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
21267        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
21268        // across all three canonical windows so a future off-by-one
21269        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
21270        // window-conditional cap surfaces here as a test failure rather
21271        // than a silent contract narrowing.
21272        for secs in [1u64, 60, 3600] {
21273            let mut s = three_member_spec();
21274            s.politicas.rate_limit = Some(RateLimit {
21275                rate: POLICY_RATE_LIMIT_MAX,
21276                window: Duration::from_secs(secs),
21277            });
21278            s.validate().unwrap_or_else(|e| {
21279                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
21280            });
21281        }
21282    }
21283
21284    #[test]
21285    fn accepts_policy_rate_limit_typical_values() {
21286        // The documented production-playbook recommendation band —
21287        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
21288        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
21289        // Enterprise ~1M per-hour. Every value in the validated set
21290        // must pass; pin the band explicitly so a future tightening
21291        // surfaces here.
21292        //
21293        // Clears the fixture's `:retries` (which is `Some(3)`) so this
21294        // per-axis sweep is pure: the sibling cross-axis
21295        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
21296        // rejects any `rate <= retries` pair, so the `rate = 1`
21297        // boundary at the head of the sweep would otherwise trip on the
21298        // fixture-inherited retry policy rather than the per-axis
21299        // boundary this test names. Same discipline the sibling per-axis
21300        // `accepts_circuit_breaker_max_failures_typical_values` sweep
21301        // takes against the fixture's `:retries` for the peer cross-axis
21302        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
21303        // arm.
21304        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
21305            for secs in [1u64, 60, 3600] {
21306                let mut s = three_member_spec();
21307                s.politicas.retries = None;
21308                s.politicas.rate_limit = Some(RateLimit {
21309                    rate,
21310                    window: Duration::from_secs(secs),
21311                });
21312                s.validate().unwrap_or_else(|e| {
21313                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
21314                });
21315            }
21316        }
21317    }
21318
21319    #[test]
21320    fn policy_rate_limit_zero_takes_precedence_over_cap() {
21321        // The cross-arm ordering pin: `rate == 0` is structurally
21322        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
21323        // (cap), but the zero-floor diagnostic is the more
21324        // self-locating one (it directly names the omit-axis
21325        // remediation). Pin the order so a future refactor that
21326        // reorders the arms surfaces here as a test failure rather
21327        // than a silent diagnostic regression. Same shape every other
21328        // zero-then-cap ordering on this surface uses
21329        // ([`AplicacaoError::PolicyRetriesZero`] then
21330        // [`AplicacaoError::PolicyRetriesExceedsCap`];
21331        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
21332        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
21333        let mut s = three_member_spec();
21334        s.politicas.rate_limit = Some(RateLimit {
21335            rate: 0,
21336            window: Duration::from_secs(1),
21337        });
21338        assert_eq!(
21339            s.validate().unwrap_err(),
21340            AplicacaoError::PolicyRateLimitZero,
21341            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
21342        );
21343    }
21344
21345    #[test]
21346    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
21347        // Two-axis-bad pin: rate above cap *and* window non-canonical.
21348        // The validate gate must fire on the rate cap first — the
21349        // amplification-shape (no-op limiter) diagnostic is the more
21350        // fundamental one; the window-canonical diagnostic is the
21351        // narrower codec-round-trip shape. Pin the ordering so a future
21352        // refactor that reorders the rate-then-window check arms
21353        // surfaces here as a test failure rather than a silent
21354        // diagnostic regression.
21355        let mut s = three_member_spec();
21356        s.politicas.rate_limit = Some(RateLimit {
21357            rate: POLICY_RATE_LIMIT_MAX + 1,
21358            window: Duration::from_secs(45),
21359        });
21360        assert_eq!(
21361            s.validate().unwrap_err(),
21362            AplicacaoError::PolicyRateLimitExceedsCap {
21363                rate: POLICY_RATE_LIMIT_MAX + 1
21364            },
21365            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
21366        );
21367    }
21368
21369    #[test]
21370    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
21371        // The diagnostic-shape pin: the offending `u32` is carried
21372        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
21373        // variant so the surfaced error message names the value the
21374        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
21375        // the mesh-policy ceiling …"`), not just the cap. Same
21376        // self-locating diagnostic shape every other typed-cap arm on
21377        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
21378        // carries the offending retries count verbatim,
21379        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
21380        // the offending failure count verbatim).
21381        let mut s = three_member_spec();
21382        s.politicas.rate_limit = Some(RateLimit {
21383            rate: 5_000_000,
21384            window: Duration::from_secs(1),
21385        });
21386        let err = s.validate().unwrap_err();
21387        assert!(
21388            matches!(
21389                err,
21390                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
21391            ),
21392            "got {err:?}"
21393        );
21394        let msg = err.to_string();
21395        assert!(
21396            msg.contains("5000000"),
21397            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
21398        );
21399    }
21400
21401    #[test]
21402    fn policy_rate_limit_cap_pins_canonical_value() {
21403        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
21404        // 1_000_000 — two-to-three orders of magnitude above every
21405        // documented production-playbook recommendation band (Envoy /
21406        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
21407        // Gateway 10_000..=100_000 per-minute) and below the
21408        // clearly-pathological "paste-from-binary blob" floor
21409        // (100_000_000, u32::MAX). Pinning the literal value here
21410        // surfaces a future drift (a relaxation to 10_000_000, a
21411        // tightening to 100_000) as a deliberate test edit, not a
21412        // silent contract narrowing.
21413        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
21414    }
21415
21416    #[test]
21417    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
21418        // Both axes are invalid here: rate == 0 *and* window is
21419        // non-canonical. The validate gate must fire on rate first
21420        // (matching the existing `rejects_zero_rate_limit` ordering),
21421        // so the existing diagnostic continues to lead with the
21422        // simpler "zero rate" framing. Pinning the order of checks
21423        // so a future refactor that reorders the arms surfaces here
21424        // as a test failure rather than a silent diagnostic
21425        // regression.
21426        let mut s = three_member_spec();
21427        s.politicas.rate_limit = Some(RateLimit {
21428            rate: 0,
21429            window: Duration::from_secs(45),
21430        });
21431        assert_eq!(
21432            s.validate().unwrap_err(),
21433            AplicacaoError::PolicyRateLimitZero
21434        );
21435    }
21436
21437    #[test]
21438    fn rate_limit_canonical_windows_validate() {
21439        // The three canonical windows the codec round-trips
21440        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
21441        // unchanged. Pin the full canonical set as a positive case
21442        // (the existing `rate_limit_round_trip_seconds` /
21443        // `rate_limit_round_trip_minutes` tests pin the
21444        // serialize-then-deserialize property at the codec layer; this
21445        // test pins the validate-side complement so a future tightening
21446        // of the canonical set — e.g. dropping `:hour` — surfaces here
21447        // as a test failure rather than a silent contract narrowing).
21448        for secs in [1u64, 60, 3600] {
21449            let mut s = three_member_spec();
21450            s.politicas.rate_limit = Some(RateLimit {
21451                rate: 100,
21452                window: Duration::from_secs(secs),
21453            });
21454            s.validate().expect("canonical window must validate");
21455        }
21456    }
21457
21458    #[test]
21459    fn rate_limit_validated_value_round_trips_through_codec() {
21460        // The structural property the validate gate enforces:
21461        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
21462        // losslessly through the `rate_limit_codec` (serialize → string
21463        // → deserialize → equal value). Pin this end-to-end so a future
21464        // change to either side (the validate gate's accepted window
21465        // set, the codec's parse/render unit set) that breaks the
21466        // alignment surfaces here. The previous-state shape (typed
21467        // slot accepts arbitrary `Duration`, codec only round-trips
21468        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
21469        // window — the validate gate now forecloses that.
21470        for secs in [1u64, 60, 3600] {
21471            let mut s = three_member_spec();
21472            s.politicas.rate_limit = Some(RateLimit {
21473                rate: 250,
21474                window: Duration::from_secs(secs),
21475            });
21476            s.validate().unwrap();
21477            let json = serde_json::to_string(&s.politicas).unwrap();
21478            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21479            assert_eq!(
21480                back.rate_limit, s.politicas.rate_limit,
21481                "every validated :rate-limit must round-trip losslessly through the codec"
21482            );
21483        }
21484    }
21485
21486    #[test]
21487    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
21488        // The hour-window canonical form (`"<n>/h"`) was missing from
21489        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
21490        // pair. Now that the validate gate pins 3600s as part of the
21491        // canonical set, pin its serialize-side render shape too so
21492        // the third leg of the s/m/h tripod is explicitly tested.
21493        let policy = MeshPolicy {
21494            rate_limit: Some(RateLimit {
21495                rate: 10000,
21496                window: Duration::from_secs(3600),
21497            }),
21498            ..Default::default()
21499        };
21500        let json = serde_json::to_string(&policy).unwrap();
21501        assert!(
21502            json.contains("\"10000/h\""),
21503            "hour-window canonical form must render with `h` suffix (got: {json})"
21504        );
21505        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21506        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
21507    }
21508
21509    #[test]
21510    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
21511        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
21512        // typed accessor's accepted-window set against the codec's
21513        // accepted set explicitly. A future addition to the codec
21514        // (e.g. accepting `:day`/`:week` as authoring units) must be
21515        // accompanied by a parallel addition here, and a regression
21516        // that drops one of the three canonical units from either
21517        // side surfaces as a test failure. The accessor is the
21518        // single source of truth for the canonical-window set —
21519        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
21520        // gate and [`rate_limit_codec::render`]'s canonical arm both
21521        // read through it — this test enshrines that its
21522        // `Duration → Option<RateLimitUnit>` projection matches the
21523        // codec's parse / render arms' accepted-window set exactly.
21524        //
21525        // Predecessor: this pin previously read the module-private
21526        // free helper `is_canonical_rate_limit_window` — a delegate
21527        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
21528        // — but the helper had no production consumers left after the
21529        // validate-gate migration onto [`RateLimit::canonical_unit`]
21530        // and was deleted; the closed-set arm-window bijection now
21531        // lives on exactly one typed dispatch on the substrate
21532        // primitive.
21533        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
21534            RateLimit { rate: 1, window }.canonical_unit()
21535        };
21536        assert!(canonical_unit(Duration::from_secs(1)).is_some());
21537        assert!(canonical_unit(Duration::from_secs(60)).is_some());
21538        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
21539        // Non-canonical windows the accessor rejects.
21540        assert!(canonical_unit(Duration::ZERO).is_none());
21541        assert!(canonical_unit(Duration::from_secs(2)).is_none());
21542        assert!(canonical_unit(Duration::from_secs(30)).is_none());
21543        assert!(canonical_unit(Duration::from_secs(120)).is_none());
21544        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
21545        // Sub-second windows: even `Duration::from_millis(1000)` is
21546        // exactly 1s and accepted; `Duration::from_millis(500)` is
21547        // sub-second and rejected.
21548        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
21549        assert!(canonical_unit(Duration::from_millis(500)).is_none());
21550        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
21551    }
21552
21553    #[test]
21554    fn rate_limit_unit_table_projections_are_mutual_inverses() {
21555        // Bidirection pin against the closed-set typed enum
21556        // [`RateLimitUnit`] arm-table (the canonical
21557        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
21558        // of the rate-limit unit surface reads from). The two
21559        // projection directions [`RateLimitUnit::from_suffix`] /
21560        // [`RateLimitUnit::window`] (str → Duration, exposed as one
21561        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
21562        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
21563        // (Duration → str, exposed as one typed dispatch through
21564        // [`RateLimit::canonical_unit`] composed with
21565        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
21566        // codec's parse arm ([`rate_limit_codec::parse`] via
21567        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
21568        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
21569        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
21570        // via [`RateLimit::canonical_unit`]) all key off. A future
21571        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
21572        // sub-second window) is one variant + one arm per method on the
21573        // closed-set enum; the compiler-enforced exhaustiveness on
21574        // every consumer's `match self` arms picks it up by
21575        // construction. This pin enshrines that both projection
21576        // directions agree on every canonical arm row and neither
21577        // leaks a spurious entry the other doesn't recognize.
21578        //
21579        // Predecessor: this test previously read the two vestigial
21580        // module-private free helpers `rate_limit_window_unit` and
21581        // `rate_limit_window_from_unit` on the `Duration → &str` and
21582        // `&str → Duration` axes; the former was deleted after its
21583        // sole production consumer ([`rate_limit_codec::render`])
21584        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
21585        // the latter is folded here into the substrate primitive
21586        // [`RateLimitUnit::window_from_suffix`] so both projection
21587        // directions live on the closed-set enum's arm-table.
21588        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
21589            let window = super::RateLimitUnit::window_from_suffix(unit)
21590                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
21591            assert_eq!(
21592                window,
21593                Duration::from_secs(secs),
21594                "unit {unit:?} must resolve to {secs}s"
21595            );
21596            let projected_suffix = RateLimit { rate: 1, window }
21597                .canonical_unit()
21598                .map(super::RateLimitUnit::as_suffix);
21599            assert_eq!(
21600                projected_suffix,
21601                Some(unit),
21602                "Duration({secs}s) must render as {unit:?} \
21603                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
21604            );
21605        }
21606        // Non-table units yield None on the `unit → Duration`
21607        // projection — a future `"d"` addition to the table would
21608        // flip this arm; today it pins the current three-row table's
21609        // rejection semantics.
21610        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
21611        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
21612        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
21613        // Non-table Durations yield None on the `Duration → unit`
21614        // projection — pins that the two projections agree on the
21615        // "not in the table" semantic too, so a drift where the
21616        // parse-side accepts a value the render-side can't emit is
21617        // a build error at the two-arm pair, not a silent codec
21618        // round-trip break.
21619        let projected_suffix = |window: Duration| -> Option<&'static str> {
21620            RateLimit { rate: 1, window }
21621                .canonical_unit()
21622                .map(super::RateLimitUnit::as_suffix)
21623        };
21624        assert!(projected_suffix(Duration::from_secs(2)).is_none());
21625        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
21626        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
21627    }
21628
21629    #[test]
21630    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
21631        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
21632        // substrate-primitive `&str → Duration` associated method the
21633        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
21634        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
21635        // to the same [`Duration`] the two-step composition
21636        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
21637        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
21638        // `"MIN"`) must project to [`None`] on both paths. A future
21639        // implementation of `window_from_suffix` that took a shortcut
21640        // through a per-suffix `match` table (bypassing the arm-table's
21641        // `Self::from_suffix` scan and the arm-table's `Self::window`
21642        // dispatch) would silently split the accept-set — the parse
21643        // arm would accept a suffix the enum's arm-table doesn't know,
21644        // or reject a suffix the enum's arm-table does; this pin
21645        // surfaces that drift at caixa-core build time rather than at a
21646        // downstream serde round-trip audit on a live `MeshPolicy`.
21647        //
21648        // Same byte-parity discipline the sibling
21649        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
21650        // pin carries on the peer `Duration → RateLimitUnit` axis via
21651        // [`RateLimit::canonical_unit`], and the peer
21652        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
21653        // carries on the bidirectional arm-table axis — extended here
21654        // onto the fifth (and last unlifted) projection axis on the
21655        // closed-set enum's arm-table.
21656        let composition = |suffix: &str| -> Option<Duration> {
21657            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
21658        };
21659        for suffix in ["s", "m", "h"] {
21660            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
21661            let via_composition = composition(suffix);
21662            assert_eq!(
21663                via_method, via_composition,
21664                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
21665                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
21666                 method must delegate to the arm-table's two typed dispatches, \
21667                 not shortcut through a per-suffix match table"
21668            );
21669            assert!(
21670                via_method.is_some(),
21671                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
21672                 RateLimitUnit::window_from_suffix"
21673            );
21674        }
21675        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
21676            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
21677            let via_composition = composition(suffix);
21678            assert_eq!(
21679                via_method, via_composition,
21680                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
21681                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
21682                 axis too"
21683            );
21684            assert!(
21685                via_method.is_none(),
21686                "non-arm suffix {suffix:?} must project to None via \
21687                 RateLimitUnit::window_from_suffix — a future extension that \
21688                 accepted this suffix without a corresponding arm on the enum \
21689                 would split the codec's parse-accepted set from the enum's \
21690                 arm-table"
21691            );
21692        }
21693        // And the codec's parse arm now reads through this method: a
21694        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
21695        // the same `Duration` the method returns for its unit, closing
21696        // the two-consumer drift surface (the codec's parse arm and the
21697        // enum's arm-table) with one typed dispatch on the substrate
21698        // primitive.
21699        for suffix in ["s", "m", "h"] {
21700            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
21701            let mp: MeshPolicy = serde_json::from_str(&wire)
21702                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
21703            let parsed = mp.rate_limit().expect("rate_limit payload present");
21704            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
21705                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
21706            assert_eq!(
21707                parsed.window(),
21708                via_method,
21709                "codec parse arm on {wire:?} must resolve the window through \
21710                 RateLimitUnit::window_from_suffix, not a divergent path"
21711            );
21712        }
21713    }
21714
21715    #[test]
21716    fn rate_limit_unit_all_enumerates_every_arm_once() {
21717        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
21718        // enumerate every arm of the closed-set enum exactly once, in
21719        // the canonical shortest-to-longest window order (Second before
21720        // Minute before Hour) — the same order the sibling
21721        // [`crate::supervisor::RestartStrategy`] /
21722        // [`crate::supervisor::RestartPolicy`] /
21723        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
21724        // typed enums carry (the arm declared first is the arm listed
21725        // first). A future variant addition that extends the enum
21726        // without appending to [`RateLimitUnit::ALL`] leaves the
21727        // exhaustive iteration surface silently short one arm — the
21728        // codec's parse arm would then reject the new suffix even
21729        // though the enum knows it. This pin closes the drift.
21730        assert_eq!(
21731            super::RateLimitUnit::ALL,
21732            &[
21733                super::RateLimitUnit::Second,
21734                super::RateLimitUnit::Minute,
21735                super::RateLimitUnit::Hour,
21736            ],
21737            "RateLimitUnit::ALL must enumerate every arm exactly once, \
21738             in canonical shortest-to-longest window order"
21739        );
21740    }
21741
21742    #[test]
21743    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
21744        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
21745        // every arm's [`RateLimitUnit::as_suffix`] output must parse
21746        // back through [`RateLimitUnit::from_suffix`] to the same
21747        // variant. A future arm addition that lands `as_suffix` but
21748        // forgets `from_suffix` (`from_suffix` iterates
21749        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
21750        // is the load-bearing carrier of the round-trip; the sibling
21751        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
21752        // the `ALL` half) trips here at caixa-core build time rather
21753        // than surfacing as a codec round-trip miss (a `render` emit
21754        // that lands a suffix the paired `parse` cannot decode).
21755        for unit in super::RateLimitUnit::ALL {
21756            let suffix = unit.as_suffix();
21757            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
21758                panic!(
21759                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
21760                     RateLimitUnit::as_suffix output — got None for {unit:?}"
21761                )
21762            });
21763            assert_eq!(
21764                parsed, *unit,
21765                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
21766                 must return RateLimitUnit::{unit:?}"
21767            );
21768        }
21769    }
21770
21771    #[test]
21772    fn rate_limit_unit_from_window_and_window_round_trip() {
21773        // Total round-trip pin on the `(from_window, window)` pair:
21774        // every arm's [`RateLimitUnit::window`] output must parse back
21775        // through [`RateLimitUnit::from_window`] to the same variant.
21776        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
21777        // on the peer `Duration` axis — the two round-trip pins
21778        // together enshrine that both projections of the typed
21779        // canonical-unit bijection are total on the arm-set.
21780        for unit in super::RateLimitUnit::ALL {
21781            let window = unit.window();
21782            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
21783                panic!(
21784                    "RateLimitUnit::from_window({window:?}) must accept every \
21785                     RateLimitUnit::window output — got None for {unit:?}"
21786                )
21787            });
21788            assert_eq!(
21789                parsed, *unit,
21790                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
21791                 must return RateLimitUnit::{unit:?}"
21792            );
21793        }
21794    }
21795
21796    #[test]
21797    fn rate_limit_unit_from_window_accessor_is_const_fn() {
21798        // Fail-before-pass-after pin: witnesses the
21799        // [`RateLimitUnit::from_window`] `const`-eval posture via a
21800        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
21801        // -> Option<RateLimitUnit>` whose body calls
21802        // `RateLimitUnit::from_window(window)`, well-formed only when
21803        // the callee is itself `const fn` (any future downgrade to
21804        // non-`const` fails at caixa-core build time with E0015 `cannot
21805        // call non-const function`, strictly stronger than a runtime
21806        // `assert!`, side-stepping the destructor-in-const restriction
21807        // that blocks direct `const _: Option<RateLimitUnit> =
21808        // RateLimitUnit::from_window(...)` items on `Duration`'s
21809        // carrier). The runtime body sweeps every closed-set
21810        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
21811        // rejection sample (`Duration::from_millis(500)` sub-second
21812        // residue) and asserts the wrapped and direct dispatches agree
21813        // — a violation means the wrapper stopped compiling under a
21814        // future `const`-posture downgrade, or the reverse resolver's
21815        // arm-set silently split from the peer `Self::window` emitter's
21816        // arm-set. Peer of the sibling
21817        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
21818        // (152c868) /
21819        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
21820        // (152c868) /
21821        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
21822        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
21823        // `const`-eval-surface pins on the peer M2 / M3 substrate-
21824        // primitive `Copy`-return accessor axes, extended onto the
21825        // reverse `Duration → RateLimitUnit` projection axis on the
21826        // M3 mesh-slot rate-limit closed-set typed enum.
21827        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
21828            super::RateLimitUnit::from_window(window)
21829        }
21830        for unit in super::RateLimitUnit::ALL {
21831            let window = unit.window();
21832            let via_wrapper = from_window_via_const_fn(window);
21833            let direct = super::RateLimitUnit::from_window(window);
21834            assert_eq!(
21835                via_wrapper, direct,
21836                "RateLimitUnit::from_window({window:?}) via const fn \
21837                 wrapper must agree with direct dispatch for {unit:?}"
21838            );
21839            assert_eq!(
21840                via_wrapper,
21841                Some(*unit),
21842                "RateLimitUnit::from_window({window:?}) via const fn \
21843                 wrapper must return Some({unit:?}) for the peer \
21844                 window() output"
21845            );
21846        }
21847        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
21848        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
21849    }
21850
21851    #[test]
21852    fn rate_limit_unit_from_window_composes_through_window_accessor() {
21853        // Composition-witness pin on the routing-through-peer discipline:
21854        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
21855        // through the peer `pub const fn` [`RateLimitUnit::window`]
21856        // canonical-`Duration` projection rather than a hand-authored
21857        // per-arm second-magnitude literal — a future arm-magnitude edit
21858        // on the sibling `window()` accessor (a `Second → 2s` typo, a
21859        // `Hour → 3599s` off-by-one) must therefore reach this reverse
21860        // resolver by construction. A pin that hard-coded the three
21861        // second-magnitudes here would silently split from the peer
21862        // emitter on any such edit; instead, this pin asserts the
21863        // composition invariant `from_window(u.window()) == Some(u)`
21864        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
21865        // arm — a violation means either the peer `Self::window`
21866        // accessor drifted (breaking every downstream consumer that
21867        // reads through it), or the reverse resolver stopped routing
21868        // through the peer (introducing a hand-authored literal that
21869        // silently disagrees with the emitter). Either failure is a
21870        // caixa-core-build-time surface, not a downstream renderer
21871        // round-trip regression.
21872        //
21873        // Peer of the sibling
21874        // [`crate::render::assert_str_reexport_identity`] discipline on
21875        // the substrate-primitive `&'static str` re-export axis and the
21876        // [`rate_limit_unit_from_window_and_window_round_trip`]
21877        // round-trip pin on the peer projection direction; extends the
21878        // one-canonical-dispatch-per-projection discipline onto the
21879        // reverse-resolver's per-arm probe axis.
21880        for unit in super::RateLimitUnit::ALL {
21881            let window_via_peer = unit.window();
21882            let resolved = super::RateLimitUnit::from_window(window_via_peer);
21883            assert_eq!(
21884                resolved,
21885                Some(*unit),
21886                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
21887                 must return Some({unit:?}) — the reverse resolver's per-arm \
21888                 probes must route through the peer `Self::window` accessor \
21889                 so any future arm-magnitude edit reaches both projection \
21890                 directions by construction"
21891            );
21892        }
21893    }
21894
21895    #[test]
21896    fn rate_limit_canonical_unit_accessor_is_const_fn() {
21897        // Fail-before-pass-after pin: witnesses the
21898        // [`RateLimit::canonical_unit`] `const`-eval posture via a
21899        // `const fn` wrapper
21900        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
21901        // whose body calls `rl.canonical_unit()`, well-formed only when
21902        // the callee is itself `const fn` (any future downgrade to
21903        // non-`const` fails at caixa-core build time with E0015 `cannot
21904        // call non-const method`). The runtime body sweeps every
21905        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
21906        // constructs a typed [`RateLimit`] with the peer `Self::window`
21907        // canonical `Duration`, then asserts both the wrapper and the
21908        // direct dispatch agree and both return `Some(unit)`. Composes
21909        // with the sibling
21910        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
21911        // typed [`RateLimit`] projection layer's `const`-posture is
21912        // load-bearing on the reverse resolver's `const`-posture, and
21913        // both must migrate together (a downgrade of either surface
21914        // splits the paired `const`-eval-surface pass on the M3
21915        // mesh-slot rate-limit `Duration ↔ Self` bijection).
21916        const fn canonical_unit_via_const_fn(
21917            rl: &super::RateLimit,
21918        ) -> Option<super::RateLimitUnit> {
21919            rl.canonical_unit()
21920        }
21921        for unit in super::RateLimitUnit::ALL {
21922            let rl = super::RateLimit {
21923                rate: 1,
21924                window: unit.window(),
21925            };
21926            let via_wrapper = canonical_unit_via_const_fn(&rl);
21927            let direct = rl.canonical_unit();
21928            assert_eq!(
21929                via_wrapper, direct,
21930                "RateLimit::canonical_unit() via const fn wrapper must \
21931                 agree with direct dispatch for {unit:?}"
21932            );
21933            assert_eq!(
21934                via_wrapper,
21935                Some(*unit),
21936                "RateLimit::canonical_unit() via const fn wrapper must \
21937                 return Some({unit:?}) for a RateLimit whose window is \
21938                 the peer RateLimitUnit::{unit:?}.window() output"
21939            );
21940        }
21941    }
21942
21943    #[test]
21944    fn rate_limit_unit_projections_are_pairwise_distinct() {
21945        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
21946        // [`RateLimitUnit::window`] outputs must be pairwise distinct
21947        // across every arm — an accidental copy-paste flip that
21948        // reroutes one arm's suffix or window to also match another
21949        // silently collapses two arms onto one, so
21950        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
21951        // (both using `find` on `Self::ALL`) would return whichever
21952        // arm the linear scan lands on first — a match-arm-ordering-
21953        // dependent outcome the closed-set typed-enum shape is meant
21954        // to rule out structurally. Peer of the sibling
21955        // `caixa_kind_wire_consts_are_pairwise_distinct` /
21956        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
21957        // other closed-set typed-enum discriminator axes.
21958        let all = super::RateLimitUnit::ALL;
21959        for (i, a) in all.iter().enumerate() {
21960            for (j, b) in all.iter().enumerate() {
21961                if i != j {
21962                    assert_ne!(
21963                        a.as_suffix(),
21964                        b.as_suffix(),
21965                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
21966                         must be distinct — a collision silently collapses two \
21967                         arms onto one under from_suffix's linear scan"
21968                    );
21969                    assert_ne!(
21970                        a.window(),
21971                        b.window(),
21972                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
21973                         must be distinct — a collision silently collapses two \
21974                         arms onto one under from_window's linear scan"
21975                    );
21976                }
21977            }
21978        }
21979    }
21980
21981    #[test]
21982    fn rate_limit_unit_display_routes_through_as_suffix() {
21983        // Route pin: [`std::fmt::Display`] must byte-equal
21984        // [`RateLimitUnit::as_suffix`] on every arm — the single
21985        // source of truth for the canonical suffix. A future
21986        // reimplementation that hand-rolls the arms instead of
21987        // delegating to [`RateLimitUnit::as_suffix`] would silently
21988        // desynchronize `format!("{u}")` from the codec's parse arm
21989        // (which uses `as_suffix` to compare suffixes). Peer of the
21990        // sibling `caixa_kind_display_routes_through_as_str_helper` /
21991        // `placement_strategy_display_routes_through_as_str_helper`
21992        // pins on the peer closed-set typed-enum Display axes.
21993        for unit in super::RateLimitUnit::ALL {
21994            assert_eq!(
21995                unit.to_string(),
21996                unit.as_suffix(),
21997                "RateLimitUnit::{unit:?} Display must route through \
21998                 as_suffix (single source of truth: the canonical suffix \
21999                 the codec parses and renders)"
22000            );
22001        }
22002    }
22003
22004    #[test]
22005    fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
22006        // Fail-before-pass-after byte-parity pin on the lifted
22007        // `impl AsRef<str> for RateLimitUnit` — asserts the standard-
22008        // library trait impl and the substrate-primitive
22009        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
22010        // resolve to the same `&str` per instance across the three-arm
22011        // closed set, so any future silent detour that routes the impl
22012        // through a divergent projection (a per-arm inline
22013        // `match self { RateLimitUnit::Second => "s", … }` re-inlining
22014        // that opens a compile-time link to the un-lifted arm-literal,
22015        // a swap onto the second-magnitude
22016        // [`super::RateLimitUnit::window`] axis that would collide the
22017        // canonical-suffix / token-bucket-refill two-axis split) trips
22018        // at caixa-core test time under `PartialEq` rather than at a
22019        // downstream `impl AsRef<str>`-bound consumer's silent split.
22020        // Sweeps every one of the three arms
22021        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
22022        // is covered only by the sibling `Display` path. Peer of the
22023        // sibling
22024        // `placement_strategy_as_ref_str_routes_through_as_str_accessor`
22025        // (d86edd2) on the M3 mesh-placement closed-set typed enum,
22026        // and the peer
22027        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
22028        // (cd2091f) pin on the top-level closed-set typed
22029        // discriminator — the pins together close the substrate
22030        // primitive's `AsRef<str>` projection axis on every closed-set
22031        // typed enum with a `fmt::Display` surface across the M2 / M3
22032        // typed slots plus the top-level `:kind` + `:versao`
22033        // primitives.
22034        for &unit in super::RateLimitUnit::ALL {
22035            assert_eq!(
22036                <super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
22037                unit.as_suffix(),
22038                "AsRef<str> impl on RateLimitUnit::{unit:?} must \
22039                 byte-equal RateLimitUnit::as_suffix on the same \
22040                 instance — divergence signals a silent detour off the \
22041                 substrate-primitive accessor"
22042            );
22043        }
22044    }
22045
22046    #[test]
22047    fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
22048        // Fail-before-pass-after byte-parity pin on the three-path
22049        // convergence discipline the M3 `:politicas :rate-limit`
22050        // canonical-unit primitive now carries on the `&str`-projection
22051        // axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
22052        // lifted impl), `format!("{v}")` (the pre-existing
22053        // [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
22054        // primitive `pub const fn` accessor both trait impls delegate
22055        // through) must resolve to the same byte-string on every
22056        // instance across the three-arm closed set. Refuses any future
22057        // divergence between the two trait impls (a stray
22058        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
22059        // rather than delegating through the shared accessor; a
22060        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
22061        // literal cascade) that would silently split the two
22062        // projection paths of the same closed-set typed enum. Mirrors
22063        // the sibling three-path-convergence discipline the peer
22064        // [`super::PlacementStrategy`] typed enum carries
22065        // (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
22066        // d86edd2), the peer [`crate::CaixaKind`] triple
22067        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
22068        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
22069        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
22070        // 16d5c7e).
22071        for &unit in super::RateLimitUnit::ALL {
22072            let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
22073            let via_display: String = format!("{unit}");
22074            let via_accessor: &str = unit.as_suffix();
22075            assert_eq!(via_as_ref, via_accessor);
22076            assert_eq!(via_display, via_accessor);
22077            assert_eq!(via_as_ref, via_display.as_str());
22078        }
22079    }
22080
22081    #[test]
22082    fn rate_limit_unit_from_window_rejects_non_canonical() {
22083        // Rejection pin on the parser's accept-set: any Duration
22084        // outside the three-arm [`RateLimitUnit::window`] output set
22085        // (sub-second residue, or a second-magnitude outside `{1, 60,
22086        // 3600}`) must return `None`. A future accidental widening of
22087        // the accept-set (rounding down sub-second residue to the
22088        // nearest arm, admitting `Duration::from_secs(30)` as a
22089        // half-minute unit) would silently drift the parser's accept-
22090        // set from the emitter's — a validated slot with a
22091        // non-canonical window would then round-trip through the
22092        // codec to a canonical form the author never wrote.
22093        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
22094        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
22095        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
22096        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
22097        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
22098        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
22099        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
22100    }
22101
22102    #[test]
22103    fn rate_limit_unit_from_suffix_rejects_unknown() {
22104        // Rejection pin on the suffix parser's accept-set: any string
22105        // outside the three-arm [`RateLimitUnit::as_suffix`] output
22106        // set must return `None`. Peer of the sibling
22107        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
22108        // the [`crate::CaixaKind`] `from_wire` accept-set.
22109        for bad in [
22110            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
22111            " s",
22112        ] {
22113            assert!(
22114                super::RateLimitUnit::from_suffix(bad).is_none(),
22115                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
22116                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
22117                 outputs"
22118            );
22119        }
22120    }
22121
22122    #[test]
22123    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
22124        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
22125        // every canonical `:window` magnitude the validate gate
22126        // accepts must map to the paired [`RateLimitUnit`] arm through
22127        // this accessor. A future validate-gate rebrand that widened
22128        // the accepted-window set without extending [`RateLimitUnit`]
22129        // would silently split the accessor's `Some`-return set from
22130        // the validate gate's accept-set — a slot that satisfies
22131        // validate would land at the accessor with `None`, so a
22132        // consumer past validate that pattern-matches on the returned
22133        // `Some` would silently miss the newly-accepted magnitude.
22134        for (window_secs, expected) in [
22135            (1u64, super::RateLimitUnit::Second),
22136            (60, super::RateLimitUnit::Minute),
22137            (3600, super::RateLimitUnit::Hour),
22138        ] {
22139            let rl = RateLimit {
22140                rate: 100,
22141                window: Duration::from_secs(window_secs),
22142            };
22143            assert_eq!(
22144                rl.canonical_unit(),
22145                Some(expected),
22146                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
22147                 must return Some({expected:?})"
22148            );
22149        }
22150        // Non-canonical windows the validate gate rejects also return
22151        // None here — the accessor is the typed-enum projection of
22152        // the sibling `is_canonical_rate_limit_window` predicate.
22153        let bad = RateLimit {
22154            rate: 100,
22155            window: Duration::from_secs(30),
22156        };
22157        assert!(
22158            bad.canonical_unit().is_none(),
22159            "RateLimit with a non-canonical window must return None from \
22160             canonical_unit — the validate gate rejects the same set"
22161        );
22162    }
22163
22164    #[test]
22165    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
22166        // Fail-before-pass-after byte-parity pin: for every canonical
22167        // window the [`rate_limit_codec::render`] arm's emitted string
22168        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
22169        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
22170        // the vestigial free helper [`rate_limit_window_unit`] (a
22171        // `find_map`-walked `Duration → &'static str` delegate) onto the
22172        // substrate primitive [`RateLimit::canonical_unit`] typed method
22173        // (a closed-set `match self.window` arm on
22174        // [`RateLimitUnit::from_window`], projected through
22175        // [`RateLimitUnit::as_suffix`] via the enum's
22176        // [`std::fmt::Display`] impl). A future re-routing of the render
22177        // arm through a differently-computed unit projection would break
22178        // this pin at build time rather than as a silent per-consumer
22179        // codec round-trip drift far from the substrate primitive edit.
22180        //
22181        // Sibling to the peer
22182        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
22183        // on the free-helper axis: that pin locks the two projections
22184        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
22185        // on the closed-set arm table; this pin locks the codec's render
22186        // arm reads through the typed accessor rather than the free
22187        // helper. Two production consumers of the canonical-unit axis
22188        // now key off one typed dispatch on the substrate primitive.
22189        for (window_secs, unit) in [
22190            (1u64, super::RateLimitUnit::Second),
22191            (60, super::RateLimitUnit::Minute),
22192            (3600, super::RateLimitUnit::Hour),
22193        ] {
22194            let rl = RateLimit {
22195                rate: 42,
22196                window: Duration::from_secs(window_secs),
22197            };
22198            let policy = MeshPolicy {
22199                rate_limit: Some(rl),
22200                ..Default::default()
22201            };
22202            let json = serde_json::to_string(&policy).unwrap();
22203            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
22204            assert!(
22205                json.contains(&expected),
22206                "rate_limit_codec::render must emit {expected} (via \
22207                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
22208                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
22209            );
22210            // And the accessor route resolves to the same typed unit
22211            // the render arm's Display formatting is asked to produce —
22212            // so a future edit that split the two paths (one through
22213            // the accessor, one through a re-introduced free helper)
22214            // trips this pin.
22215            assert_eq!(
22216                rl.canonical_unit(),
22217                Some(unit),
22218                "RateLimit::canonical_unit must return Some({unit:?}) for a \
22219                 {window_secs}s window; the codec render arm reads the same \
22220                 typed unit through this accessor"
22221            );
22222        }
22223    }
22224
22225    #[test]
22226    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
22227        // Fail-before-pass-after byte-parity pin on the validate gate's
22228        // canonical-window shape probe: every non-canonical `:window`
22229        // the free-helper predicate [`is_canonical_rate_limit_window`]
22230        // rejects is also rejected by the substrate primitive
22231        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
22232        // gate now reads through, and vice versa on the accepted set
22233        // (the three canonical windows). Locks the migration from the
22234        // free helper onto the substrate primitive: a future re-routing
22235        // of one of the two paths through a differently-computed unit
22236        // projection would silently split the codec's accepted set from
22237        // the validate gate's accepted set — a two-consumer drift the
22238        // codec-round-trip pin
22239        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
22240        // above closes on the render arm and this pin closes on the
22241        // validate arm.
22242        for canonical_window_secs in [1u64, 60, 3600] {
22243            let mut s = three_member_spec();
22244            let rl = RateLimit {
22245                rate: 100,
22246                window: Duration::from_secs(canonical_window_secs),
22247            };
22248            s.politicas.rate_limit = Some(rl);
22249            assert!(
22250                s.validate().is_ok(),
22251                "canonical {canonical_window_secs}s window must pass \
22252                 validate_politicas — the validate gate now reads \
22253                 RateLimit::canonical_unit().is_none() and the accessor \
22254                 returns Some on every canonical arm"
22255            );
22256            assert!(
22257                rl.canonical_unit().is_some(),
22258                "canonical {canonical_window_secs}s window must resolve to \
22259                 Some on RateLimit::canonical_unit — the validate gate reads \
22260                 this accessor directly"
22261            );
22262        }
22263        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
22264            let mut s = three_member_spec();
22265            let rl = RateLimit {
22266                rate: 100,
22267                window: Duration::from_secs(non_canonical_window_secs),
22268            };
22269            s.politicas.rate_limit = Some(rl);
22270            assert_eq!(
22271                s.validate().unwrap_err(),
22272                AplicacaoError::PolicyRateLimitWindowNotCanonical {
22273                    window: rl.window(),
22274                },
22275                "non-canonical {non_canonical_window_secs}s window must be \
22276                 rejected by validate_politicas — the validate gate now \
22277                 keys off RateLimit::canonical_unit().is_none()"
22278            );
22279            assert!(
22280                rl.canonical_unit().is_none(),
22281                "non-canonical {non_canonical_window_secs}s window must \
22282                 resolve to None on RateLimit::canonical_unit — the two \
22283                 paths (the free helper the validate gate previously read \
22284                 and the substrate primitive the validate gate now reads) \
22285                 must agree on the same rejected set"
22286            );
22287        }
22288        // And the substrate-primitive [`RateLimit::canonical_unit`]
22289        // accessor's accepted-window set matches the codec's parse arm's
22290        // accepted-suffix set on every canonical / non-canonical shape,
22291        // so a future silent drift between the codec's accepted set and
22292        // the validate gate's accepted set is a build error at test time
22293        // (both consumers key off the same closed-set enum's `match self`
22294        // arms). The predecessor free helper `is_canonical_rate_limit_window`
22295        // — a delegate that composed [`RateLimitUnit::from_window`] with
22296        // `.is_some()` — was deleted after this migration; the
22297        // canonical-window set now lives on exactly one typed dispatch
22298        // on the substrate primitive.
22299        for (secs, expected) in [
22300            (1u64, true),
22301            (60, true),
22302            (3600, true),
22303            (2, false),
22304            (30, false),
22305            (86_400, false),
22306        ] {
22307            let window = Duration::from_secs(secs);
22308            let rl = RateLimit { rate: 1, window };
22309            assert_eq!(
22310                rl.canonical_unit().is_some(),
22311                expected,
22312                "RateLimit::canonical_unit().is_some() must agree with the \
22313                 codec-accepted canonical-window set on {secs}s"
22314            );
22315            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
22316                1 => "s",
22317                60 => "m",
22318                3600 => "h",
22319                _ => return,
22320            })
22321            .is_some_and(|d| d == window);
22322            if expected {
22323                assert!(
22324                    suffix_from_axis,
22325                    "the codec's `&str → Duration` axis \
22326                     ({secs}s) must round-trip to the same Duration the \
22327                     substrate primitive's accessor returns Some on"
22328                );
22329            }
22330        }
22331    }
22332
22333    #[test]
22334    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
22335        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
22336        // derive: for each of the three variants, exactly one of the
22337        // generated `is_second` / `is_minute` / `is_hour` predicates
22338        // returns `true` and the other two return `false`. Peer of
22339        // the sibling
22340        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
22341        // sibling `IsVariant`-derived closed-set typed-enum pins.
22342        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
22343            (super::RateLimitUnit::Second, [true, false, false]),
22344            (super::RateLimitUnit::Minute, [false, true, false]),
22345            (super::RateLimitUnit::Hour, [false, false, true]),
22346        ];
22347        for (variant, expected) in rows {
22348            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
22349            assert_eq!(
22350                observed, expected,
22351                "RateLimitUnit::{variant:?} is_* predicates must partition \
22352                 the arm set (second, minute, hour); got {observed:?}"
22353            );
22354        }
22355    }
22356
22357    #[test]
22358    fn rejects_policy_timeout_sub_millisecond() {
22359        // A purely sub-millisecond `Duration` (`from_micros(500)` =
22360        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
22361        // arm passes — but `as_millis() == 0`, so the shared codec's
22362        // `render` arm returns the literal `"0s"`, which the
22363        // codec's `parse` arm then deserializes as `Duration::ZERO`
22364        // and the `PolicyTimeoutZero` zero-floor gate would reject
22365        // on re-validate. Pin the rejection at the typed slot's
22366        // canonical-floor gate so the round-trip break surfaces at
22367        // validate time, naming the offending `Duration`, rather
22368        // than at the next serialize → deserialize round-trip far
22369        // from the source `caixa.lisp`.
22370        let mut s = three_member_spec();
22371        let timeout = Duration::from_micros(500);
22372        s.politicas.timeout = Some(timeout);
22373        assert_eq!(
22374            s.validate().unwrap_err(),
22375            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
22376        );
22377    }
22378
22379    #[test]
22380    fn rejects_policy_timeout_non_integer_millisecond() {
22381        // A `Duration` with non-integer-millisecond residue
22382        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
22383        // through the shared codec's `render` arm as `"1ms"` (the
22384        // `as_millis()` floor truncates), which the codec's `parse`
22385        // arm then deserializes as `Duration::from_millis(1)` =
22386        // 1_000_000 ns — silently *different* from the original.
22387        // Pin the rejection so this round-trip break surfaces at
22388        // validate time, where the offending `Duration` is named,
22389        // rather than as a silent value-laundered round-trip on the
22390        // next codec round-trip.
22391        let mut s = three_member_spec();
22392        let timeout = Duration::from_micros(1500);
22393        s.politicas.timeout = Some(timeout);
22394        assert_eq!(
22395            s.validate().unwrap_err(),
22396            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
22397        );
22398    }
22399
22400    #[test]
22401    fn accepts_policy_timeout_integer_millisecond_forms() {
22402        // The codec's accepted set — integer multiples of 1ms — is
22403        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
22404        // `1h` all pass the canonical gate. Pin the canonical-forms
22405        // sweep so a future tightening of the codec's grammar (e.g.
22406        // dropping `:ms`) surfaces here as a test failure rather
22407        // than a silent contract narrowing on the typed slot.
22408        for timeout in [
22409            Duration::from_millis(1),
22410            Duration::from_millis(500),
22411            Duration::from_millis(1500),
22412            Duration::from_secs(30),
22413            Duration::from_secs(120),
22414            Duration::from_secs(3600),
22415        ] {
22416            let mut s = three_member_spec();
22417            s.politicas.timeout = Some(timeout);
22418            s.validate()
22419                .expect("integer-millisecond :timeout must validate");
22420        }
22421    }
22422
22423    #[test]
22424    fn policy_timeout_zero_takes_precedence_over_canonical() {
22425        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
22426        // pass the canonical-millisecond gate; the more self-locating
22427        // `PolicyTimeoutZero` arm (which names the omit-axis
22428        // remediation directly) must fire first. Pin the ordering so
22429        // a future refactor that reorders the arms surfaces here as a
22430        // test failure rather than a silent diagnostic regression.
22431        let mut s = three_member_spec();
22432        s.politicas.timeout = Some(Duration::ZERO);
22433        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
22434    }
22435
22436    #[test]
22437    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
22438        // The diagnostic envelope carries the offending `Duration`
22439        // verbatim so the author can grep their `caixa.lisp` for
22440        // `:timeout "<value>"` and fix it in one edit. Same
22441        // diagnostic shape every other typed-slot canonical-form
22442        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
22443        // peer `:rate-limit :window` axis.
22444        let mut s = three_member_spec();
22445        let timeout = Duration::from_nanos(1_000_001);
22446        s.politicas.timeout = Some(timeout);
22447        match s.validate().unwrap_err() {
22448            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
22449                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
22450            }
22451            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
22452        }
22453    }
22454
22455    #[test]
22456    fn rejects_policy_timeout_above_cap() {
22457        // The fail-before-pass-after pin: 3601s = 1h + 1s is
22458        // structurally one canonical-tick past the
22459        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
22460        // integer-millisecond magnitude the canonical-form arm above
22461        // accepts cleanly, that the codec round-trips losslessly as
22462        // `"3601s"`, and that silently passed validate on every
22463        // pre-gate codebase because the typed slot's only checks were
22464        // the zero-floor and canonical-form arms. The mesh-level
22465        // deadline degenerates only at the runtime substrate (Envoy
22466        // / Cilium L7 timeout overlay) far from the source
22467        // `caixa.lisp` with no field naming the offending policy.
22468        let mut s = three_member_spec();
22469        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
22470        s.politicas.timeout = Some(timeout);
22471        assert_eq!(
22472            s.validate().unwrap_err(),
22473            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
22474        );
22475    }
22476
22477    #[test]
22478    fn rejects_policy_timeout_one_millisecond_above_cap() {
22479        // Boundary case: exactly 1ms past the cap (the granularity
22480        // the canonical-form gate enforces). Catches a future
22481        // "strictly less than" half-measure and pins the diagnostic
22482        // to name the offending `Duration` verbatim. Peer of
22483        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
22484        // boundary pin on the sibling `:limits :memory` top edge.
22485        let mut s = three_member_spec();
22486        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
22487        s.politicas.timeout = Some(timeout);
22488        assert_eq!(
22489            s.validate().unwrap_err(),
22490            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
22491        );
22492    }
22493
22494    #[test]
22495    fn rejects_policy_timeout_far_above_cap() {
22496        // The "obvious authoring footgun" case: a `(:timeout "24h")`
22497        // or `(:timeout "86400s")` — values the canonical-form arm
22498        // accepts as integer-millisecond magnitudes, the codec
22499        // round-trips losslessly through serde, but the mesh-level
22500        // policy cannot honor (a 24-hour synchronous-`:contratos`
22501        // deadline is operationally indistinguishable from
22502        // omit-the-axis). Until this gate landed validate accepted
22503        // it. Pin both common above-cap values (24h, 7d) so a future
22504        // relaxation that drops the upper bound surfaces here.
22505        for timeout in [
22506            Duration::from_secs(86_400),    // 24h
22507            Duration::from_secs(604_800),   // 7d
22508            Duration::from_secs(1_000_000), // ~11.5 days
22509        ] {
22510            let mut s = three_member_spec();
22511            s.politicas.timeout = Some(timeout);
22512            assert_eq!(
22513                s.validate().unwrap_err(),
22514                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
22515            );
22516        }
22517    }
22518
22519    #[test]
22520    fn accepts_policy_timeout_at_cap() {
22521        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
22522        // must validate. The cap is inclusive on the top edge,
22523        // matching the [`POLICY_RETRIES_MAX`] /
22524        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
22525        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
22526        // sibling capped axes. Pin the boundary explicitly so a
22527        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
22528        // instead of `>`) surfaces here as a test failure rather
22529        // than a silent contract narrowing.
22530        let mut s = three_member_spec();
22531        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
22532        s.validate()
22533            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
22534    }
22535
22536    #[test]
22537    fn accepts_policy_timeout_typical_values() {
22538        // The documented production-playbook band positive-control
22539        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
22540        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
22541        // plus a sweep through the long-running-workflow band
22542        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
22543        // validated set explicitly so a future tightening of the
22544        // ceiling surfaces here as a deliberate test edit, not a
22545        // silent contract narrowing.
22546        for timeout in [
22547            Duration::from_millis(1),
22548            Duration::from_millis(500),
22549            Duration::from_secs(1),
22550            Duration::from_secs(10),
22551            Duration::from_secs(15), // Envoy default
22552            Duration::from_secs(30),
22553            Duration::from_secs(60), // AWS App Mesh typical
22554            Duration::from_secs(300),
22555            Duration::from_secs(900),
22556            Duration::from_secs(1800),
22557            Duration::from_secs(3600), // exactly 1h, the cap
22558        ] {
22559            let mut s = three_member_spec();
22560            s.politicas.timeout = Some(timeout);
22561            s.validate()
22562                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
22563        }
22564    }
22565
22566    #[test]
22567    fn policy_timeout_zero_takes_precedence_over_cap() {
22568        // The cross-arm ordering pin: `Duration::ZERO` is
22569        // structurally outside both `>= 1ms` (zero-floor) and
22570        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
22571        // diagnostic is the more self-locating one (it directly
22572        // names the omit-axis remediation), so the validate gate
22573        // must fire on zero first. Same shape every other
22574        // zero-then-shape ordering on this surface uses
22575        // ([`AplicacaoError::PolicyRetriesZero`] then
22576        // [`AplicacaoError::PolicyRetriesExceedsCap`];
22577        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
22578        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
22579        let mut s = three_member_spec();
22580        s.politicas.timeout = Some(Duration::ZERO);
22581        assert_eq!(
22582            s.validate().unwrap_err(),
22583            AplicacaoError::PolicyTimeoutZero,
22584            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
22585        );
22586    }
22587
22588    #[test]
22589    fn policy_timeout_canonical_takes_precedence_over_cap() {
22590        // The cross-arm ordering pin: a `Duration` that is *both*
22591        // sub-millisecond (non-canonical-form) and structurally
22592        // above the cap surfaces the canonical-form diagnostic
22593        // first, because the round-trip-shape break is the more
22594        // fundamental issue (the value can't even round-trip
22595        // through the codec, so the cap diagnostic naming
22596        // `1ms..=1h` would be misleading — there's no integer-ms
22597        // form of the offending value). Pin the order so a future
22598        // refactor that reorders the arms surfaces here as a test
22599        // failure rather than a silent diagnostic regression.
22600        let mut s = three_member_spec();
22601        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
22602        // *and* total magnitude above the 1h cap.
22603        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
22604        s.politicas.timeout = Some(timeout);
22605        assert_eq!(
22606            s.validate().unwrap_err(),
22607            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
22608            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
22609        );
22610    }
22611
22612    #[test]
22613    fn policy_timeout_cap_diagnostic_carries_offending_value() {
22614        // The diagnostic-shape pin: the offending `Duration` is
22615        // carried verbatim into the
22616        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
22617        // surfaced error message names the value the author wrote
22618        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
22619        // exceeds the mesh-policy ceiling …"`), not just the cap.
22620        // Same self-locating diagnostic shape every other typed-cap
22621        // arm on this surface carries
22622        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
22623        // offending retry count verbatim).
22624        let mut s = three_member_spec();
22625        let timeout = Duration::from_secs(7200); // 2h
22626        s.politicas.timeout = Some(timeout);
22627        let err = s.validate().unwrap_err();
22628        assert!(
22629            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
22630            "got {err:?}"
22631        );
22632        let msg = err.to_string();
22633        assert!(
22634            msg.contains("7200"),
22635            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
22636        );
22637    }
22638
22639    #[test]
22640    fn policy_timeout_cap_pins_canonical_value() {
22641        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
22642        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
22643        // the shared duration codec emits as a clean canonical
22644        // string (`"<n>h"`). Pinning the literal value here surfaces
22645        // a future drift (a relaxation to 24h, a tightening to 5m)
22646        // as a deliberate test edit, not a silent contract
22647        // narrowing. Same shape every other typed-cap value pin on
22648        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
22649        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
22650        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
22651    }
22652
22653    #[test]
22654    fn policy_timeout_cap_value_round_trips_through_codec() {
22655        // The codec round-trip property the cap arm preserves: the
22656        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
22657        // the shared duration codec — every value at the cap renders
22658        // to a clean canonical string (`"1h"`) and parses back to
22659        // the same `Duration`. Pin this so a future drift between
22660        // the cap constant and the codec's largest emitted unit
22661        // surfaces here. Same shape every other typed boundary pin
22662        // on this surface uses
22663        // (`wasm32_memory_cap_matches_parsed_4_gib`).
22664        let policy = MeshPolicy {
22665            timeout: Some(POLICY_TIMEOUT_MAX),
22666            ..Default::default()
22667        };
22668        let json = serde_json::to_string(&policy).unwrap();
22669        // The codec emits `"1h"` for the canonical 1-hour magnitude.
22670        assert!(
22671            json.contains("\"1h\""),
22672            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
22673        );
22674        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22675        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
22676    }
22677
22678    #[test]
22679    fn rejects_circuit_breaker_window_sub_millisecond() {
22680        // Peer of the `:timeout` sub-millisecond arm on the second
22681        // typed-`Duration` `:politicas` axis: a purely sub-ms
22682        // `Duration` (`from_micros(500)`) renders through the shared
22683        // codec as `"0s"`, which the codec parses back to
22684        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
22685        // zero-floor gate then rejects on re-validate.
22686        let mut s = three_member_spec();
22687        let window = Duration::from_micros(500);
22688        s.politicas.circuit_breaker = Some(CircuitBreaker {
22689            max_failures: 5,
22690            window,
22691        });
22692        assert_eq!(
22693            s.validate().unwrap_err(),
22694            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
22695        );
22696    }
22697
22698    #[test]
22699    fn rejects_circuit_breaker_window_non_integer_millisecond() {
22700        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
22701        // with non-integer-millisecond residue renders through the
22702        // shared codec as the truncated `"<n>ms"` form, parsing back
22703        // to a *different* `Duration` on the next round-trip.
22704        let mut s = three_member_spec();
22705        let window = Duration::from_micros(1500);
22706        s.politicas.circuit_breaker = Some(CircuitBreaker {
22707            max_failures: 5,
22708            window,
22709        });
22710        assert_eq!(
22711            s.validate().unwrap_err(),
22712            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
22713        );
22714    }
22715
22716    #[test]
22717    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
22718        // The canonical-forms sweep on the breaker axis: every
22719        // integer-ms multiple the codec round-trips losslessly
22720        // passes the canonical gate.
22721        //
22722        // Clears `:timeout` from the fixture so this per-axis sweep
22723        // covers windows shorter than the fixture's 30s timeout
22724        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
22725        // structurally-inert breaker
22726        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
22727        // the cross-axis gate at the end of
22728        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
22729        // `(:timeout, :window)` shape, not on the per-axis
22730        // integer-millisecond canonical-form shape this test pins.
22731        // The paired shape is covered by
22732        // `rejects_circuit_breaker_window_below_timeout`.
22733        for window in [
22734            Duration::from_millis(1),
22735            Duration::from_millis(500),
22736            Duration::from_millis(1500),
22737            Duration::from_secs(30),
22738            Duration::from_secs(60),
22739            Duration::from_secs(3600),
22740        ] {
22741            let mut s = three_member_spec();
22742            s.politicas.timeout = None;
22743            s.politicas.circuit_breaker = Some(CircuitBreaker {
22744                max_failures: 5,
22745                window,
22746            });
22747            s.validate()
22748                .expect("integer-millisecond :circuit-breaker :window must validate");
22749        }
22750    }
22751
22752    #[test]
22753    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
22754        // `Duration::ZERO` would pass the canonical-ms gate (the
22755        // sub-ns residue is zero) but must surface the narrower
22756        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
22757        // remediation.
22758        let mut s = three_member_spec();
22759        s.politicas.circuit_breaker = Some(CircuitBreaker {
22760            max_failures: 5,
22761            window: Duration::ZERO,
22762        });
22763        assert_eq!(
22764            s.validate().unwrap_err(),
22765            AplicacaoError::PolicyBreakerZeroWindow
22766        );
22767    }
22768
22769    #[test]
22770    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
22771        // Both axes invalid: max_failures == 0 *and* window is
22772        // sub-ms. The validate gate must fire on max_failures first
22773        // (matching the existing ordering pin
22774        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
22775        // the existing diagnostic continues to lead with the simpler
22776        // "zero threshold" framing.
22777        let mut s = three_member_spec();
22778        s.politicas.circuit_breaker = Some(CircuitBreaker {
22779            max_failures: 0,
22780            window: Duration::from_micros(500),
22781        });
22782        assert_eq!(
22783            s.validate().unwrap_err(),
22784            AplicacaoError::PolicyBreakerZeroFailures
22785        );
22786    }
22787
22788    #[test]
22789    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
22790        let mut s = three_member_spec();
22791        let window = Duration::from_nanos(60_000_000_001);
22792        s.politicas.circuit_breaker = Some(CircuitBreaker {
22793            max_failures: 5,
22794            window,
22795        });
22796        match s.validate().unwrap_err() {
22797            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
22798                assert_eq!(w, window, "diagnostic must carry the offending Duration");
22799            }
22800            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
22801        }
22802    }
22803
22804    #[test]
22805    fn rejects_circuit_breaker_window_above_cap() {
22806        // The fail-before-pass-after pin: 3601s = 1h + 1s is
22807        // structurally one canonical-tick past the
22808        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
22809        // integer-millisecond magnitude the canonical-form arm above
22810        // accepts cleanly, that the codec round-trips losslessly as
22811        // `"3601s"`, and that silently passed validate on every
22812        // pre-gate codebase because the typed slot's only checks were
22813        // the zero-floor and canonical-form arms. The
22814        // rolling-window-to-lifetime-counter degeneration surfaces
22815        // only at the runtime substrate (Envoy's outlier_detection
22816        // interval, the future CiliumClusterwideEnvoyConfig overlay)
22817        // far from the source `caixa.lisp` with no field naming the
22818        // offending policy.
22819        let mut s = three_member_spec();
22820        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
22821        s.politicas.circuit_breaker = Some(CircuitBreaker {
22822            max_failures: 5,
22823            window,
22824        });
22825        assert_eq!(
22826            s.validate().unwrap_err(),
22827            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
22828        );
22829    }
22830
22831    #[test]
22832    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
22833        // Boundary case: exactly 1ms past the cap (the granularity the
22834        // canonical-form gate enforces). Catches a future "strictly
22835        // less than" half-measure and pins the diagnostic to name the
22836        // offending `Duration` verbatim. Peer of
22837        // `rejects_policy_timeout_one_millisecond_above_cap` on the
22838        // sibling duration-typed `:politicas :timeout` top edge.
22839        let mut s = three_member_spec();
22840        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
22841        s.politicas.circuit_breaker = Some(CircuitBreaker {
22842            max_failures: 5,
22843            window,
22844        });
22845        assert_eq!(
22846            s.validate().unwrap_err(),
22847            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
22848        );
22849    }
22850
22851    #[test]
22852    fn rejects_circuit_breaker_window_far_above_cap() {
22853        // The "obvious authoring footgun" case: a `(:window "24h")` or
22854        // `(:window "86400s")` — values the canonical-form arm
22855        // accepts as integer-millisecond magnitudes, the codec
22856        // round-trips losslessly through serde, but the
22857        // rolling-window breaker contract cannot honor (a 24-hour
22858        // rolling failure window is operationally a lifetime counter).
22859        // Until this gate landed validate accepted it. Pin both common
22860        // above-cap values (24h, 7d) so a future relaxation that
22861        // drops the upper bound surfaces here.
22862        for window in [
22863            Duration::from_secs(86_400),    // 24h
22864            Duration::from_secs(604_800),   // 7d
22865            Duration::from_secs(1_000_000), // ~11.5 days
22866        ] {
22867            let mut s = three_member_spec();
22868            s.politicas.circuit_breaker = Some(CircuitBreaker {
22869                max_failures: 5,
22870                window,
22871            });
22872            assert_eq!(
22873                s.validate().unwrap_err(),
22874                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
22875            );
22876        }
22877    }
22878
22879    #[test]
22880    fn accepts_circuit_breaker_window_at_cap() {
22881        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
22882        // (1h) — must validate. The cap is inclusive on the top edge,
22883        // matching the [`POLICY_TIMEOUT_MAX`] /
22884        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
22885        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
22886        // sibling capped axes. Pin the boundary explicitly so a
22887        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
22888        // instead of `>`) surfaces here as a test failure rather than
22889        // a silent contract narrowing.
22890        let mut s = three_member_spec();
22891        s.politicas.circuit_breaker = Some(CircuitBreaker {
22892            max_failures: 5,
22893            window: POLICY_BREAKER_WINDOW_MAX,
22894        });
22895        s.validate()
22896            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
22897    }
22898
22899    #[test]
22900    fn accepts_circuit_breaker_window_typical_values() {
22901        // The documented production-playbook band positive-control
22902        // sweep — every value Hystrix / resilience4j / Istio / Envoy
22903        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
22904        // through the long-tail failure-detection band (15m, 30m, 1h)
22905        // the cap accepts. Pin the inclusive validated set explicitly
22906        // so a future tightening of the ceiling surfaces here as a
22907        // deliberate test edit, not a silent contract narrowing.
22908        //
22909        // Clears `:timeout` from the fixture so this per-axis sweep
22910        // covers windows shorter than the fixture's 30s timeout
22911        // (Hystrix's 10s default, resilience4j's 30s, and the
22912        // sub-second warm-up band) — every such value is a
22913        // structurally-inert breaker under the cross-axis gate at the
22914        // end of [`AplicacaoSpec::validate_politicas`]
22915        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
22916        // the paired `(:timeout, :window)` shape is covered by
22917        // `rejects_circuit_breaker_window_below_timeout`; this
22918        // per-axis pin ranges only over the per-axis-bracket accept set.
22919        for window in [
22920            Duration::from_millis(1),
22921            Duration::from_millis(500),
22922            Duration::from_secs(1),
22923            Duration::from_secs(10), // Hystrix / Istio / Envoy default
22924            Duration::from_secs(30),
22925            Duration::from_secs(60),  // resilience4j typical
22926            Duration::from_secs(300), // AWS App Mesh typical
22927            Duration::from_secs(900),
22928            Duration::from_secs(1800),
22929            Duration::from_secs(3600), // exactly 1h, the cap
22930        ] {
22931            let mut s = three_member_spec();
22932            s.politicas.timeout = None;
22933            s.politicas.circuit_breaker = Some(CircuitBreaker {
22934                max_failures: 5,
22935                window,
22936            });
22937            s.validate()
22938                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
22939        }
22940    }
22941
22942    #[test]
22943    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
22944        // The cross-arm ordering pin: `Duration::ZERO` is structurally
22945        // outside both `>= 1ms` (zero-floor) and
22946        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
22947        // diagnostic is the more self-locating one (it directly names
22948        // the omit-axis remediation), so the validate gate must fire
22949        // on zero first. Same shape every other zero-then-cap
22950        // ordering on this surface uses
22951        // ([`AplicacaoError::PolicyTimeoutZero`] then
22952        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
22953        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
22954        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
22955        let mut s = three_member_spec();
22956        s.politicas.circuit_breaker = Some(CircuitBreaker {
22957            max_failures: 5,
22958            window: Duration::ZERO,
22959        });
22960        assert_eq!(
22961            s.validate().unwrap_err(),
22962            AplicacaoError::PolicyBreakerZeroWindow,
22963            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
22964        );
22965    }
22966
22967    #[test]
22968    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
22969        // The cross-arm ordering pin: a `Duration` that is *both*
22970        // sub-millisecond (non-canonical-form) and structurally above
22971        // the cap surfaces the canonical-form diagnostic first,
22972        // because the round-trip-shape break is the more fundamental
22973        // issue (the value can't even round-trip through the codec, so
22974        // the cap diagnostic naming `1ms..=1h` would be misleading —
22975        // there's no integer-ms form of the offending value). Pin the
22976        // order so a future refactor that reorders the arms surfaces
22977        // here as a test failure rather than a silent diagnostic
22978        // regression. Peer of
22979        // `policy_timeout_canonical_takes_precedence_over_cap` on the
22980        // sibling duration-typed `:politicas :timeout` axis.
22981        let mut s = three_member_spec();
22982        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
22983        s.politicas.circuit_breaker = Some(CircuitBreaker {
22984            max_failures: 5,
22985            window,
22986        });
22987        assert_eq!(
22988            s.validate().unwrap_err(),
22989            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
22990            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
22991        );
22992    }
22993
22994    #[test]
22995    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
22996        // The cross-arm ordering pin between the two breaker axes: a
22997        // `CircuitBreaker` whose *both* `max_failures` is above its
22998        // cap *and* `window` is above its cap surfaces the
22999        // max-failures cap diagnostic first, because the validate
23000        // gate visits the failures arm before the window arm. Pin the
23001        // order so a future refactor that reorders the breaker arms
23002        // surfaces here.
23003        let mut s = three_member_spec();
23004        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
23005        s.politicas.circuit_breaker = Some(CircuitBreaker {
23006            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
23007            window,
23008        });
23009        assert_eq!(
23010            s.validate().unwrap_err(),
23011            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
23012                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
23013            },
23014            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
23015        );
23016    }
23017
23018    #[test]
23019    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
23020        // The diagnostic-shape pin: the offending `Duration` is
23021        // carried verbatim into the
23022        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
23023        // the surfaced error message names the value the author wrote
23024        // (`":politicas :circuit-breaker :window (Duration { secs:
23025        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
23026        // just the cap. Same self-locating diagnostic shape every
23027        // other typed-cap arm on this surface carries
23028        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
23029        // offending `Duration` verbatim).
23030        let mut s = three_member_spec();
23031        let window = Duration::from_secs(7200); // 2h
23032        s.politicas.circuit_breaker = Some(CircuitBreaker {
23033            max_failures: 5,
23034            window,
23035        });
23036        let err = s.validate().unwrap_err();
23037        assert!(
23038            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
23039            "got {err:?}"
23040        );
23041        let msg = err.to_string();
23042        assert!(
23043            msg.contains("7200"),
23044            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
23045        );
23046    }
23047
23048    #[test]
23049    fn circuit_breaker_window_cap_pins_canonical_value() {
23050        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
23051        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
23052        // shared duration codec emits as a clean canonical string
23053        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
23054        // the sibling duration-typed `:politicas :timeout` axis (the
23055        // two duration-typed `:politicas` axes share a uniform top
23056        // edge). Pinning the literal value here surfaces a future
23057        // drift (a relaxation to 24h, a tightening to 5m) as a
23058        // deliberate test edit, not a silent contract narrowing. Same
23059        // shape every other typed-cap value pin on this surface uses
23060        // (`policy_timeout_cap_pins_canonical_value`).
23061        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
23062        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
23063        assert_eq!(
23064            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
23065            "the two duration-typed `:politicas` caps share the same top edge"
23066        );
23067    }
23068
23069    #[test]
23070    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
23071        // The codec round-trip property the cap arm preserves: the
23072        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
23073        // through the shared duration codec — every value at the cap
23074        // renders to a clean canonical string (`"1h"`) and parses back
23075        // to the same `Duration`. Pin this so a future drift between
23076        // the cap constant and the codec's largest emitted unit
23077        // surfaces here. Same shape every other typed boundary pin on
23078        // this surface uses
23079        // (`policy_timeout_cap_value_round_trips_through_codec`).
23080        let policy = MeshPolicy {
23081            circuit_breaker: Some(CircuitBreaker {
23082                max_failures: 5,
23083                window: POLICY_BREAKER_WINDOW_MAX,
23084            }),
23085            ..Default::default()
23086        };
23087        let json = serde_json::to_string(&policy).unwrap();
23088        // The codec emits `"1h"` for the canonical 1-hour magnitude.
23089        assert!(
23090            json.contains("\"1h\""),
23091            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
23092        );
23093        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23094        assert_eq!(
23095            back.circuit_breaker.unwrap().window,
23096            POLICY_BREAKER_WINDOW_MAX
23097        );
23098    }
23099
23100    #[test]
23101    fn is_integer_millisecond_duration_predicate_tracks_codec() {
23102        // Pin the predicate's accepted set against the codec's
23103        // accepted set explicitly. The codec parses
23104        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
23105        // accepted value is an integer-millisecond multiple — so the
23106        // predicate must accept exactly that set. Same shape every
23107        // other predicate-on-the-typed-slot helper carries
23108        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
23109        // Read directly from the codec-owned predicate — the crate's
23110        // single source of truth every typed-`Duration` axis now routes
23111        // through via
23112        // [`crate::render::require_positive_canonical_bounded_duration`].
23113        use super::supervisor::duration_codec::is_integer_millisecond_duration;
23114        assert!(is_integer_millisecond_duration(Duration::ZERO));
23115        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
23116        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
23117        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
23118        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
23119        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
23120        // Non-integer-millisecond residue: rejected.
23121        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
23122        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
23123        assert!(!is_integer_millisecond_duration(Duration::from_micros(
23124            1500
23125        )));
23126        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
23127        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
23128            999_999
23129        )));
23130        // The 1-ns-past-1ms boundary: rejected (no longer a clean
23131        // integer-millisecond multiple).
23132        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
23133            1_000_001
23134        )));
23135    }
23136
23137    #[test]
23138    fn policy_timeout_validated_value_round_trips_through_codec() {
23139        // The structural property the canonical-ms gate enforces:
23140        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
23141        // round-trips losslessly through the shared `duration_codec`
23142        // (serialize → string → deserialize → equal value). Pin this
23143        // end-to-end so a future change to either side (the validate
23144        // gate's accepted granularity, the codec's parse/render unit
23145        // set) that breaks the alignment surfaces here. The
23146        // previous-state shape (typed slot accepts arbitrary
23147        // `Duration`, codec only round-trips integer-ms) would fail
23148        // this test for any `Duration::from_micros(1500)` timeout —
23149        // the validate gate now forecloses that.
23150        for timeout in [
23151            Duration::from_millis(1),
23152            Duration::from_millis(1500),
23153            Duration::from_secs(30),
23154            Duration::from_secs(3600),
23155        ] {
23156            let mut s = three_member_spec();
23157            s.politicas.timeout = Some(timeout);
23158            s.validate().unwrap();
23159            let json = serde_json::to_string(&s.politicas).unwrap();
23160            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23161            assert_eq!(
23162                back.timeout, s.politicas.timeout,
23163                "every validated :timeout must round-trip losslessly through the codec"
23164            );
23165        }
23166    }
23167
23168    #[test]
23169    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
23170        // Peer of the `:timeout` round-trip property on the breaker
23171        // axis.
23172        //
23173        // Clears `:timeout` from the fixture so the round-trip pin
23174        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
23175        // cross-axis gate would otherwise reject as structurally-inert
23176        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
23177        // the paired `(:timeout, :window)` cross-axis relation is
23178        // pinned separately by
23179        // `rejects_circuit_breaker_window_below_timeout`, and this
23180        // property is a pure serde-codec round-trip on the per-axis
23181        // slot.
23182        for window in [
23183            Duration::from_millis(1),
23184            Duration::from_millis(1500),
23185            Duration::from_secs(30),
23186            Duration::from_secs(3600),
23187        ] {
23188            let mut s = three_member_spec();
23189            s.politicas.timeout = None;
23190            s.politicas.circuit_breaker = Some(CircuitBreaker {
23191                max_failures: 5,
23192                window,
23193            });
23194            s.validate().unwrap();
23195            let json = serde_json::to_string(&s.politicas).unwrap();
23196            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23197            assert_eq!(
23198                back.circuit_breaker.unwrap().window,
23199                window,
23200                "every validated :circuit-breaker :window must round-trip losslessly"
23201            );
23202        }
23203    }
23204
23205    #[test]
23206    fn rejects_circuit_breaker_window_below_timeout() {
23207        // The fail-before-pass-after pin on the cross-axis
23208        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
23209        // is individually well-formed under its own per-axis bracket
23210        // (both integer-millisecond, both above the zero floor, both
23211        // below the cap), but the pair is a structurally-inert
23212        // breaker: a call dispatched at t=0 is declared failed at
23213        // t=30s, by which point the 10s rolling window open at
23214        // dispatch has already rolled twice, so no window can hold
23215        // a timeout-derived failure however high the call volume.
23216        //
23217        // Envoy's `outlier_detection.interval` against the per-route
23218        // request timeout carries the identical relation; Hystrix
23219        // ships the canonical ratio in its defaults (10s window
23220        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
23221        //
23222        // Pin both the diagnostic arm and the payload values so a
23223        // future re-shape of the arm surfaces here as a deliberate
23224        // test edit.
23225        let mut s = three_member_spec();
23226        s.politicas.timeout = Some(Duration::from_secs(30));
23227        s.politicas.circuit_breaker = Some(CircuitBreaker {
23228            max_failures: 5,
23229            window: Duration::from_secs(10),
23230        });
23231        assert_eq!(
23232            s.validate().unwrap_err(),
23233            AplicacaoError::PolicyBreakerWindowBelowTimeout {
23234                window: Duration::from_secs(10),
23235                timeout: Duration::from_secs(30),
23236            }
23237        );
23238    }
23239
23240    #[test]
23241    fn accepts_circuit_breaker_window_equal_to_timeout() {
23242        // Boundary pin: `:window == :timeout` is the smallest window
23243        // that structurally admits at least one full timeout-derived
23244        // failure before the rolling interval closes (the invariant
23245        // is `:window >= :timeout`, not strict inequality). Catches
23246        // a future off-by-one tightening that would drift the accept
23247        // set away from the codified [`MeshPolicy::breaker_window_
23248        // observes_timeout`] predicate.
23249        let mut s = three_member_spec();
23250        s.politicas.timeout = Some(Duration::from_secs(30));
23251        s.politicas.circuit_breaker = Some(CircuitBreaker {
23252            max_failures: 5,
23253            window: Duration::from_secs(30),
23254        });
23255        s.validate()
23256            .expect("window == timeout is the boundary accept case");
23257    }
23258
23259    #[test]
23260    fn accepts_circuit_breaker_window_above_timeout() {
23261        // Positive-control sweep across the production-playbook band —
23262        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
23263        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
23264        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
23265        // playbook recommends must validate under the cross-axis gate.
23266        for (timeout, window) in [
23267            (Duration::from_secs(1), Duration::from_secs(10)),
23268            (Duration::from_secs(5), Duration::from_secs(30)),
23269            (Duration::from_secs(10), Duration::from_secs(60)),
23270            (Duration::from_secs(30), Duration::from_secs(300)),
23271            (Duration::from_secs(60), Duration::from_secs(300)),
23272        ] {
23273            let mut s = three_member_spec();
23274            s.politicas.timeout = Some(timeout);
23275            s.politicas.circuit_breaker = Some(CircuitBreaker {
23276                max_failures: 5,
23277                window,
23278            });
23279            s.validate().unwrap_or_else(|e| {
23280                panic!(
23281                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
23282                     validate; got {e:?}"
23283                )
23284            });
23285        }
23286    }
23287
23288    #[test]
23289    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
23290        // Off-by-one boundary pin: a window exactly 1ms shy of the
23291        // timeout is still structurally inert under the invariant
23292        // (the dispatch-to-report lag is `timeout`, so the window
23293        // must span at least one such lag). Catches a future
23294        // strict-inequality relaxation that would silently drift
23295        // the accept boundary.
23296        let timeout = Duration::from_secs(30);
23297        let window = Duration::from_millis(29_999);
23298        let mut s = three_member_spec();
23299        s.politicas.timeout = Some(timeout);
23300        s.politicas.circuit_breaker = Some(CircuitBreaker {
23301            max_failures: 5,
23302            window,
23303        });
23304        assert_eq!(
23305            s.validate().unwrap_err(),
23306            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
23307        );
23308    }
23309
23310    #[test]
23311    fn cross_axis_gate_vacuous_when_timeout_absent() {
23312        // The predicate is vacuously `true` when `:timeout` is None —
23313        // a `:circuit-breaker` alone declares no relation to a
23314        // substrate-imposed deadline (the failure signal reaches the
23315        // breaker from the transport's own error surface, so no
23316        // dispatch-to-report lag is knowable at author time). Pin so
23317        // a future tightening that made the gate opinionated on
23318        // half-declared pairs surfaces here.
23319        let mut s = three_member_spec();
23320        s.politicas.timeout = None;
23321        s.politicas.circuit_breaker = Some(CircuitBreaker {
23322            max_failures: 5,
23323            window: Duration::from_millis(1),
23324        });
23325        s.validate().expect(
23326            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
23327        );
23328    }
23329
23330    #[test]
23331    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
23332        // Peer of the sibling `:timeout`-absent case: a `:timeout`
23333        // without a `:circuit-breaker` declares a per-call deadline
23334        // without any rolling-window failure accounting, so the pair
23335        // is undeclared and the cross-axis gate has nothing to check.
23336        let mut s = three_member_spec();
23337        s.politicas.timeout = Some(Duration::from_secs(3600));
23338        s.politicas.circuit_breaker = None;
23339        s.validate().expect(
23340            "cross-axis gate must be vacuous when :circuit-breaker is None, \
23341             however large :timeout is",
23342        );
23343    }
23344
23345    #[test]
23346    fn cross_axis_gate_runs_after_per_axis_brackets() {
23347        // Ordering pin: a pair whose window is *both* zero-floor-
23348        // violating and structurally below the timeout must surface
23349        // the per-axis zero-floor arm first — the zero-floor
23350        // diagnostic is more self-locating (its omit-axis remediation
23351        // is directly named), where the cross-axis arm would send the
23352        // author to reconcile two values one of which is not a
23353        // meaningful window at all. Same ordering discipline every
23354        // per-axis bracket carries internally (zero-floor before
23355        // canonical-form before cap).
23356        let mut s = three_member_spec();
23357        s.politicas.timeout = Some(Duration::from_secs(30));
23358        s.politicas.circuit_breaker = Some(CircuitBreaker {
23359            max_failures: 5,
23360            window: Duration::ZERO,
23361        });
23362        assert_eq!(
23363            s.validate().unwrap_err(),
23364            AplicacaoError::PolicyBreakerZeroWindow,
23365            "per-axis zero-floor arm must fire before the cross-axis gate"
23366        );
23367    }
23368
23369    #[test]
23370    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
23371        // Equivalence pin: the substrate-canonical
23372        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
23373        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
23374        // arm must discriminate the same set on every pair covered
23375        // by their shared invariant. A future refactor of either
23376        // side that breaks the equivalence trips here rather than as
23377        // a divergence between the predicate's Boolean answer and
23378        // the validate gate's Ok/Err arm — the same
23379        // predicate-vs-gate coherence discipline the peer
23380        // [`PlacementStrategy::is_shard_keyed`] predicate carries
23381        // against `AplicacaoSpec::validate_placement`. The sweep
23382        // covers both arms of the invariant (below, equal, above)
23383        // and both vacuous arms (None `:timeout`, None
23384        // `:circuit-breaker`), so the equivalence holds
23385        // exhaustively over the axis-covered accept and reject sets.
23386        let cases: &[(Option<Duration>, Option<Duration>)] = &[
23387            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
23388            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
23389            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
23390            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
23391            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
23392            (None, Some(Duration::from_secs(1))),
23393            (Some(Duration::from_secs(30)), None),
23394            (None, None),
23395        ];
23396        for (timeout, window) in cases.iter().copied() {
23397            let politicas = MeshPolicy {
23398                timeout,
23399                circuit_breaker: window.map(|w| CircuitBreaker {
23400                    max_failures: 5,
23401                    window: w,
23402                }),
23403                ..Default::default()
23404            };
23405            let predicate = politicas.breaker_window_observes_timeout();
23406
23407            let mut s = three_member_spec();
23408            s.politicas = politicas.clone();
23409            let gate_ok = !matches!(
23410                s.validate(),
23411                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
23412            );
23413
23414            assert_eq!(
23415                predicate, gate_ok,
23416                "predicate must agree with validate arm on pair \
23417                 (timeout={timeout:?}, window={window:?})"
23418            );
23419        }
23420    }
23421
23422    #[test]
23423    fn rejects_rate_limit_starves_circuit_breaker() {
23424        // The fail-before-pass-after pin on the cross-axis
23425        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
23426        // individually well-formed under its own per-axis bracket
23427        // (both above the zero floor, both below the cap, rate-limit
23428        // window canonical), but the pair is a structurally-inert
23429        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
23430        // calls per rolling breaker window, so no window can
23431        // accumulate five failures however catastrophic the upstream
23432        // failure rate.
23433        //
23434        // Envoy's `outlier_detection.consecutive_5xx` paired against
23435        // `local_rate_limit.token_bucket.max_tokens` /
23436        // `fill_interval` carries the identical relation; every
23437        // production playbook that pairs the two axes (Envoy, Istio,
23438        // AWS App Mesh, Kong) sizes the rate at or above the
23439        // breaker's minimum-request-volume threshold for exactly this
23440        // reason.
23441        //
23442        // Pin both the diagnostic arm and the payload values so a
23443        // future re-shape of the arm surfaces here as a deliberate
23444        // test edit. Clears `:timeout` so the sibling
23445        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
23446        // does not fire first on the ordering-precedent it holds
23447        // over this arm.
23448        let mut s = three_member_spec();
23449        s.politicas.timeout = None;
23450        s.politicas.circuit_breaker = Some(CircuitBreaker {
23451            max_failures: 5,
23452            window: Duration::from_secs(10),
23453        });
23454        s.politicas.rate_limit = Some(RateLimit {
23455            rate: 1,
23456            window: Duration::from_secs(3600),
23457        });
23458        assert_eq!(
23459            s.validate().unwrap_err(),
23460            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23461                rate: 1,
23462                rl_window: Duration::from_secs(3600),
23463                max_failures: 5,
23464                cb_window: Duration::from_secs(10),
23465            }
23466        );
23467    }
23468
23469    #[test]
23470    fn accepts_rate_limit_can_trip_circuit_breaker() {
23471        // Positive-control sweep across the production-playbook band
23472        // — every pair a real playbook recommends where the rate
23473        // clearly admits enough calls per breaker window to reach
23474        // `:max-failures` must validate. Envoy default 5 failures
23475        // in 10s with 100/s (1000 calls / window, 200× the threshold),
23476        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
23477        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
23478        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
23479        // the sibling cross-axis arm is vacuous on this sweep.
23480        for (rate, rl_window, max_failures, cb_window) in [
23481            (
23482                100u32,
23483                Duration::from_secs(1),
23484                5u32,
23485                Duration::from_secs(10),
23486            ),
23487            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
23488            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
23489            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
23490            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
23491        ] {
23492            let mut s = three_member_spec();
23493            s.politicas.timeout = None;
23494            s.politicas.circuit_breaker = Some(CircuitBreaker {
23495                max_failures,
23496                window: cb_window,
23497            });
23498            s.politicas.rate_limit = Some(RateLimit {
23499                rate,
23500                window: rl_window,
23501            });
23502            s.validate().unwrap_or_else(|e| {
23503                panic!(
23504                    "production-playbook pair rate={rate}/{rl_window:?} \
23505                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
23506                )
23507            });
23508        }
23509    }
23510
23511    #[test]
23512    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
23513        // Boundary pin: `rate × cb_window == max_failures × rl_window`
23514        // is the smallest bucket capacity that structurally admits
23515        // exactly `max_failures` calls per rolling breaker window
23516        // (the invariant is `≥`, not strict inequality). Catches a
23517        // future off-by-one tightening to strict inequality that
23518        // would drift the accept set away from the codified
23519        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
23520        // 5 calls/s over a 1s breaker window == 5 max_failures.
23521        let mut s = three_member_spec();
23522        s.politicas.timeout = None;
23523        s.politicas.circuit_breaker = Some(CircuitBreaker {
23524            max_failures: 5,
23525            window: Duration::from_secs(1),
23526        });
23527        s.politicas.rate_limit = Some(RateLimit {
23528            rate: 5,
23529            window: Duration::from_secs(1),
23530        });
23531        s.validate()
23532            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
23533    }
23534
23535    #[test]
23536    fn rejects_rate_limit_one_call_short_per_cb_window() {
23537        // Off-by-one boundary pin: exactly one call short of the trip
23538        // threshold per breaker window is still structurally inert
23539        // (the invariant is `≥`, so `<` refuses even a one-call
23540        // shortfall). 4 calls/s over a 1s window == 4 admissible
23541        // failures, one shy of the 5-`max_failures` threshold.
23542        // Catches a future strict-inequality relaxation that would
23543        // silently drift the accept boundary.
23544        let mut s = three_member_spec();
23545        s.politicas.timeout = None;
23546        s.politicas.circuit_breaker = Some(CircuitBreaker {
23547            max_failures: 5,
23548            window: Duration::from_secs(1),
23549        });
23550        s.politicas.rate_limit = Some(RateLimit {
23551            rate: 4,
23552            window: Duration::from_secs(1),
23553        });
23554        assert_eq!(
23555            s.validate().unwrap_err(),
23556            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23557                rate: 4,
23558                rl_window: Duration::from_secs(1),
23559                max_failures: 5,
23560                cb_window: Duration::from_secs(1),
23561            }
23562        );
23563    }
23564
23565    #[test]
23566    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
23567        // The predicate is vacuously `true` when `:rate-limit` is
23568        // None — a `:circuit-breaker` alone declares no relation to
23569        // a substrate-imposed call rate (the failure signal reaches
23570        // the breaker from the transport's own error surface, at
23571        // whatever rate upstream callers push traffic). Pin so a
23572        // future tightening that made the gate opinionated on
23573        // half-declared pairs surfaces here.
23574        let mut s = three_member_spec();
23575        s.politicas.timeout = None;
23576        s.politicas.circuit_breaker = Some(CircuitBreaker {
23577            max_failures: 1000,
23578            window: Duration::from_millis(1),
23579        });
23580        s.politicas.rate_limit = None;
23581        s.validate().expect(
23582            "cross-axis starve gate must be vacuous when :rate-limit is None, \
23583             however high :max-failures and however small :window are",
23584        );
23585    }
23586
23587    #[test]
23588    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
23589        // Peer of the sibling `:rate-limit`-absent case: a
23590        // `:rate-limit` without a `:circuit-breaker` declares a
23591        // per-edge token-bucket rate without any failure counter to
23592        // starve, so the pair is undeclared and the cross-axis gate
23593        // has nothing to check.
23594        //
23595        // Also clears the fixture's `:retries` (which is `Some(3)`) so
23596        // the sibling cross-axis
23597        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
23598        // (which reasons across the paired `(:retries, :rate-limit)`
23599        // pair independent of `:circuit-breaker`) is vacuous on this
23600        // pin — this test names the *starve* arm's vacuity on the
23601        // `:circuit-breaker`-absent case, not the burst arm's.
23602        let mut s = three_member_spec();
23603        s.politicas.timeout = None;
23604        s.politicas.retries = None;
23605        s.politicas.circuit_breaker = None;
23606        s.politicas.rate_limit = Some(RateLimit {
23607            rate: 1,
23608            window: Duration::from_secs(3600),
23609        });
23610        s.validate().expect(
23611            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
23612             however low :rate is",
23613        );
23614    }
23615
23616    #[test]
23617    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
23618        // Ordering pin: a pair whose rate is *both* zero-floor-
23619        // violating and structurally below the trip threshold must
23620        // surface the per-axis zero-floor arm first — the zero-floor
23621        // diagnostic is more self-locating (its omit-axis remediation
23622        // is directly named), where the cross-axis arm would send the
23623        // author to reconcile four values one of which is not a
23624        // meaningful rate at all. Same ordering discipline every
23625        // per-axis bracket carries internally (zero-floor before
23626        // canonical-form before cap), and the sibling cross-axis
23627        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
23628        // ordering pins on the `(:timeout, :window)` pair.
23629        let mut s = three_member_spec();
23630        s.politicas.timeout = None;
23631        s.politicas.circuit_breaker = Some(CircuitBreaker {
23632            max_failures: 5,
23633            window: Duration::from_secs(10),
23634        });
23635        s.politicas.rate_limit = Some(RateLimit {
23636            rate: 0,
23637            window: Duration::from_secs(1),
23638        });
23639        assert_eq!(
23640            s.validate().unwrap_err(),
23641            AplicacaoError::PolicyRateLimitZero,
23642            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
23643        );
23644    }
23645
23646    #[test]
23647    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
23648        // Cross-axis ordering pin: a `:politicas` whose axes trip
23649        // BOTH cross-axis arms — `:window < :timeout` (the sibling
23650        // `PolicyBreakerWindowBelowTimeout` invariant) AND
23651        // `:rate-limit` starves the breaker within `:window` (this
23652        // arm) — must surface the timeout-relation diagnostic first.
23653        // The timeout arm is the per-call-deadline invariant every
23654        // synchronous edge carries whether or not `:rate-limit` is
23655        // declared, so its diagnostic is more self-locating; the
23656        // starve arm needs the reader to reason across three axes,
23657        // where the timeout arm names only two.
23658        //
23659        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
23660        // pair trips both: the window is below the timeout, and the
23661        // rate (1 call/hour) admits far fewer than 5 calls per 10s
23662        // breaker window.
23663        let mut s = three_member_spec();
23664        s.politicas.timeout = Some(Duration::from_secs(30));
23665        s.politicas.circuit_breaker = Some(CircuitBreaker {
23666            max_failures: 5,
23667            window: Duration::from_secs(10),
23668        });
23669        s.politicas.rate_limit = Some(RateLimit {
23670            rate: 1,
23671            window: Duration::from_secs(3600),
23672        });
23673        assert_eq!(
23674            s.validate().unwrap_err(),
23675            AplicacaoError::PolicyBreakerWindowBelowTimeout {
23676                window: Duration::from_secs(10),
23677                timeout: Duration::from_secs(30),
23678            },
23679            "sibling :window<:timeout cross-axis arm must fire before the \
23680             starve arm when both apply"
23681        );
23682    }
23683
23684    #[test]
23685    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
23686        // Equivalence pin: the substrate-canonical
23687        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
23688        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
23689        // arm must discriminate the same set on every pair covered
23690        // by their shared invariant. A future refactor of either
23691        // side that breaks the equivalence trips here rather than as
23692        // a divergence between the predicate's Boolean answer and
23693        // the validate gate's Ok/Err arm — the same
23694        // predicate-vs-gate coherence discipline the sibling
23695        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
23696        // carries against `AplicacaoSpec::validate_politicas`. The
23697        // sweep covers both arms of the invariant (strictly below,
23698        // exactly at, strictly above) and both vacuous arms (None
23699        // `:rate-limit`, None `:circuit-breaker`), so the
23700        // equivalence holds exhaustively over the axis-covered
23701        // accept and reject sets. Clears `:timeout` throughout so
23702        // the sibling `:window<:timeout` gate is vacuous on every
23703        // input.
23704        let rl = |rate: u32, secs: u64| {
23705            Some(RateLimit {
23706                rate,
23707                window: Duration::from_secs(secs),
23708            })
23709        };
23710        let cb = |max_failures: u32, secs: u64| {
23711            Some(CircuitBreaker {
23712                max_failures,
23713                window: Duration::from_secs(secs),
23714            })
23715        };
23716        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
23717            // starving pairs (predicate = false, gate = Err)
23718            (rl(1, 3600), cb(5, 10)),
23719            (rl(4, 1), cb(5, 1)),
23720            // boundary + coherent pairs (predicate = true, gate = Ok)
23721            (rl(5, 1), cb(5, 1)),
23722            (rl(100, 1), cb(5, 10)),
23723            // vacuous arms
23724            (None, cb(5, 10)),
23725            (rl(1, 3600), None),
23726            (None, None),
23727        ];
23728        for (rate_limit, circuit_breaker) in cases.iter().copied() {
23729            let politicas = MeshPolicy {
23730                circuit_breaker,
23731                rate_limit,
23732                ..Default::default()
23733            };
23734            let predicate = politicas.breaker_can_trip_under_rate_limit();
23735
23736            let mut s = three_member_spec();
23737            s.politicas = politicas.clone();
23738            s.politicas.timeout = None;
23739            let gate_ok = !matches!(
23740                s.validate(),
23741                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
23742            );
23743
23744            assert_eq!(
23745                predicate, gate_ok,
23746                "predicate must agree with validate arm on pair \
23747                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
23748            );
23749        }
23750    }
23751
23752    #[test]
23753    fn rejects_retries_saturate_breaker_trip_threshold() {
23754        // The fail-before-pass-after pin on the cross-axis
23755        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
23756        // axis is individually well-formed under its own per-axis
23757        // bracket (both above the zero floor, both below the cap), but
23758        // the pair is a structurally-truncated retry policy: one
23759        // client's `retries + 1 = 4` failing attempts hit the trip
23760        // threshold on the third attempt, the breaker opens, and the
23761        // fourth attempt (the last declared retry) is blocked by the
23762        // open breaker — the substrate declared four attempts and
23763        // structurally allows three.
23764        //
23765        // Envoy's `retry_policy.num_retries` paired against
23766        // `outlier_detection.consecutive_5xx` carries the identical
23767        // relation; every production playbook that pairs the two axes
23768        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
23769        // trip threshold strictly above any single client's retry
23770        // budget so the breaker distinguishes one persistently-failing
23771        // client from sustained multi-client failure.
23772        //
23773        // Pin both the diagnostic arm and the payload values so a
23774        // future re-shape of the arm surfaces here as a deliberate
23775        // test edit. Clears `:timeout` and `:rate-limit` so the
23776        // sibling cross-axis
23777        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
23778        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
23779        // arms do not fire first on the ordering-precedent they hold
23780        // over this arm.
23781        let mut s = three_member_spec();
23782        s.politicas.timeout = None;
23783        s.politicas.retries = Some(3);
23784        s.politicas.circuit_breaker = Some(CircuitBreaker {
23785            max_failures: 3,
23786            window: Duration::from_secs(1),
23787        });
23788        s.politicas.rate_limit = None;
23789        assert_eq!(
23790            s.validate().unwrap_err(),
23791            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23792                retries: 3,
23793                max_failures: 3,
23794            }
23795        );
23796    }
23797
23798    #[test]
23799    fn accepts_retries_below_breaker_trip_threshold() {
23800        // Positive-control sweep across the production-playbook band
23801        // — every pair a real playbook recommends where the breaker's
23802        // trip threshold is strictly above the client's retry budget
23803        // must validate. Envoy default `num_retries: 3` with
23804        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
23805        // opens on multi-client failures beyond that); Istio
23806        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
23807        // `execution.isolation.thread.timeoutInMilliseconds` + 3
23808        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
23809        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
23810        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
23811        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
23812        // arms are vacuous on this sweep.
23813        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
23814        {
23815            let mut s = three_member_spec();
23816            s.politicas.timeout = None;
23817            s.politicas.retries = Some(retries);
23818            s.politicas.circuit_breaker = Some(CircuitBreaker {
23819                max_failures,
23820                window: Duration::from_secs(60),
23821            });
23822            s.politicas.rate_limit = None;
23823            s.validate().unwrap_or_else(|e| {
23824                panic!(
23825                    "production-playbook pair retries={retries} \
23826                     max_failures={max_failures} must validate; got {e:?}"
23827                )
23828            });
23829        }
23830    }
23831
23832    #[test]
23833    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
23834        // Boundary pin: `max_failures == retries + 1` is the smallest
23835        // trip threshold that admits one client's exhausted retries
23836        // through completion (the R+1th failure — the last declared
23837        // retry — trips the breaker exactly as it completes, so
23838        // retries fully executed). The invariant is `>`, not `>=`,
23839        // stated in the coherent direction `max_failures > retries`.
23840        // Catches a future off-by-one tightening to
23841        // `max_failures > retries + 1` that would drift the accept set
23842        // away from the codified
23843        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
23844        // predicate.
23845        let mut s = three_member_spec();
23846        s.politicas.timeout = None;
23847        s.politicas.retries = Some(3);
23848        s.politicas.circuit_breaker = Some(CircuitBreaker {
23849            max_failures: 4,
23850            window: Duration::from_secs(60),
23851        });
23852        s.politicas.rate_limit = None;
23853        s.validate()
23854            .expect("max_failures == retries + 1 is the boundary accept case");
23855    }
23856
23857    #[test]
23858    fn rejects_retries_equal_to_breaker_trip_threshold() {
23859        // Off-by-one boundary pin: exactly at the trip threshold is
23860        // still structurally truncating (the invariant is `>`, so `<=`
23861        // refuses even the tight boundary). `retries = 3` with
23862        // `max_failures = 3` means the breaker trips on the third
23863        // failure — the last declared retry attempt is blocked.
23864        // Catches a future relaxation to `>=` that would silently
23865        // drift the accept boundary.
23866        let mut s = three_member_spec();
23867        s.politicas.timeout = None;
23868        s.politicas.retries = Some(3);
23869        s.politicas.circuit_breaker = Some(CircuitBreaker {
23870            max_failures: 3,
23871            window: Duration::from_secs(60),
23872        });
23873        s.politicas.rate_limit = None;
23874        assert_eq!(
23875            s.validate().unwrap_err(),
23876            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23877                retries: 3,
23878                max_failures: 3,
23879            }
23880        );
23881    }
23882
23883    #[test]
23884    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
23885        // The predicate is vacuously `true` when `:retries` is None —
23886        // a `:circuit-breaker` alone declares a failure counter whose
23887        // per-client attempt count is unconstrained by the substrate,
23888        // so no per-client saturation bound on failures-per-client-call
23889        // is knowable at author time. The substrate takes no position
23890        // on whether an omitted `:retries` axis means zero retries or
23891        // "the client picks its own retry policy" — either way, the
23892        // pair is undeclared and the cross-axis gate has nothing to
23893        // check. Pin so a future tightening that made the gate
23894        // opinionated on half-declared pairs surfaces here.
23895        let mut s = three_member_spec();
23896        s.politicas.timeout = None;
23897        s.politicas.retries = None;
23898        s.politicas.circuit_breaker = Some(CircuitBreaker {
23899            max_failures: 1,
23900            window: Duration::from_secs(60),
23901        });
23902        s.politicas.rate_limit = None;
23903        s.validate().expect(
23904            "cross-axis retries gate must be vacuous when :retries is None, \
23905             however low :max-failures is",
23906        );
23907    }
23908
23909    #[test]
23910    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
23911        // Peer of the sibling `:retries`-absent case: a `:retries`
23912        // without a `:circuit-breaker` declares a client-retry policy
23913        // with no failure counter to trip, so the pair is undeclared
23914        // and the cross-axis gate has nothing to check.
23915        let mut s = three_member_spec();
23916        s.politicas.timeout = None;
23917        s.politicas.retries = Some(POLICY_RETRIES_MAX);
23918        s.politicas.circuit_breaker = None;
23919        s.politicas.rate_limit = None;
23920        s.validate().expect(
23921            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
23922             however high :retries is",
23923        );
23924    }
23925
23926    #[test]
23927    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
23928        // Ordering pin: a pair whose retries is *both* zero-floor-
23929        // violating and structurally at-or-below the trip threshold
23930        // must surface the per-axis zero-floor arm first — the
23931        // zero-floor diagnostic is more self-locating (its omit-axis
23932        // remediation is directly named), where the cross-axis arm
23933        // would send the author to reconcile two values one of which
23934        // is not a meaningful retry count at all. Same ordering
23935        // discipline every per-axis bracket carries internally
23936        // (zero-floor before canonical-form before cap), and the
23937        // sibling cross-axis
23938        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
23939        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
23940        let mut s = three_member_spec();
23941        s.politicas.timeout = None;
23942        s.politicas.retries = Some(0);
23943        s.politicas.circuit_breaker = Some(CircuitBreaker {
23944            max_failures: 3,
23945            window: Duration::from_secs(60),
23946        });
23947        s.politicas.rate_limit = None;
23948        assert_eq!(
23949            s.validate().unwrap_err(),
23950            AplicacaoError::PolicyRetriesZero,
23951            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
23952        );
23953    }
23954
23955    #[test]
23956    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
23957        // Cross-axis ordering pin: a `:politicas` whose axes trip
23958        // BOTH cross-axis arms — `:rate-limit` starves the breaker
23959        // within `:window` (the sibling
23960        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
23961        // `:retries + 1` saturates `:max-failures` (this arm) — must
23962        // surface the rate-limit-starve diagnostic first. The
23963        // rate-limit-starve arm reasons across the token-bucket
23964        // admission axis every rate-limited edge carries whether or
23965        // not `:retries` is declared, so its diagnostic is more
23966        // self-locating; the retries-saturate arm reasons across a
23967        // per-client retry-policy budget the starve arm does not
23968        // touch.
23969        //
23970        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
23971        // pair trips both: the rate structurally cannot deliver 5
23972        // failures per 10s breaker window, and simultaneously
23973        // one client's `retries + 1 = 6` attempts alone would
23974        // saturate the 5-`max_failures` threshold.
23975        let mut s = three_member_spec();
23976        s.politicas.timeout = None;
23977        s.politicas.retries = Some(5);
23978        s.politicas.circuit_breaker = Some(CircuitBreaker {
23979            max_failures: 5,
23980            window: Duration::from_secs(10),
23981        });
23982        s.politicas.rate_limit = Some(RateLimit {
23983            rate: 1,
23984            window: Duration::from_secs(3600),
23985        });
23986        assert_eq!(
23987            s.validate().unwrap_err(),
23988            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23989                rate: 1,
23990                rl_window: Duration::from_secs(3600),
23991                max_failures: 5,
23992                cb_window: Duration::from_secs(10),
23993            },
23994            "sibling :rate-limit-starve cross-axis arm must fire before the \
23995             retries-saturate arm when both apply"
23996        );
23997    }
23998
23999    #[test]
24000    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
24001        // Equivalence pin: the substrate-canonical
24002        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
24003        // predicate and the [`AplicacaoSpec::validate_politicas`]
24004        // cross-axis arm must discriminate the same set on every pair
24005        // covered by their shared invariant. A future refactor of
24006        // either side that breaks the equivalence trips here rather
24007        // than as a divergence between the predicate's Boolean answer
24008        // and the validate gate's Ok/Err arm — the same
24009        // predicate-vs-gate coherence discipline the sibling
24010        // [`MeshPolicy::breaker_window_observes_timeout`] and
24011        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
24012        // carry against `AplicacaoSpec::validate_politicas`. The
24013        // sweep covers both arms of the invariant (strictly below,
24014        // exactly at the boundary, strictly above) and both vacuous
24015        // arms (None `:retries`, None `:circuit-breaker`), so the
24016        // equivalence holds exhaustively over the axis-covered accept
24017        // and reject sets. Clears `:timeout` and `:rate-limit`
24018        // throughout so the sibling cross-axis arms are vacuous on
24019        // every input.
24020        let cb = |max_failures: u32| {
24021            Some(CircuitBreaker {
24022                max_failures,
24023                window: Duration::from_secs(60),
24024            })
24025        };
24026        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
24027            // saturating pairs (predicate = false, gate = Err)
24028            (Some(3), cb(3)),
24029            (Some(3), cb(1)),
24030            (Some(10), cb(5)),
24031            // boundary + coherent pairs (predicate = true, gate = Ok)
24032            (Some(3), cb(4)),
24033            (Some(1), cb(5)),
24034            (Some(3), cb(20)),
24035            // vacuous arms
24036            (None, cb(1)),
24037            (Some(10), None),
24038            (None, None),
24039        ];
24040        for (retries, circuit_breaker) in cases.iter().copied() {
24041            let politicas = MeshPolicy {
24042                retries,
24043                circuit_breaker,
24044                ..Default::default()
24045            };
24046            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
24047
24048            let mut s = three_member_spec();
24049            s.politicas = politicas.clone();
24050            let gate_ok = !matches!(
24051                s.validate(),
24052                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
24053            );
24054
24055            assert_eq!(
24056                predicate, gate_ok,
24057                "predicate must agree with validate arm on pair \
24058                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
24059            );
24060        }
24061    }
24062
24063    #[test]
24064    fn rejects_rate_limit_cannot_admit_retry_burst() {
24065        // The fail-before-pass-after pin on the cross-axis
24066        // `(:retries, :rate-limit)` invariant. Each axis is
24067        // individually well-formed under its own per-axis bracket (both
24068        // above the zero floor, both below the cap), but the pair is a
24069        // structurally-truncated retry policy: one client's
24070        // `retries + 1 = 6` failing attempts consume 6 tokens from a
24071        // bucket that admits at most 3 per refill window, so the fourth
24072        // attempt onward is 429ed by the local rate limiter and the
24073        // declared retry policy is silently truncated by the same rate
24074        // limiter it feeds through — the substrate declared six
24075        // attempts and structurally allows three.
24076        //
24077        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
24078        // against `retry_policy.num_retries` carries the identical
24079        // relation; every production playbook that pairs the two axes
24080        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
24081        // capacity strictly above any single client's retry budget so
24082        // the limiter distinguishes one client's declared retries from
24083        // sustained multi-client load.
24084        //
24085        // Pin both the diagnostic arm and the payload values so a
24086        // future re-shape of the arm surfaces here as a deliberate
24087        // test edit. Clears `:timeout` and `:circuit-breaker` so the
24088        // sibling cross-axis
24089        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
24090        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
24091        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
24092        // arms do not fire first on the ordering-precedent they hold
24093        // over this arm.
24094        let mut s = three_member_spec();
24095        s.politicas.timeout = None;
24096        s.politicas.retries = Some(5);
24097        s.politicas.circuit_breaker = None;
24098        s.politicas.rate_limit = Some(RateLimit {
24099            rate: 3,
24100            window: Duration::from_secs(1),
24101        });
24102        assert_eq!(
24103            s.validate().unwrap_err(),
24104            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
24105                retries: 5,
24106                rate: 3,
24107            }
24108        );
24109    }
24110
24111    #[test]
24112    fn accepts_rate_limit_admits_retry_burst() {
24113        // Positive-control sweep across the production-playbook band
24114        // — every pair a real playbook recommends where the bucket
24115        // capacity is strictly above the client's retry budget must
24116        // validate. Envoy default `num_retries: 3` with 100/s (100
24117        // tokens per window admits 4 attempts per client with 96 to
24118        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
24119        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
24120        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
24121        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
24122        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
24123        // arms are vacuous on this sweep.
24124        for (retries, rate, secs) in [
24125            (3u32, 100u32, 1u64),
24126            (3, 50, 1),
24127            (2, 10, 1),
24128            (5, 1000, 1),
24129            (3, 1_000_000, 3600),
24130            (10, POLICY_RATE_LIMIT_MAX, 1),
24131        ] {
24132            let mut s = three_member_spec();
24133            s.politicas.timeout = None;
24134            s.politicas.retries = Some(retries);
24135            s.politicas.circuit_breaker = None;
24136            s.politicas.rate_limit = Some(RateLimit {
24137                rate,
24138                window: Duration::from_secs(secs),
24139            });
24140            s.validate().unwrap_or_else(|e| {
24141                panic!(
24142                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
24143                     must validate; got {e:?}"
24144                )
24145            });
24146        }
24147    }
24148
24149    #[test]
24150    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
24151        // Boundary pin: `rate == retries + 1` is the smallest bucket
24152        // capacity that structurally admits one client's exhausted
24153        // retries through completion (each attempt draws exactly one
24154        // token; `retries + 1` tokens available admits `retries + 1`
24155        // attempts, retries fully executed). The invariant is `>=`,
24156        // stated in the coherent direction `rate >= retries + 1`.
24157        // Catches a future off-by-one tightening to `rate > retries + 1`
24158        // that would drift the accept set away from the codified
24159        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
24160        let mut s = three_member_spec();
24161        s.politicas.timeout = None;
24162        s.politicas.retries = Some(3);
24163        s.politicas.circuit_breaker = None;
24164        s.politicas.rate_limit = Some(RateLimit {
24165            rate: 4,
24166            window: Duration::from_secs(1),
24167        });
24168        s.validate()
24169            .expect("rate == retries + 1 is the boundary accept case");
24170    }
24171
24172    #[test]
24173    fn rejects_rate_one_below_retry_burst() {
24174        // Off-by-one boundary pin: exactly one token short of the
24175        // retry burst is still structurally truncating (the invariant
24176        // is `>=`, so `<` refuses even a one-token shortfall).
24177        // `retries = 3` with `rate = 3` means one client's four
24178        // attempts consume four tokens from a three-token bucket —
24179        // the fourth attempt is 429ed. Catches a future relaxation to
24180        // `>` on the wrong side (`rate > retries`, accepting equal)
24181        // that would silently drift the accept boundary and admit a
24182        // structurally-truncated retry policy at the emit boundary.
24183        let mut s = three_member_spec();
24184        s.politicas.timeout = None;
24185        s.politicas.retries = Some(3);
24186        s.politicas.circuit_breaker = None;
24187        s.politicas.rate_limit = Some(RateLimit {
24188            rate: 3,
24189            window: Duration::from_secs(1),
24190        });
24191        assert_eq!(
24192            s.validate().unwrap_err(),
24193            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
24194                retries: 3,
24195                rate: 3,
24196            }
24197        );
24198    }
24199
24200    #[test]
24201    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
24202        // The predicate is vacuously `true` when `:retries` is None —
24203        // a `:rate-limit` alone declares a token-bucket rate whose
24204        // per-client attempt count is unconstrained by the substrate,
24205        // so no per-client saturation bound on tokens-per-client-call
24206        // is knowable at author time. The substrate takes no position
24207        // on whether an omitted `:retries` axis means zero retries or
24208        // "the client picks its own retry policy" — either way, the
24209        // pair is undeclared and the cross-axis gate has nothing to
24210        // check. Pin so a future tightening that made the gate
24211        // opinionated on half-declared pairs surfaces here.
24212        let mut s = three_member_spec();
24213        s.politicas.timeout = None;
24214        s.politicas.retries = None;
24215        s.politicas.circuit_breaker = None;
24216        s.politicas.rate_limit = Some(RateLimit {
24217            rate: 1,
24218            window: Duration::from_secs(1),
24219        });
24220        s.validate().expect(
24221            "cross-axis burst gate must be vacuous when :retries is None, \
24222             however low :rate is",
24223        );
24224    }
24225
24226    #[test]
24227    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
24228        // Peer of the sibling `:retries`-absent case: a `:retries`
24229        // without a `:rate-limit` declares a client-retry policy with
24230        // no rate limiter to saturate, so the pair is undeclared and
24231        // the cross-axis gate has nothing to check. Uses
24232        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
24233        // authored retry budget the per-axis cap admits — a `:retries
24234        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
24235        // or not `:rate-limit` is declared.
24236        let mut s = three_member_spec();
24237        s.politicas.timeout = None;
24238        s.politicas.retries = Some(POLICY_RETRIES_MAX);
24239        s.politicas.circuit_breaker = None;
24240        s.politicas.rate_limit = None;
24241        s.validate().expect(
24242            "cross-axis burst gate must be vacuous when :rate-limit is None, \
24243             however high :retries is",
24244        );
24245    }
24246
24247    #[test]
24248    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
24249        // Ordering pin: a pair whose retries is *both* zero-floor-
24250        // violating and structurally below the retry-burst threshold
24251        // must surface the per-axis zero-floor arm first — the
24252        // zero-floor diagnostic is more self-locating (its omit-axis
24253        // remediation is directly named), where the cross-axis arm
24254        // would send the author to reconcile two values one of which
24255        // is not a meaningful retry count at all. Same ordering
24256        // discipline every per-axis bracket carries internally
24257        // (zero-floor before canonical-form before cap), and the
24258        // sibling cross-axis
24259        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
24260        // ordering pin on the `(:retries, :max-failures)` pair.
24261        let mut s = three_member_spec();
24262        s.politicas.timeout = None;
24263        s.politicas.retries = Some(0);
24264        s.politicas.circuit_breaker = None;
24265        s.politicas.rate_limit = Some(RateLimit {
24266            rate: 1,
24267            window: Duration::from_secs(1),
24268        });
24269        assert_eq!(
24270            s.validate().unwrap_err(),
24271            AplicacaoError::PolicyRetriesZero,
24272            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
24273        );
24274    }
24275
24276    #[test]
24277    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
24278        // Cross-axis ordering pin: a `:politicas` whose axes trip
24279        // BOTH cross-axis arms — `:rate-limit` starves the breaker
24280        // within `:window` (the sibling
24281        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
24282        // `:retries + 1` exceeds the bucket capacity (this arm) —
24283        // must surface the rate-limit-starve diagnostic first. The
24284        // starve arm is the token-bucket admission invariant every
24285        // rate-limited edge carries against the breaker whether or
24286        // not `:retries` is declared, so its diagnostic is more
24287        // self-locating; the burst arm reasons across a per-client
24288        // retry-policy budget the starve arm does not touch. Same
24289        // "more foundational cross-axis first" ordering discipline the
24290        // sibling
24291        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
24292        // pin on the peer pair carries.
24293        //
24294        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
24295        // pair trips both: the rate structurally cannot deliver 5
24296        // failures per 10s breaker window (starve arm), and
24297        // simultaneously one client's `retries + 1 = 6` attempts alone
24298        // would exhaust the 1-token bucket (burst arm).
24299        let mut s = three_member_spec();
24300        s.politicas.timeout = None;
24301        s.politicas.retries = Some(5);
24302        s.politicas.circuit_breaker = Some(CircuitBreaker {
24303            max_failures: 5,
24304            window: Duration::from_secs(10),
24305        });
24306        s.politicas.rate_limit = Some(RateLimit {
24307            rate: 1,
24308            window: Duration::from_secs(3600),
24309        });
24310        assert_eq!(
24311            s.validate().unwrap_err(),
24312            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24313                rate: 1,
24314                rl_window: Duration::from_secs(3600),
24315                max_failures: 5,
24316                cb_window: Duration::from_secs(10),
24317            },
24318            "sibling :rate-limit-starve cross-axis arm must fire before the \
24319             burst arm when both apply"
24320        );
24321    }
24322
24323    #[test]
24324    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
24325        // Cross-axis ordering pin: a `:politicas` whose axes trip
24326        // BOTH the retries-saturate arm and this burst arm — one
24327        // client's `retries + 1` failures saturate the breaker's trip
24328        // threshold (the sibling
24329        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
24330        // `retries + 1` exceeds the bucket capacity (this arm) —
24331        // must surface the retries-saturate diagnostic first. The
24332        // saturate arm is the per-client-vs-breaker relation every
24333        // retry-with-breaker pair carries whether or not `:rate-limit`
24334        // is declared, so its diagnostic is more self-locating; the
24335        // burst arm reasons across the rate-limit token-bucket
24336        // admission axis the saturate arm does not touch. Same
24337        // "more foundational cross-axis first" ordering discipline
24338        // carries here.
24339        //
24340        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
24341        // rate: 3/s }` pair trips both: the breaker's `max_failures
24342        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
24343        // one client's `retries + 1 = 6` attempts alone would exhaust
24344        // the 3-token bucket (burst arm). Clears `:timeout` so the
24345        // sibling `:window<:timeout` gate is vacuous, and the
24346        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
24347        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
24348        // the arm that fires first.
24349        let mut s = three_member_spec();
24350        s.politicas.timeout = None;
24351        s.politicas.retries = Some(5);
24352        s.politicas.circuit_breaker = Some(CircuitBreaker {
24353            max_failures: 3,
24354            window: Duration::from_secs(60),
24355        });
24356        s.politicas.rate_limit = Some(RateLimit {
24357            rate: 3,
24358            window: Duration::from_secs(1),
24359        });
24360        assert_eq!(
24361            s.validate().unwrap_err(),
24362            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
24363                retries: 5,
24364                max_failures: 3,
24365            },
24366            "sibling :retries-saturate cross-axis arm must fire before the \
24367             burst arm when both apply"
24368        );
24369    }
24370
24371    #[test]
24372    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
24373        // Equivalence pin: the substrate-canonical
24374        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
24375        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
24376        // must discriminate the same set on every pair covered by
24377        // their shared invariant. A future refactor of either side
24378        // that breaks the equivalence trips here rather than as a
24379        // divergence between the predicate's Boolean answer and the
24380        // validate gate's Ok/Err arm — the same predicate-vs-gate
24381        // coherence discipline the three sibling cross-axis
24382        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
24383        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
24384        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
24385        // carry against `AplicacaoSpec::validate_politicas`. The sweep
24386        // covers both arms of the invariant (strictly below, exactly
24387        // at the boundary, strictly above) and both vacuous arms
24388        // (None `:retries`, None `:rate-limit`), so the equivalence
24389        // holds exhaustively over the axis-covered accept and reject
24390        // sets. Clears `:timeout` and `:circuit-breaker` throughout
24391        // so the three sibling cross-axis arms are vacuous on every
24392        // input.
24393        let rl = |rate: u32, secs: u64| {
24394            Some(RateLimit {
24395                rate,
24396                window: Duration::from_secs(secs),
24397            })
24398        };
24399        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
24400            // burst-exceeding pairs (predicate = false, gate = Err)
24401            (Some(3), rl(3, 1)),
24402            (Some(5), rl(1, 1)),
24403            (Some(10), rl(5, 1)),
24404            // boundary + coherent pairs (predicate = true, gate = Ok)
24405            (Some(3), rl(4, 1)),
24406            (Some(1), rl(5, 1)),
24407            (Some(3), rl(1_000_000, 3600)),
24408            // vacuous arms
24409            (None, rl(1, 1)),
24410            (Some(10), None),
24411            (None, None),
24412        ];
24413        for (retries, rate_limit) in cases.iter().copied() {
24414            let politicas = MeshPolicy {
24415                retries,
24416                rate_limit,
24417                ..Default::default()
24418            };
24419            let predicate = politicas.rate_limit_admits_retry_burst();
24420
24421            let mut s = three_member_spec();
24422            s.politicas = politicas.clone();
24423            let gate_ok = !matches!(
24424                s.validate(),
24425                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
24426            );
24427
24428            assert_eq!(
24429                predicate, gate_ok,
24430                "predicate must agree with validate arm on pair \
24431                 (retries={retries:?}, rate_limit={rate_limit:?})"
24432            );
24433        }
24434    }
24435
24436    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
24437    /// equivalence pin — assert that on each `(label, politicas,
24438    /// expected)` case the substrate-canonical fold and the validate
24439    /// cascade agree byte-for-byte. Extracted so each pin's own body
24440    /// stays under `clippy::too_many_lines`.
24441    fn assert_first_cross_axis_violation_agrees_with_gate(
24442        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
24443    ) {
24444        for (label, politicas, expected) in cases {
24445            let fold = politicas.first_cross_axis_violation();
24446            assert_eq!(
24447                fold.as_ref(),
24448                expected.as_ref(),
24449                "fold must return {expected:?} on `{label}`; got {fold:?}"
24450            );
24451
24452            let mut s = three_member_spec();
24453            s.politicas = politicas.clone();
24454            let gate = s.validate();
24455            match expected {
24456                None => {
24457                    // No cross-axis violation: validate must pass (the
24458                    // per-axis brackets pass by construction on every
24459                    // fixture above; every fixture's non-`:politicas`
24460                    // slots come from `three_member_spec`).
24461                    gate.as_ref()
24462                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
24463                }
24464                Some(want) => {
24465                    let got =
24466                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
24467                    assert_eq!(
24468                        &got, want,
24469                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
24470                    );
24471                }
24472            }
24473        }
24474    }
24475
24476    #[test]
24477    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
24478        // Equivalence pin on the compound cross-axis fold: the
24479        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
24480        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
24481        // cascade must return identical `AplicacaoError` variants on
24482        // every axis-covered input — the "compound-fold ≡ gate"
24483        // contract that generalizes the four sibling per-arm pins
24484        // onto the compound primitive that folds all four. A future
24485        // refactor of either side that breaks the equivalence trips
24486        // here rather than as a divergence between what the substrate
24487        // primitive answers and what `feira build` accepts.
24488        //
24489        // Half-A of the sweep: every single-arm violation (one arm
24490        // fires with the three sibling arms vacuous), the vacuous
24491        // shape (empty policy — no arm fires), and the fully-coherent
24492        // shape (every axis declared inside the coherence surface —
24493        // no arm fires). Half-B (pairwise-ordering coverage — the
24494        // "which arm wins when two apply" contract) lives in the
24495        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
24496        // pin; splitting keeps each pin's body under
24497        // `clippy::too_many_lines`.
24498        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
24499            max_failures,
24500            window: Duration::from_secs(secs),
24501        };
24502        let rl = |rate: u32, secs: u64| RateLimit {
24503            rate,
24504            window: Duration::from_secs(secs),
24505        };
24506        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
24507            (
24508                "window-below-timeout only",
24509                MeshPolicy {
24510                    timeout: Some(Duration::from_secs(30)),
24511                    circuit_breaker: Some(cb(5, 10)),
24512                    ..Default::default()
24513                },
24514                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
24515                    window: Duration::from_secs(10),
24516                    timeout: Duration::from_secs(30),
24517                }),
24518            ),
24519            (
24520                "starve only",
24521                MeshPolicy {
24522                    rate_limit: Some(rl(1, 3600)),
24523                    circuit_breaker: Some(cb(5, 10)),
24524                    ..Default::default()
24525                },
24526                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24527                    rate: 1,
24528                    rl_window: Duration::from_secs(3600),
24529                    max_failures: 5,
24530                    cb_window: Duration::from_secs(10),
24531                }),
24532            ),
24533            (
24534                "retries-saturate only",
24535                MeshPolicy {
24536                    retries: Some(3),
24537                    circuit_breaker: Some(cb(3, 60)),
24538                    ..Default::default()
24539                },
24540                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
24541                    retries: 3,
24542                    max_failures: 3,
24543                }),
24544            ),
24545            (
24546                "retries-burst only",
24547                MeshPolicy {
24548                    retries: Some(5),
24549                    rate_limit: Some(rl(3, 1)),
24550                    ..Default::default()
24551                },
24552                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
24553                    retries: 5,
24554                    rate: 3,
24555                }),
24556            ),
24557            ("empty policy", MeshPolicy::default(), None),
24558            (
24559                "fully-coherent policy",
24560                MeshPolicy {
24561                    timeout: Some(Duration::from_secs(30)),
24562                    retries: Some(3),
24563                    circuit_breaker: Some(cb(5, 60)),
24564                    mtls_required: Some(true),
24565                    rate_limit: Some(rl(100, 1)),
24566                },
24567                None,
24568            ),
24569        ];
24570        assert_first_cross_axis_violation_agrees_with_gate(cases);
24571    }
24572
24573    #[test]
24574    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
24575        // Half-B of the compound-fold ≡ gate equivalence pin: the
24576        // load-bearing pairwise-ordering coverage. Every ordered pair
24577        // of the four cross-axis arms — six combinations — where two
24578        // arms are simultaneously eligible must surface the
24579        // more-foundational arm's diagnostic verbatim. Pins the fold's
24580        // arm-ordering byte-for-byte against the validate cascade's
24581        // arm-ordering, so a future reshuffle of either side that
24582        // silently drifts the ordering trips here rather than as a
24583        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
24584        // pins cannot catch (they clear every sibling arm, so their
24585        // sweeps are pairwise-ordering-agnostic by construction).
24586        //
24587        // The six pairs the four-arm cascade admits:
24588        // window-before-starve, window-before-saturate,
24589        // window-before-burst, starve-before-saturate,
24590        // starve-before-burst, saturate-before-burst.
24591        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
24592            max_failures,
24593            window: Duration::from_secs(secs),
24594        };
24595        let rl = |rate: u32, secs: u64| RateLimit {
24596            rate,
24597            window: Duration::from_secs(secs),
24598        };
24599        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
24600            (
24601                "window+starve → window wins",
24602                MeshPolicy {
24603                    timeout: Some(Duration::from_secs(30)),
24604                    rate_limit: Some(rl(1, 3600)),
24605                    circuit_breaker: Some(cb(5, 10)),
24606                    ..Default::default()
24607                },
24608                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
24609                    window: Duration::from_secs(10),
24610                    timeout: Duration::from_secs(30),
24611                }),
24612            ),
24613            (
24614                "window+retries-saturate → window wins",
24615                MeshPolicy {
24616                    timeout: Some(Duration::from_secs(30)),
24617                    retries: Some(5),
24618                    circuit_breaker: Some(cb(3, 10)),
24619                    ..Default::default()
24620                },
24621                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
24622                    window: Duration::from_secs(10),
24623                    timeout: Duration::from_secs(30),
24624                }),
24625            ),
24626            (
24627                "window+retries-burst → window wins",
24628                MeshPolicy {
24629                    timeout: Some(Duration::from_secs(30)),
24630                    retries: Some(5),
24631                    rate_limit: Some(rl(3, 1)),
24632                    circuit_breaker: Some(cb(5, 10)),
24633                    ..Default::default()
24634                },
24635                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
24636                    window: Duration::from_secs(10),
24637                    timeout: Duration::from_secs(30),
24638                }),
24639            ),
24640            (
24641                "starve+retries-saturate → starve wins",
24642                MeshPolicy {
24643                    retries: Some(5),
24644                    rate_limit: Some(rl(1, 3600)),
24645                    circuit_breaker: Some(cb(5, 10)),
24646                    ..Default::default()
24647                },
24648                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24649                    rate: 1,
24650                    rl_window: Duration::from_secs(3600),
24651                    max_failures: 5,
24652                    cb_window: Duration::from_secs(10),
24653                }),
24654            ),
24655            (
24656                "starve+retries-burst → starve wins",
24657                MeshPolicy {
24658                    retries: Some(5),
24659                    rate_limit: Some(rl(1, 3600)),
24660                    circuit_breaker: Some(cb(10, 10)),
24661                    ..Default::default()
24662                },
24663                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24664                    rate: 1,
24665                    rl_window: Duration::from_secs(3600),
24666                    max_failures: 10,
24667                    cb_window: Duration::from_secs(10),
24668                }),
24669            ),
24670            (
24671                "retries-saturate+retries-burst → saturate wins",
24672                MeshPolicy {
24673                    retries: Some(5),
24674                    rate_limit: Some(rl(3, 1)),
24675                    circuit_breaker: Some(cb(3, 60)),
24676                    ..Default::default()
24677                },
24678                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
24679                    retries: 5,
24680                    max_failures: 3,
24681                }),
24682            ),
24683        ];
24684        assert_first_cross_axis_violation_agrees_with_gate(cases);
24685    }
24686
24687    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
24688    /// equivalence pin — assert that on each `(label, politicas,
24689    /// expected)` case both the substrate primitive
24690    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
24691    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
24692    /// same `three_member_spec` fixture whose non-`:politicas` slots
24693    /// always validate cleanly) return identical `AplicacaoError` variants.
24694    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
24695    /// the sibling cross-axis-only surface — extended here onto the
24696    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
24697    /// own body stays under `clippy::too_many_lines`.
24698    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
24699        for (label, politicas, expected) in cases {
24700            let direct = politicas.validate();
24701            match (expected, &direct) {
24702                (None, Ok(())) => {}
24703                (None, Err(got)) => {
24704                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
24705                }
24706                (Some(want), Ok(())) => {
24707                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
24708                }
24709                (Some(want), Err(got)) => assert_eq!(
24710                    got, want,
24711                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
24712                ),
24713            }
24714
24715            let mut s = three_member_spec();
24716            s.politicas = politicas.clone();
24717            let gate = s.validate();
24718            match (expected, &gate) {
24719                (None, Ok(())) => {}
24720                (None, Err(got)) => {
24721                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
24722                }
24723                (Some(want), Ok(())) => {
24724                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
24725                }
24726                (Some(want), Err(got)) => assert_eq!(
24727                    got, want,
24728                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
24729                ),
24730            }
24731        }
24732    }
24733
24734    #[test]
24735    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
24736        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
24737        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
24738        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
24739        // :max-failures`, `:rate-limit` rate) that discriminate the
24740        // "per-axis phase fires" arm of the compound gate, plus one
24741        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
24742        // ZERO }`) that pins the phase-boundary ordering — the per-axis
24743        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
24744        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
24745        // diagnostic wins over the window-below-timeout diagnostic. Peer
24746        // of the sibling
24747        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
24748        // + `_on_pairwise_orderings` pins on the compound cross-axis
24749        // fold, extended here onto the outer compound entry gate that
24750        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
24751        // clean-pass surfaces) lives in the sibling
24752        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
24753        // pin; splitting keeps each pin's body under
24754        // `clippy::too_many_lines`.
24755        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
24756            (
24757                "per-axis: timeout zero",
24758                MeshPolicy {
24759                    timeout: Some(Duration::ZERO),
24760                    ..Default::default()
24761                },
24762                Some(AplicacaoError::PolicyTimeoutZero),
24763            ),
24764            (
24765                "per-axis: retries zero",
24766                MeshPolicy {
24767                    retries: Some(0),
24768                    ..Default::default()
24769                },
24770                Some(AplicacaoError::PolicyRetriesZero),
24771            ),
24772            (
24773                "per-axis: breaker max-failures zero",
24774                MeshPolicy {
24775                    circuit_breaker: Some(CircuitBreaker {
24776                        max_failures: 0,
24777                        window: Duration::from_secs(60),
24778                    }),
24779                    ..Default::default()
24780                },
24781                Some(AplicacaoError::PolicyBreakerZeroFailures),
24782            ),
24783            (
24784                "per-axis: rate-limit rate zero",
24785                MeshPolicy {
24786                    rate_limit: Some(RateLimit {
24787                        rate: 0,
24788                        window: Duration::from_secs(1),
24789                    }),
24790                    ..Default::default()
24791                },
24792                Some(AplicacaoError::PolicyRateLimitZero),
24793            ),
24794            (
24795                "per-axis before cross-axis: zero-window wins over window-below-timeout",
24796                MeshPolicy {
24797                    timeout: Some(Duration::from_secs(30)),
24798                    circuit_breaker: Some(CircuitBreaker {
24799                        max_failures: 5,
24800                        window: Duration::ZERO,
24801                    }),
24802                    ..Default::default()
24803                },
24804                Some(AplicacaoError::PolicyBreakerZeroWindow),
24805            ),
24806        ];
24807        assert_validate_matches_gate(cases);
24808    }
24809
24810    #[test]
24811    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
24812        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
24813        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
24814        // arm that discriminates the "cross-axis phase fires" arm of
24815        // the compound gate (window-below-timeout — sibling per-arm
24816        // coverage lives in the two
24817        // `first_cross_axis_violation_matches_gate_on_*` pins above),
24818        // plus the two clean-pass shapes (empty policy — every axis
24819        // absent — and fully-coherent — every axis inside the coherence
24820        // surface) that pin the compound gate's `Ok(())` arm. Half-A
24821        // (per-axis + phase-boundary surfaces) lives in the sibling
24822        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
24823        // pin; splitting keeps each pin's body under
24824        // `clippy::too_many_lines`.
24825        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
24826            (
24827                "cross-axis: window-below-timeout",
24828                MeshPolicy {
24829                    timeout: Some(Duration::from_secs(30)),
24830                    circuit_breaker: Some(CircuitBreaker {
24831                        max_failures: 5,
24832                        window: Duration::from_secs(10),
24833                    }),
24834                    ..Default::default()
24835                },
24836                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
24837                    window: Duration::from_secs(10),
24838                    timeout: Duration::from_secs(30),
24839                }),
24840            ),
24841            ("clean pass: empty policy", MeshPolicy::default(), None),
24842            (
24843                "clean pass: every axis coherent",
24844                MeshPolicy {
24845                    timeout: Some(Duration::from_secs(30)),
24846                    retries: Some(3),
24847                    circuit_breaker: Some(CircuitBreaker {
24848                        max_failures: 5,
24849                        window: Duration::from_secs(60),
24850                    }),
24851                    mtls_required: Some(true),
24852                    rate_limit: Some(RateLimit {
24853                        rate: 100,
24854                        window: Duration::from_secs(1),
24855                    }),
24856                },
24857                None,
24858            ),
24859        ];
24860        assert_validate_matches_gate(cases);
24861    }
24862
24863    #[test]
24864    fn empty_politicas_validates() {
24865        // Omitting every policy axis is fine — defaults express "no
24866        // policy on this axis", not "policy = 0". The fixture's typical
24867        // values continue to validate; this test pins that
24868        // MeshPolicy::default() is a clean pass through validate().
24869        let mut s = three_member_spec();
24870        s.politicas = MeshPolicy::default();
24871        s.validate().unwrap();
24872    }
24873
24874    #[test]
24875    fn typical_politicas_validates_with_every_axis_set() {
24876        // The full §III.1 example block (timeout + retries + breaker +
24877        // mtls + rate-limit) — every axis nonzero — must remain a
24878        // clean pass.
24879        let mut s = three_member_spec();
24880        s.politicas = MeshPolicy {
24881            timeout: Some(Duration::from_secs(30)),
24882            retries: Some(3),
24883            circuit_breaker: Some(CircuitBreaker {
24884                max_failures: 5,
24885                window: Duration::from_secs(60),
24886            }),
24887            mtls_required: Some(true),
24888            rate_limit: Some(RateLimit {
24889                rate: 100,
24890                window: Duration::from_secs(1),
24891            }),
24892        };
24893        s.validate().unwrap();
24894    }
24895
24896    #[test]
24897    fn rejects_empty_cluster_name() {
24898        let mut s = three_member_spec();
24899        s.placement.clusters = vec!["rio".into(), String::new()];
24900        assert_eq!(
24901            s.validate().unwrap_err(),
24902            AplicacaoError::PlacementClusterEmpty
24903        );
24904    }
24905
24906    #[test]
24907    fn rejects_duplicate_cluster_names() {
24908        let mut s = three_member_spec();
24909        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
24910        let err = s.validate().unwrap_err();
24911        assert!(
24912            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
24913            "got {err:?}"
24914        );
24915    }
24916
24917    #[test]
24918    fn rejects_placement_cluster_with_uppercase() {
24919        // The canonical "I copied the cluster's display name verbatim"
24920        // typo — K8s context names are lowercase per DNS-1123 label
24921        // rule, but org docs often round-trip a TitleCase identifier
24922        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
24923        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
24924        // on the peer name axis.
24925        let mut s = three_member_spec();
24926        s.placement.clusters = vec!["Rio".into(), "mar".into()];
24927        let err = s.validate().unwrap_err();
24928        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
24929            panic!("expected PlacementClusterInvalid, got other variant");
24930        };
24931        assert_eq!(cluster, "Rio");
24932        assert!(
24933            reason.contains("uppercase"),
24934            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
24935        );
24936        assert!(
24937            reason.contains("\"rio\""),
24938            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
24939        );
24940    }
24941
24942    #[test]
24943    fn rejects_placement_cluster_with_underscore() {
24944        // The canonical "I'm thinking of an env var / hostname slug"
24945        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
24946        // schema. K8s context filtering on `my_cluster` silently misses
24947        // the cluster the author intended; the gate moves it to caixa-
24948        // build time. Same shape as `rejects_membro_caixa_with_underscore`
24949        // (3f9d7a0).
24950        let mut s = three_member_spec();
24951        s.placement.clusters = vec!["my_cluster".into()];
24952        let err = s.validate().unwrap_err();
24953        assert!(
24954            matches!(
24955                err,
24956                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24957                    if cluster == "my_cluster" && reason.contains('_')
24958            ),
24959            "got {err:?}"
24960        );
24961    }
24962
24963    #[test]
24964    fn rejects_placement_cluster_with_dot() {
24965        // A `:placement :clusters` entry is a single DNS-1123 *label*,
24966        // not a subdomain — even though K8s context names sometimes
24967        // carry a dotted form via kubeconfig conventions, the strictest
24968        // floor among the use sites (DNS-1035 cluster.x-k8s.io
24969        // `metadata.name`, Cilium identity label values) wins. The "I
24970        // want to namespace my cluster names with `.`" intent is
24971        // expressed via `-` (`mar-east`).
24972        let mut s = three_member_spec();
24973        s.placement.clusters = vec!["team.rio".into()];
24974        let err = s.validate().unwrap_err();
24975        assert!(
24976            matches!(
24977                err,
24978                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24979                    if cluster == "team.rio" && reason.contains('.')
24980            ),
24981            "got {err:?}"
24982        );
24983    }
24984
24985    #[test]
24986    fn rejects_placement_cluster_with_leading_hyphen() {
24987        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
24988        // with an alphanumeric. The K8s apiserver rejects `-rio`
24989        // outright; the rendered fan-out would emit a `metadata.name:
24990        // "-rio"` that fails admission far from the source caixa.lisp.
24991        let mut s = three_member_spec();
24992        s.placement.clusters = vec!["-rio".into()];
24993        let err = s.validate().unwrap_err();
24994        assert!(
24995            matches!(
24996                err,
24997                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24998                    if cluster == "-rio" && reason.contains("start and end")
24999            ),
25000            "got {err:?}"
25001        );
25002    }
25003
25004    #[test]
25005    fn rejects_placement_cluster_with_trailing_hyphen() {
25006        // The symmetric arm of the boundary rule. Pin separately so
25007        // both ends are covered against a future relaxation that only
25008        // checks one boundary (parallel to
25009        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
25010        let mut s = three_member_spec();
25011        s.placement.clusters = vec!["rio-".into()];
25012        let err = s.validate().unwrap_err();
25013        assert!(
25014            matches!(
25015                err,
25016                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
25017                    if cluster == "rio-"
25018            ),
25019            "got {err:?}"
25020        );
25021    }
25022
25023    #[test]
25024    fn rejects_placement_cluster_with_unicode() {
25025        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
25026        // before it reaches K8s. The byte-by-byte ASCII validity check
25027        // rejects multi-byte UTF-8 sequences by the first byte that
25028        // fails `[a-z0-9-]`.
25029        let mut s = three_member_spec();
25030        s.placement.clusters = vec!["rió".into()];
25031        let err = s.validate().unwrap_err();
25032        assert!(
25033            matches!(
25034                err,
25035                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
25036                    if cluster == "rió"
25037            ),
25038            "got {err:?}"
25039        );
25040    }
25041
25042    #[test]
25043    fn rejects_placement_cluster_with_whitespace() {
25044        // Whitespace is the canonical "I pasted from a sketch / doc"
25045        // footgun. The apiserver rejects every cluster `metadata.name`
25046        // value carrying whitespace.
25047        let mut s = three_member_spec();
25048        s.placement.clusters = vec!["rio cluster".into()];
25049        let err = s.validate().unwrap_err();
25050        assert!(
25051            matches!(
25052                err,
25053                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
25054                    if cluster == "rio cluster"
25055            ),
25056            "got {err:?}"
25057        );
25058    }
25059
25060    #[test]
25061    fn rejects_placement_cluster_too_long() {
25062        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
25063        // pin. The diagnostic names both the cap (63) and the actual
25064        // length so the author can shorten in one edit. Mirrors
25065        // `rejects_membro_caixa_too_long` (3f9d7a0).
25066        let mut s = three_member_spec();
25067        let too_long = "a".repeat(64);
25068        s.placement.clusters = vec![too_long.clone()];
25069        let err = s.validate().unwrap_err();
25070        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
25071            panic!("expected PlacementClusterInvalid");
25072        };
25073        assert_eq!(cluster, too_long);
25074        assert!(
25075            reason.contains("63") && reason.contains("64"),
25076            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
25077        );
25078    }
25079
25080    #[test]
25081    fn placement_cluster_max_length_validates() {
25082        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
25083        // future tightening (e.g. dropping to 62) surfaces here as a
25084        // regression, mirroring `membro_caixa_max_length_validates`
25085        // (3f9d7a0).
25086        let mut s = three_member_spec();
25087        s.placement.clusters = vec!["a".repeat(63)];
25088        s.validate().unwrap();
25089    }
25090
25091    #[test]
25092    fn accepts_canonical_placement_cluster_forms() {
25093        // The DNS-1123 label shapes a caixa author is realistically
25094        // going to write for cluster names: single-word lowercase
25095        // (`rio`), regional hyphen-joined (`mar-east`), single
25096        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
25097        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
25098        // Pin every leg so a future tightening that bans (e.g.) digit-
25099        // start identifiers surfaces here.
25100        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
25101            let mut s = three_member_spec();
25102            s.placement.clusters = vec![form.into()];
25103            s.validate().unwrap_or_else(|e| {
25104                panic!("canonical cluster form {form:?} must validate, got {e:?}")
25105            });
25106        }
25107    }
25108
25109    #[test]
25110    fn placement_cluster_empty_takes_precedence_over_invalid() {
25111        // Order pin: the existing `PlacementClusterEmpty` diagnostic
25112        // (which doesn't try to parse) fires before the new
25113        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
25114        // `:clusters` entry keeps its narrower error message — the new
25115        // gate would also reject `""`, but the empty-string arm is the
25116        // more self-locating diagnostic. Mirrors the
25117        // `membro_caixa_empty_takes_precedence_over_invalid` pin
25118        // (3f9d7a0).
25119        let mut s = three_member_spec();
25120        s.placement.clusters = vec!["rio".into(), String::new()];
25121        let err = s.validate().unwrap_err();
25122        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
25123    }
25124
25125    #[test]
25126    fn placement_cluster_invalid_fires_before_duplicate_check() {
25127        // Order pin: a malformed-shape `:clusters` entry surfaces *its
25128        // own* diagnostic, even when a later entry would otherwise
25129        // collapse onto a duplicate name. The per-entry shape gate runs
25130        // inline before the duplicate-key insert, parallel to
25131        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
25132        let mut s = three_member_spec();
25133        s.placement.clusters = vec!["Rio".into(), "rio".into()];
25134        let err = s.validate().unwrap_err();
25135        assert!(
25136            matches!(
25137                err,
25138                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
25139            ),
25140            "got {err:?}"
25141        );
25142    }
25143
25144    #[test]
25145    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
25146        // The diagnostic-shape pin: the error names the offending
25147        // `:clusters` value verbatim so the author can grep their
25148        // caixa.lisp without re-running the build, and carries a
25149        // non-empty `reason` naming the specific violation. Same shape
25150        // every typed-shape gate enshrines
25151        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
25152        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
25153        let mut s = three_member_spec();
25154        s.placement.clusters = vec!["BAD_CLUSTER".into()];
25155        let err = s.validate().unwrap_err();
25156        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
25157            panic!("expected PlacementClusterInvalid");
25158        };
25159        assert_eq!(cluster, "BAD_CLUSTER");
25160        assert!(
25161            !reason.is_empty(),
25162            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
25163        );
25164    }
25165
25166    #[test]
25167    fn rejects_sharded_with_empty_clusters() {
25168        // §III.1: Sharded uses :clusters as the shard pool. An empty
25169        // pool means "shard across no clusters" — meaningless, same as
25170        // Replicated with no hosts.
25171        let mut s = three_member_spec();
25172        s.placement.estrategia = PlacementStrategy::Sharded;
25173        s.placement.shard_key = Some("$tenantId".into());
25174        s.placement.clusters = vec![];
25175        assert!(matches!(
25176            s.validate().unwrap_err(),
25177            AplicacaoError::PlacementWithoutClusters {
25178                estrategia: PlacementStrategy::Sharded
25179            }
25180        ));
25181    }
25182
25183    #[test]
25184    fn rejects_sharded_with_empty_shard_key() {
25185        let mut s = three_member_spec();
25186        s.placement.estrategia = PlacementStrategy::Sharded;
25187        s.placement.shard_key = Some(String::new());
25188        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
25189    }
25190
25191    #[test]
25192    fn rejects_shard_key_under_replicated_strategy() {
25193        // The fail-before-pass-after pin: a `:placement (:estrategia
25194        // Replicated :shard-key "tenantId")` manifest carries the
25195        // hash-keyed-distribution slot on a strategy that never consumes
25196        // it. Before the gate the typed slot's value silently vanished
25197        // at the renderer layer (caixa-mesh emits `placement.shardKey`
25198        // verbatim regardless of strategy; the Akka-style cluster-
25199        // sharding reconciler keys off `estrategia == Sharded` and
25200        // ignores the slot otherwise), with no diagnostic. Lifting the
25201        // rejection to a build-time gate makes the
25202        // `shard_key.is_some() == matches!(estrategia, Sharded)`
25203        // partition a structural property of every validated
25204        // [`Placement`].
25205        let mut s = three_member_spec();
25206        // The fixture already uses Replicated; just add a shard-key.
25207        s.placement.shard_key = Some("$tenantId".into());
25208        let err = s.validate().unwrap_err();
25209        let AplicacaoError::ShardKeyOnNonSharded {
25210            estrategia,
25211            shard_key,
25212        } = err
25213        else {
25214            panic!("expected ShardKeyOnNonSharded, got {err:?}");
25215        };
25216        assert_eq!(estrategia, PlacementStrategy::Replicated);
25217        assert_eq!(shard_key, "$tenantId");
25218    }
25219
25220    #[test]
25221    fn rejects_shard_key_under_singlenode_strategy() {
25222        // Peer of the Replicated case above on the SingleNode arm: OTP
25223        // distributed-app takeover (one cluster runs at a time) has no
25224        // hash-keyed routing axis to consume `:shard-key` either, so
25225        // the rejection fires on both non-Sharded arms uniformly.
25226        let mut s = three_member_spec();
25227        s.placement.estrategia = PlacementStrategy::SingleNode;
25228        s.placement.shard_key = Some("$tenantId".into());
25229        let err = s.validate().unwrap_err();
25230        let AplicacaoError::ShardKeyOnNonSharded {
25231            estrategia,
25232            shard_key,
25233        } = err
25234        else {
25235            panic!("expected ShardKeyOnNonSharded, got {err:?}");
25236        };
25237        assert_eq!(estrategia, PlacementStrategy::SingleNode);
25238        assert_eq!(shard_key, "$tenantId");
25239    }
25240
25241    #[test]
25242    fn rejects_empty_shard_key_under_replicated_strategy() {
25243        // The `Some("")` case under non-Sharded is rejected by
25244        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
25245        // fires before the empty-value gate), not
25246        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
25247        // the `Sharded` arm). Pin the partition so a future reorder of
25248        // the validate_placement match arms doesn't silently swap which
25249        // diagnostic the author sees — both are author errors, but
25250        // ShardKeyOnNonSharded names which strategy is the actual fix
25251        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
25252        // only says "pick a non-empty key".
25253        let mut s = three_member_spec();
25254        s.placement.shard_key = Some(String::new());
25255        let err = s.validate().unwrap_err();
25256        assert!(
25257            matches!(
25258                err,
25259                AplicacaoError::ShardKeyOnNonSharded {
25260                    estrategia: PlacementStrategy::Replicated,
25261                    ref shard_key,
25262                } if shard_key.is_empty()
25263            ),
25264            "got {err:?}"
25265        );
25266    }
25267
25268    #[test]
25269    fn replicated_without_shard_key_validates() {
25270        // The complement of the rejection: `:placement :estrategia
25271        // Replicated` with `:shard-key None` is the canonical happy
25272        // path on every existing fixture. Pin the no-shard-key case so
25273        // the new gate doesn't accidentally fire on `None`.
25274        let mut s = three_member_spec();
25275        assert!(matches!(
25276            s.placement.estrategia,
25277            PlacementStrategy::Replicated
25278        ));
25279        s.placement.shard_key = None;
25280        s.validate().unwrap();
25281    }
25282
25283    #[test]
25284    fn singlenode_without_shard_key_validates() {
25285        // Peer of the Replicated no-shard-key case on the SingleNode
25286        // arm — both non-Sharded strategies must validate cleanly when
25287        // the slot is omitted.
25288        let mut s = three_member_spec();
25289        s.placement.estrategia = PlacementStrategy::SingleNode;
25290        s.placement.shard_key = None;
25291        s.validate().unwrap();
25292    }
25293
25294    #[test]
25295    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
25296        // Fail-before-pass-after pin on
25297        // [`AplicacaoError::shard_key_on_non_sharded`]'s
25298        // substrate-primitive posture: byte-identity + `Display`
25299        // byte-string parity against the open-coded struct-literal
25300        // for every non-`Sharded` [`PlacementStrategy`] arm across a
25301        // representative `:shard-key` value the sole in-crate wire-up
25302        // site (`AplicacaoSpec::validate_placement`'s
25303        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
25304        // arm) emits. Any wrapper-side silent normalization, `.into()`
25305        // divergence, or accidental field rebrand on the ctor body
25306        // surfaces at assert time rather than at a downstream consumer
25307        // that reads `err.estrategia` / `err.shard_key` back and gets a
25308        // different value than the one it stored.
25309        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
25310            let placement = Placement {
25311                estrategia,
25312                clusters: vec!["cluster-a".to_string()],
25313                shard_key: Some("$tenantId".to_string()),
25314                affinity: None,
25315            };
25316            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
25317            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
25318                estrategia,
25319                shard_key: "$tenantId".to_string(),
25320            };
25321            assert_eq!(
25322                via_ctor, via_literal,
25323                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
25324                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
25325            );
25326            assert_eq!(
25327                via_ctor.to_string(),
25328                via_literal.to_string(),
25329                "Display byte-string must byte-equal the open-coded struct-literal \
25330                 for {estrategia:?}"
25331            );
25332        }
25333    }
25334
25335    #[test]
25336    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
25337        // Boundary-sweep pin on the ctor's substrate-primitive
25338        // projection: the `estrategia` slot is stored verbatim from
25339        // [`Placement::estrategia`] on every arm the accessor can
25340        // return, and the `shard_key` slot preserves the caller-side
25341        // `&str` byte-for-byte. Sweeping every arm of
25342        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
25343        // current caller never reaches, since the ctor is a substrate
25344        // primitive independent of any single caller's dispatch gate)
25345        // catches a future silent field-rebrand or per-arm ctor
25346        // divergence at caixa-core build time rather than at a
25347        // downstream consumer far from the wire-up commit.
25348        for &estrategia in PlacementStrategy::ALL {
25349            let placement = Placement {
25350                estrategia,
25351                clusters: vec!["cluster-a".to_string()],
25352                shard_key: Some("$tenantId".to_string()),
25353                affinity: None,
25354            };
25355            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
25356            let AplicacaoError::ShardKeyOnNonSharded {
25357                estrategia: stored_estrategia,
25358                shard_key: stored_shard_key,
25359            } = err
25360            else {
25361                panic!(
25362                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
25363                );
25364            };
25365            assert_eq!(
25366                stored_estrategia, estrategia,
25367                "estrategia slot must round-trip verbatim through Placement::estrategia \
25368                 for {estrategia:?}"
25369            );
25370            assert_eq!(
25371                stored_shard_key, "$tenantId",
25372                "shard_key slot must preserve the caller-side &str byte-for-byte \
25373                 for {estrategia:?}"
25374            );
25375        }
25376    }
25377
25378    #[test]
25379    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
25380        // End-to-end pin: the sole in-crate wire-up site
25381        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
25382        // refusal) routes through
25383        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
25384        // `Err` byte-equals the ctor's output on the same non-`Sharded`
25385        // fixture. A future silent de-lift of the wire-up back to the
25386        // open-coded struct-literal trips this test at caixa-core build
25387        // time rather than at a downstream diagnostic consumer far from
25388        // the wire-up commit.
25389        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
25390            let mut s = three_member_spec();
25391            s.placement.estrategia = estrategia;
25392            s.placement.shard_key = Some("$tenantId".to_string());
25393            let observed = s.validate().unwrap_err();
25394            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
25395            assert_eq!(
25396                observed, expected,
25397                "validate_placement's non-Sharded-arm Err must byte-equal \
25398                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
25399            );
25400            assert_eq!(
25401                observed.to_string(),
25402                expected.to_string(),
25403                "Display byte-string parity for {estrategia:?}"
25404            );
25405        }
25406    }
25407
25408    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
25409        // Fixture builder for the `:placement :shard-key` shape gate
25410        // tests: a three-member Aplicacao on the `Sharded` strategy
25411        // with the supplied `:shard-key` slot. Co-locates the
25412        // arm-construction so every test below carries one line of
25413        // setup (the offending `:shard-key` value) and the assertion.
25414        let mut s = three_member_spec();
25415        s.placement.estrategia = PlacementStrategy::Sharded;
25416        s.placement.shard_key = Some(key.into());
25417        s
25418    }
25419
25420    #[test]
25421    fn rejects_shard_key_with_embedded_space() {
25422        // The canonical paste-from-aligned-doc footgun:
25423        // `:shard-key "$tenant Id"` — the Akka-style entity-id
25424        // extractor reads the slot as a single-token reference, and an
25425        // embedded space breaks the token boundary at the runtime
25426        // hash-extractor pass with no diagnostic naming the offending
25427        // entry.
25428        let s = sharded_spec_with_key("$tenant Id");
25429        let err = s.validate().unwrap_err();
25430        assert!(
25431            matches!(
25432                err,
25433                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
25434                    if shard_key == "$tenant Id" && reason.contains("space")
25435            ),
25436            "got {err:?}"
25437        );
25438    }
25439
25440    #[test]
25441    fn rejects_shard_key_with_leading_space() {
25442        // Leading-space arm of the embedded-whitespace footgun — the
25443        // paste-from-aligned-doc / paste-from-CSV-cell variant where
25444        // the leading column-padding leaked into the slot.
25445        let s = sharded_spec_with_key(" $tenantId");
25446        let err = s.validate().unwrap_err();
25447        assert!(
25448            matches!(
25449                err,
25450                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
25451                    if shard_key == " $tenantId"
25452            ),
25453            "got {err:?}"
25454        );
25455    }
25456
25457    #[test]
25458    fn rejects_shard_key_with_trailing_newline() {
25459        // The canonical paste-from-shell-heredoc footgun — every
25460        // `<<EOF` heredoc terminator paste leaves a trailing newline
25461        // the YAML emitter then folds away inconsistently across
25462        // emitter implementations.
25463        let s = sharded_spec_with_key("$tenantId\n");
25464        let err = s.validate().unwrap_err();
25465        assert!(
25466            matches!(
25467                err,
25468                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
25469                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
25470            ),
25471            "got {err:?}"
25472        );
25473    }
25474
25475    #[test]
25476    fn rejects_shard_key_with_embedded_tab() {
25477        // The paste-from-aligned-doc tab-stop variant — tabs land
25478        // alongside spaces in copy-paste from formatted columns.
25479        let s = sharded_spec_with_key("$tenant\tId");
25480        let err = s.validate().unwrap_err();
25481        assert!(
25482            matches!(
25483                err,
25484                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
25485                    if shard_key == "$tenant\tId" && reason.contains("tab")
25486            ),
25487            "got {err:?}"
25488        );
25489    }
25490
25491    #[test]
25492    fn rejects_shard_key_with_control_character() {
25493        // The paste-from-binary / paste-from-screen-cleared-terminal
25494        // footgun — an embedded `\x01` (SOH) byte that some YAML
25495        // emitters silently strip and others escape as ``,
25496        // breaking round-trip across emitter implementations.
25497        let s = sharded_spec_with_key("$tenant\u{0001}Id");
25498        let err = s.validate().unwrap_err();
25499        assert!(
25500            matches!(
25501                err,
25502                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
25503                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
25504            ),
25505            "got {err:?}"
25506        );
25507    }
25508
25509    #[test]
25510    fn rejects_shard_key_with_non_ascii() {
25511        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
25512        // footgun — non-ASCII bytes normalize differently between the
25513        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
25514        // YAML parser, the same entity ID can silently map to two
25515        // distinct shards on a re-render.
25516        let s = sharded_spec_with_key("$tenàntId");
25517        let err = s.validate().unwrap_err();
25518        assert!(
25519            matches!(
25520                err,
25521                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
25522                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
25523            ),
25524            "got {err:?}"
25525        );
25526    }
25527
25528    #[test]
25529    fn rejects_shard_key_too_long() {
25530        // Length cap pin: 64 bytes — one byte over the
25531        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
25532        // here is a paste-from-doc multi-line blob landing in
25533        // `:shard-key` instead of a single-token extractor expression.
25534        let too_long = "a".repeat(64);
25535        let s = sharded_spec_with_key(&too_long);
25536        let err = s.validate().unwrap_err();
25537        let AplicacaoError::ShardKeyInvalid {
25538            ref shard_key,
25539            ref reason,
25540        } = err
25541        else {
25542            panic!("expected ShardKeyInvalid, got {err:?}");
25543        };
25544        assert_eq!(shard_key, &too_long);
25545        assert!(
25546            reason.contains("63") && reason.contains("64"),
25547            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
25548        );
25549    }
25550
25551    #[test]
25552    fn shard_key_max_length_validates() {
25553        // Boundary pin: 63 bytes exactly — the
25554        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
25555        // dropping to 62) surfaces here as a regression, mirroring
25556        // `placement_cluster_max_length_validates` /
25557        // `placement_affinity_max_length_validates` on the peer
25558        // identifier-shaped slots.
25559        let s = sharded_spec_with_key(&"a".repeat(63));
25560        s.validate().unwrap();
25561    }
25562
25563    #[test]
25564    fn accepts_canonical_shard_key_forms() {
25565        // The Akka-style entity-id extractor shapes a caixa author is
25566        // realistically going to write — pin every leg so a future
25567        // tightening that bans (e.g.) the `${...}` interpolation
25568        // variant or the `metadata.<field>` JSONPath form surfaces
25569        // here as a regression. The canonical forms span:
25570        //
25571        //   - bare property name (`tenantId`, `customerId`)
25572        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
25573        //   - JSONPath-style nested reference (`metadata.tenantId`,
25574        //     `$.user.id`)
25575        //   - interpolation-style template (`${tenant}`)
25576        //   - snake_case property name (`customer_id`)
25577        //   - kebab-case property name (`customer-id` — accepted
25578        //     because the slot is a printable-ASCII single-token
25579        //     reference, not a DNS-1123 label like
25580        //     `:placement :affinity` / `:clusters`)
25581        //   - single character (`a`, `$` — boundary)
25582        for form in [
25583            "tenantId",
25584            "customerId",
25585            "$tenantId",
25586            "metadata.tenantId",
25587            "$.user.id",
25588            "${tenant}",
25589            "customer_id",
25590            "customer-id",
25591            "a",
25592            "$",
25593        ] {
25594            let s = sharded_spec_with_key(form);
25595            s.validate().unwrap_or_else(|e| {
25596                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
25597            });
25598        }
25599    }
25600
25601    #[test]
25602    fn shard_key_empty_takes_precedence_over_invalid() {
25603        // Order pin: the existing `ShardedKeyEmpty` diagnostic
25604        // (reserved for the `Sharded` `Some("")` arm) fires before the
25605        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
25606        // `:shard-key` keeps its narrower error message — the new gate
25607        // would also reject `""` defensively, but the empty-string arm
25608        // is the more self-locating diagnostic. Mirrors the
25609        // `placement_cluster_empty_takes_precedence_over_invalid` pin
25610        // on the peer identifier-shaped slot.
25611        let s = sharded_spec_with_key("");
25612        let err = s.validate().unwrap_err();
25613        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
25614    }
25615
25616    #[test]
25617    fn shard_key_invalid_diagnostic_carries_offending_value() {
25618        // The diagnostic-shape pin: the error names the offending
25619        // `:shard-key` value verbatim so the author can grep their
25620        // caixa.lisp without re-running the build, and carries a
25621        // parser-shaped `reason:` naming the specific violation —
25622        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
25623        // on the peer identifier-shaped slot.
25624        let s = sharded_spec_with_key("$tenant Id");
25625        let err = s.validate().unwrap_err();
25626        let AplicacaoError::ShardKeyInvalid {
25627            ref shard_key,
25628            ref reason,
25629        } = err
25630        else {
25631            panic!("expected ShardKeyInvalid, got {err:?}");
25632        };
25633        assert_eq!(shard_key, "$tenant Id");
25634        assert!(
25635            !reason.is_empty(),
25636            "reason must name the specific violation, got empty string"
25637        );
25638    }
25639
25640    #[test]
25641    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
25642        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
25643        // `:shard-key` carried on non-Sharded strategies) fires before
25644        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
25645        // a `Replicated` strategy surfaces the more self-locating
25646        // strategy-mismatch diagnostic (naming the actual fix — drop
25647        // the slot, or switch to Sharded) rather than the shape
25648        // diagnostic. The strategy-mismatch arm is the more actionable
25649        // diagnostic: a malformed shard-key on Replicated is "you
25650        // shouldn't have a :shard-key here at all", not "your
25651        // :shard-key value is malformed".
25652        let mut s = three_member_spec();
25653        // Replicated is the default fixture strategy.
25654        s.placement.shard_key = Some("$tenant Id".into());
25655        let err = s.validate().unwrap_err();
25656        assert!(
25657            matches!(
25658                err,
25659                AplicacaoError::ShardKeyOnNonSharded {
25660                    estrategia: PlacementStrategy::Replicated,
25661                    ..
25662                }
25663            ),
25664            "got {err:?}"
25665        );
25666    }
25667
25668    #[test]
25669    fn rejects_empty_affinity_hint() {
25670        let mut s = three_member_spec();
25671        s.placement.affinity = Some(String::new());
25672        assert_eq!(
25673            s.validate().unwrap_err(),
25674            AplicacaoError::PlacementAffinityEmpty
25675        );
25676    }
25677
25678    #[test]
25679    fn placement_without_affinity_validates() {
25680        // Omitting :affinity is fine — the placement engine falls back
25681        // to the default heuristic. Pin the no-hint case so the
25682        // affinity-empty rejection doesn't accidentally fire on `None`.
25683        let mut s = three_member_spec();
25684        s.placement.affinity = None;
25685        s.validate().unwrap();
25686    }
25687
25688    #[test]
25689    fn rejects_placement_affinity_with_uppercase() {
25690        // The canonical "I copied the ADR's display name verbatim" typo
25691        // — placement hints land verbatim in K8s label-selector
25692        // territory, where the apiserver enforces the DNS-1123 label
25693        // rule (lowercase-only) on every identity-keyed admission axis.
25694        // Mirrors `rejects_placement_cluster_with_uppercase` on the
25695        // sibling slot.
25696        let mut s = three_member_spec();
25697        s.placement.affinity = Some("DataLocality".into());
25698        let err = s.validate().unwrap_err();
25699        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
25700            panic!("expected PlacementAffinityInvalid, got other variant");
25701        };
25702        assert_eq!(affinity, "DataLocality");
25703        assert!(
25704            reason.contains("uppercase"),
25705            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
25706        );
25707        assert!(
25708            reason.contains("\"datalocality\""),
25709            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
25710        );
25711    }
25712
25713    #[test]
25714    fn rejects_placement_affinity_with_underscore() {
25715        // The canonical "I'm thinking of an env var / Python identifier"
25716        // leak — `_` is forbidden by every DNS-1123 label schema. Same
25717        // shape as `rejects_placement_cluster_with_underscore` on the
25718        // sibling slot.
25719        let mut s = three_member_spec();
25720        s.placement.affinity = Some("data_locality".into());
25721        let err = s.validate().unwrap_err();
25722        assert!(
25723            matches!(
25724                err,
25725                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
25726                    if affinity == "data_locality" && reason.contains('_')
25727            ),
25728            "got {err:?}"
25729        );
25730    }
25731
25732    #[test]
25733    fn rejects_placement_affinity_with_dot() {
25734        // A `:placement :affinity` value is a single DNS-1123 *label*
25735        // (it lands as a K8s label value selector key), not a subdomain.
25736        // The "I want to namespace my hint with `.`" intent is expressed
25737        // via `-` (`data-locality-east`).
25738        let mut s = three_member_spec();
25739        s.placement.affinity = Some("data.locality".into());
25740        let err = s.validate().unwrap_err();
25741        assert!(
25742            matches!(
25743                err,
25744                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
25745                    if affinity == "data.locality" && reason.contains('.')
25746            ),
25747            "got {err:?}"
25748        );
25749    }
25750
25751    #[test]
25752    fn rejects_placement_affinity_with_unicode() {
25753        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
25754        // before it reaches K8s. The byte-by-byte ASCII validity check
25755        // rejects multi-byte UTF-8 sequences by the first byte that
25756        // fails `[a-z0-9-]`.
25757        let mut s = three_member_spec();
25758        s.placement.affinity = Some("data-localité".into());
25759        let err = s.validate().unwrap_err();
25760        assert!(
25761            matches!(
25762                err,
25763                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
25764                    if affinity == "data-localité"
25765            ),
25766            "got {err:?}"
25767        );
25768    }
25769
25770    #[test]
25771    fn rejects_placement_affinity_with_leading_hyphen() {
25772        // DNS-1123 boundary rule: labels must start with an
25773        // alphanumeric. Pin separately from the trailing-hyphen arm so
25774        // a future relaxation that only checks one boundary surfaces
25775        // here as a regression (parallel to
25776        // `rejects_placement_cluster_with_leading_hyphen`).
25777        let mut s = three_member_spec();
25778        s.placement.affinity = Some("-data-locality".into());
25779        let err = s.validate().unwrap_err();
25780        assert!(
25781            matches!(
25782                err,
25783                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
25784                    if affinity == "-data-locality" && reason.contains("start and end")
25785            ),
25786            "got {err:?}"
25787        );
25788    }
25789
25790    #[test]
25791    fn rejects_placement_affinity_with_trailing_hyphen() {
25792        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
25793        // ends are covered against a future relaxation.
25794        let mut s = three_member_spec();
25795        s.placement.affinity = Some("data-locality-".into());
25796        let err = s.validate().unwrap_err();
25797        assert!(
25798            matches!(
25799                err,
25800                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
25801                    if affinity == "data-locality-"
25802            ),
25803            "got {err:?}"
25804        );
25805    }
25806
25807    #[test]
25808    fn rejects_placement_affinity_with_whitespace() {
25809        // Whitespace is the canonical "I pasted from a sketch / doc"
25810        // footgun. The apiserver rejects every label-selector value
25811        // carrying whitespace.
25812        let mut s = three_member_spec();
25813        s.placement.affinity = Some("data locality".into());
25814        let err = s.validate().unwrap_err();
25815        assert!(
25816            matches!(
25817                err,
25818                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
25819                    if affinity == "data locality"
25820            ),
25821            "got {err:?}"
25822        );
25823    }
25824
25825    #[test]
25826    fn rejects_placement_affinity_too_long() {
25827        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
25828        // pin. The diagnostic names both the cap (63) and the actual
25829        // length so the author can shorten in one edit. Mirrors
25830        // `rejects_placement_cluster_too_long`.
25831        let mut s = three_member_spec();
25832        let too_long = "a".repeat(64);
25833        s.placement.affinity = Some(too_long.clone());
25834        let err = s.validate().unwrap_err();
25835        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
25836            panic!("expected PlacementAffinityInvalid");
25837        };
25838        assert_eq!(affinity, too_long);
25839        assert!(
25840            reason.contains("63") && reason.contains("64"),
25841            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
25842        );
25843    }
25844
25845    #[test]
25846    fn placement_affinity_max_length_validates() {
25847        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
25848        // future tightening (e.g. dropping to 62) surfaces here as a
25849        // regression, mirroring `placement_cluster_max_length_validates`.
25850        let mut s = three_member_spec();
25851        s.placement.affinity = Some("a".repeat(63));
25852        s.validate().unwrap();
25853    }
25854
25855    #[test]
25856    fn accepts_canonical_placement_affinity_forms() {
25857        // The DNS-1123 label shapes a caixa author is realistically
25858        // going to write for placement hints: the M3 canonical examples
25859        // (`data-locality`, `low-latency`, `anti-affinity`), the
25860        // single-token form (`affinity`), the single-character boundary
25861        // (`a`), the digit-start (DNS-1123 allows this, unlike
25862        // DNS-1035), and a regional-suffixed form. Pin every leg so a
25863        // future tightening that bans (e.g.) digit-start identifiers
25864        // surfaces here.
25865        for form in [
25866            "data-locality",
25867            "low-latency",
25868            "anti-affinity",
25869            "affinity",
25870            "a",
25871            "3-tier",
25872            "locality-east",
25873        ] {
25874            let mut s = three_member_spec();
25875            s.placement.affinity = Some(form.into());
25876            s.validate().unwrap_or_else(|e| {
25877                panic!("canonical affinity form {form:?} must validate, got {e:?}")
25878            });
25879        }
25880    }
25881
25882    #[test]
25883    fn placement_affinity_empty_takes_precedence_over_invalid() {
25884        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
25885        // (which doesn't try to parse) fires before the new
25886        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
25887        // `:affinity` keeps its narrower error message — the new gate
25888        // would also reject `""`, but the empty-string arm is the more
25889        // self-locating diagnostic. Mirrors the
25890        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
25891        let mut s = three_member_spec();
25892        s.placement.affinity = Some(String::new());
25893        let err = s.validate().unwrap_err();
25894        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
25895    }
25896
25897    #[test]
25898    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
25899        // The diagnostic shape pin: every rejection carries the offending
25900        // `affinity:` verbatim plus a parser-shaped `reason:` so the
25901        // author can grep their caixa.lisp for `:affinity "<hint>"` and
25902        // fix it in one edit. Mirrors the
25903        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
25904        // pin on the sibling slot.
25905        let mut s = three_member_spec();
25906        s.placement.affinity = Some("Data_Locality".into());
25907        let err = s.validate().unwrap_err();
25908        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
25909            panic!("expected PlacementAffinityInvalid");
25910        };
25911        assert_eq!(affinity, "Data_Locality");
25912        assert!(
25913            !reason.is_empty(),
25914            "diagnostic reason must not be empty (got: {reason:?})"
25915        );
25916    }
25917
25918    #[test]
25919    fn singlenode_with_takeover_candidates_validates() {
25920        // OTP distributed-application convention (MESH-COMPOSITION
25921        // §II.1): SingleNode runs on one cluster at a time but the
25922        // :clusters list enumerates the takeover candidates. Multiple
25923        // entries are not a contradiction — they are the failover pool.
25924        let mut s = three_member_spec();
25925        s.placement.estrategia = PlacementStrategy::SingleNode;
25926        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
25927        s.validate().unwrap();
25928    }
25929
25930    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
25931
25932    #[test]
25933    fn mesh_policy_default_is_empty() {
25934        // The Default impl carries None on every axis — the typed
25935        // analog of an unset `:politicas (())` slot. Renderers that
25936        // overlay the policy onto a cluster artifact key off this
25937        // predicate to skip the slot entirely; pinning so a future
25938        // axis added to MeshPolicy can't silently break the contract
25939        // (a new field whose Default is non-None would flip is_empty
25940        // to false on every existing caixa, surfacing here).
25941        assert!(MeshPolicy::default().is_empty());
25942    }
25943
25944    #[test]
25945    fn mesh_policy_with_only_timeout_is_not_empty() {
25946        let p = MeshPolicy {
25947            timeout: Some(Duration::from_secs(30)),
25948            ..Default::default()
25949        };
25950        assert!(!p.is_empty());
25951    }
25952
25953    #[test]
25954    fn mesh_policy_with_only_retries_is_not_empty() {
25955        let p = MeshPolicy {
25956            retries: Some(3),
25957            ..Default::default()
25958        };
25959        assert!(!p.is_empty());
25960    }
25961
25962    #[test]
25963    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
25964        let p = MeshPolicy {
25965            circuit_breaker: Some(CircuitBreaker {
25966                max_failures: 5,
25967                window: Duration::from_secs(60),
25968            }),
25969            ..Default::default()
25970        };
25971        assert!(!p.is_empty());
25972    }
25973
25974    #[test]
25975    fn mesh_policy_with_only_mtls_required_is_not_empty() {
25976        // Even `mtls_required: Some(false)` (an explicit opt-out) is
25977        // not empty — the author *named* the axis, the renderer needs
25978        // to honor that vs. fall back to the cluster default.
25979        let p = MeshPolicy {
25980            mtls_required: Some(false),
25981            ..Default::default()
25982        };
25983        assert!(!p.is_empty());
25984    }
25985
25986    #[test]
25987    fn mesh_policy_with_only_rate_limit_is_not_empty() {
25988        let p = MeshPolicy {
25989            rate_limit: Some(RateLimit {
25990                rate: 100,
25991                window: Duration::from_secs(1),
25992            }),
25993            ..Default::default()
25994        };
25995        assert!(!p.is_empty());
25996    }
25997
25998    #[test]
25999    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
26000        // The three-member happy-path fixture sets timeout + retries +
26001        // mtls_required — every populated axis must read non-empty.
26002        // Pin the round-trip so the M3.x per-:politicas emitter (the
26003        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
26004        // on is_empty() to decide whether to emit at all without
26005        // re-deriving the contract from inline field probes.
26006        assert!(!three_member_spec().politicas.is_empty());
26007    }
26008
26009    #[test]
26010    fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
26011        // Fail-before-pass-after round-trip pin on the paired
26012        // ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
26013        // predicate on the [`MeshPolicy`] typed slot: the lifted
26014        // constructor must materialize a value whose every one of the
26015        // five `Option<_>`-carrying per-axis fields is `None`, so the
26016        // paired [`MeshPolicy::is_empty`] predicate returns `true` on
26017        // the constructor's output by construction. A future silent
26018        // regression that omits a `None` arm from the constructor's
26019        // struct-literal (a sixth axis added to the type whose
26020        // constructor arm is forgotten, an accidental `Some(0)` on the
26021        // `retries` arm that would silently violate the
26022        // [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
26023        // here at caixa-core test time rather than surfacing as a
26024        // downstream consumer's per-`:politicas` overlay-emit path
26025        // reading a `MeshPolicy::empty()` output that fails the
26026        // emptiness predicate and lands an unexpected `spec.policies.
26027        // <axis>` field in the emitted Cilium/Envoy overlay. Peer of
26028        // the sibling
26029        // [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
26030        // pin on the M2 `:limits` typed slot — extends the same
26031        // "the canonical unset baseline satisfies the paired
26032        // emptiness predicate" round-trip discipline onto the M3
26033        // `:politicas` slot.
26034        let empty = MeshPolicy::empty();
26035        assert!(
26036            empty.is_empty(),
26037            "MeshPolicy::empty() must return a value whose is_empty() \
26038             predicate is true — got {empty:?}",
26039        );
26040        assert_eq!(empty.timeout(), None);
26041        assert_eq!(empty.retries(), None);
26042        assert_eq!(empty.circuit_breaker(), None);
26043        assert_eq!(empty.mtls_required(), None);
26044        assert_eq!(empty.rate_limit(), None);
26045    }
26046
26047    #[test]
26048    fn mesh_policy_empty_byte_equals_default() {
26049        // Fail-before-pass-after byte-parity pin on the two-path
26050        // convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
26051        // constructor must byte-equal the derived (non-`const`)
26052        // [`Default::default`] on every one of the five
26053        // `Option<_>`-carrying per-axis fields under `PartialEq`. The
26054        // two paths are semantically identical (both name the
26055        // "canonical unset [`MeshPolicy`]" shape) but structurally
26056        // distinct (the derived [`Default::default`] threads through
26057        // the derive-generated per-field `<Option<_> as Default>::default`
26058        // cascade, resolving to `None` on each; the lifted
26059        // constructor's struct-literal names each `None` arm
26060        // verbatim). A future regression on either path — an
26061        // accidental `Some(0)` on the constructor's `retries` arm
26062        // that would silently drift the constructor's output from the
26063        // derived default (surfacing here as the pin's first-arm
26064        // inequality), a future substrate-wide field-default rebrand
26065        // that lands on the derived path's per-field
26066        // `<Option<_> as Default>::default` but forgets to extend the
26067        // constructor's struct-literal (surfacing here as the pin's
26068        // per-arm inequality on the newly rebranded axis) — trips
26069        // here at caixa-core test time. The `const` binding on the
26070        // LHS forces the lifted constructor through the `const`-eval
26071        // surface at compile time, so any future accidental downgrade
26072        // to `pub fn` fires E0015 at the binding rather than at a
26073        // downstream `const`-context consumer's dispatch site. Peer
26074        // of the sibling
26075        // [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
26076        // pin on the M2 `:limits` typed slot.
26077        const EMPTY: MeshPolicy = MeshPolicy::empty();
26078        assert_eq!(
26079            EMPTY,
26080            MeshPolicy::default(),
26081            "MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
26082             every per-axis field — the two paths name the same canonical \
26083             unset baseline; a mismatch means one path drifted from the \
26084             other on some per-axis default",
26085        );
26086    }
26087
26088    #[test]
26089    fn mesh_policy_empty_ctor_is_const_fn() {
26090        // Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
26091        // constructor: the constructor must remain `pub const fn` so
26092        // downstream consumers can materialize a canonical unset
26093        // baseline in `const` context (a `const EMPTY: MeshPolicy =
26094        // MeshPolicy::empty();` module-scope binding for a
26095        // fixture-builder table, a `const`-context per-arm predicate
26096        // that folds emptiness over the constructor's output at
26097        // compile time, a compile-time lookup table the LSP hover
26098        // renderer materializes per typed-slot fixture). A future
26099        // accidental downgrade to non-`const` (an added runtime
26100        // helper reachable only from a non-`const` context in the
26101        // body, a manual hand-rolled `impl` that shadows this method)
26102        // trips at caixa-core build time — E0015 at the `const EMPTY`
26103        // binding below — rather than surfacing as a downstream
26104        // `const`-context regression far from the constructor's
26105        // declaration. The paired [`Self::is_empty`] predicate call
26106        // inside the `const { assert!(..) }` block enforces both
26107        // halves of the round-trip (constructor is `const`-callable
26108        // AND its output satisfies the paired emptiness predicate at
26109        // `const`-eval time) at caixa-core compile time. Peer of the
26110        // sibling
26111        // [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
26112        // pin on the M2 `:limits` typed slot.
26113        const EMPTY: MeshPolicy = MeshPolicy::empty();
26114        const {
26115            assert!(EMPTY.is_empty());
26116        }
26117    }
26118
26119    #[test]
26120    fn mesh_policy_default_routes_through_empty_ctor() {
26121        // Fail-before-pass-after byte-parity pin on the two-path
26122        // convergence discipline lifted onto the [`Default`] impl:
26123        // pre-fold the derive-generated [`Default::default`] and the
26124        // `pub const fn` [`MeshPolicy::empty`] constructor were
26125        // byte-equal by *coincidence* (each hand-authored or derive-
26126        // authored `None` per axis, pinned load-bearing by the
26127        // pre-existing [`mesh_policy_empty_byte_equals_default`]
26128        // sibling pin), while the folded impl now routes
26129        // [`Default::default`] through the substrate-canonical
26130        // [`Self::empty`] constructor — the two paths are byte-equal
26131        // by *construction*, one delegates to the other. This pin
26132        // sharpens the pre-existing byte-parity invariant into a
26133        // structural-delegation invariant: any future silent regression
26134        // that re-derives [`Default`] on the type (a `#[derive(Default)]`
26135        // re-addition that shadows the manual impl, a swap of the
26136        // manual impl's body onto a divergent struct-literal that
26137        // diverges from [`Self::empty`]'s output on a new field's
26138        // non-`None` canonical baseline) trips here at caixa-core test
26139        // time under `PartialEq` rather than at a downstream consumer
26140        // of the derived-until-now [`Default::default`] surface (the
26141        // five per-axis-only `..Default::default()` fixtures at
26142        // [`mesh_policy_with_only_timeout_is_not_empty`] /
26143        // [`mesh_policy_with_only_retries_is_not_empty`] /
26144        // [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
26145        // [`mesh_policy_with_only_mtls_required_is_not_empty`] /
26146        // [`mesh_policy_with_only_rate_limit_is_not_empty`], the
26147        // `MeshPolicy::default().is_empty()` round-trip at
26148        // [`mesh_policy_default_is_empty`], every future consumer of
26149        // a hypothetical `..MeshPolicy::default()` overlay-elision
26150        // arm). Peer of the sibling
26151        // [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
26152        // pin on the M2 `:limits` typed slot (abd52c2).
26153        assert_eq!(
26154            MeshPolicy::default(),
26155            MeshPolicy::empty(),
26156            "MeshPolicy::default() must delegate through MeshPolicy::empty() \
26157             on every per-axis field — a mismatch means the manual Default \
26158             impl drifted off the substrate-canonical empty() constructor \
26159             (or the constructor drifted off the impl's expected shape)",
26160        );
26161    }
26162
26163    #[test]
26164    fn mesh_policy_empty_validates_ok() {
26165        // Fail-before-pass-after invariant pin on the empty-baseline
26166        // validate composition: the canonical unset [`MeshPolicy`]
26167        // (every one of the five `Option<_>`-carrying per-axis fields
26168        // set to `None`) must pass every gate on
26169        // [`MeshPolicy::validate`]. The invariant is structurally
26170        // guaranteed today — every per-axis value-shape gate on the
26171        // validate dispatch is `if let Some(_) = self.<axis>()` guarded
26172        // and every cross-axis arm on
26173        // [`MeshPolicy::first_cross_axis_violation`] is a
26174        // `let (Some(_), Some(_))` pattern, so an all-`None` input
26175        // short-circuits every arm before any zero-floor / canonical-
26176        // form / cap / pairwise-ordering check fires. Pinning the
26177        // composition here makes the invariant load-bearing so a
26178        // future extension of the validate surface that adds a
26179        // non-`Option`-guarded gate (a hypothetical cross-slot
26180        // coherence gate a future per-axis / per-slot fold on the M3
26181        // `:politicas` slot establishes on top of the current
26182        // pairwise-cross-axis composition per
26183        // `theory/MESH-COMPOSITION.md` §III.2, a per-arm
26184        // `mtls_required`-defaults-to-`true` admission overlay a
26185        // future admission webhook lands) that fires on the all-`None`
26186        // input trips here at caixa-core test time rather than at a
26187        // downstream consumer that composed [`MeshPolicy::default`]
26188        // (which now routes through [`MeshPolicy::empty`]) with
26189        // [`MeshPolicy::validate`] as its "no-op axis short-circuit"
26190        // and observed a spurious rejection on the canonical unset
26191        // baseline. Peer of the sibling
26192        // [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
26193        // on the M2 `:limits` typed slot (abd52c2) — that one anchors
26194        // the invariant on the folded [`Default`] impl the
26195        // [`crate::LimitsSpec::empty`] constructor now backs; this one
26196        // extends it onto the M3 `:politicas` slot's folded impl.
26197        MeshPolicy::empty().validate().expect(
26198            "MeshPolicy::empty() must satisfy MeshPolicy::validate — \
26199             every per-axis value-shape gate is `if let Some(_)` guarded \
26200             and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
26201             so an all-`None` input short-circuits every arm; a spurious \
26202             rejection on the canonical unset baseline means a future \
26203             validate-side extension added a non-`Option`-guarded gate that \
26204             fires on empty input",
26205        );
26206    }
26207
26208    // ── shared duration codec: cross-slot integer-magnitude gate ──
26209    //
26210    // The integer-magnitude discipline applied to
26211    // `supervisor::duration_codec::parse` lifts onto every typed slot
26212    // that routes through the shared codec — `MeshPolicy::timeout`
26213    // (`:politicas :timeout`) and `CircuitBreaker::window`
26214    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
26215    // These cross-slot tests pin that the gate fires at the serde
26216    // layer for both typed slots, not just for the supervisor side.
26217
26218    #[test]
26219    fn policy_timeout_serde_rejects_fractional_seconds() {
26220        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
26221        // so the shared codec's integer-magnitude gate applies on
26222        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
26223        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
26224        // deserialize with the canonical-form diagnostic naming the
26225        // offending `"1.5"` and the remediation `"1500ms"`.
26226        let payload = r#"{"timeout":"1.5s"}"#;
26227        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26228        let msg = err.to_string();
26229        assert!(
26230            msg.contains("not a non-negative integer"),
26231            "expected integer-magnitude diagnostic in {msg:?}"
26232        );
26233        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
26234        assert!(
26235            msg.contains("\"1500ms\""),
26236            "missing canonical-form remediation in {msg:?}"
26237        );
26238    }
26239
26240    #[test]
26241    fn policy_timeout_serde_rejects_leading_plus_sign() {
26242        // Pin the leading-`+` arm cross-slot — the prior f64 parser
26243        // accepted `"+30s"` silently and round-tripped to `"30s"`.
26244        let payload = r#"{"timeout":"+30s"}"#;
26245        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26246        let msg = err.to_string();
26247        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
26248    }
26249
26250    #[test]
26251    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
26252        // `CircuitBreaker::window` uses `with =
26253        // "supervisor::duration_codec_required"` (the required-Duration
26254        // variant that delegates to the same shared parser). `"0.5m"`
26255        // parsed to 30s and round-tripped to `"30s"` on next emit —
26256        // DRIFT closed.
26257        let payload = format!(
26258            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
26259            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26260            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
26261        );
26262        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
26263        let msg = err.to_string();
26264        assert!(
26265            msg.contains("not a non-negative integer"),
26266            "expected integer-magnitude diagnostic in {msg:?}"
26267        );
26268        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
26269        assert!(
26270            msg.contains("\"30s\""),
26271            "missing canonical-form remediation in {msg:?}"
26272        );
26273    }
26274
26275    #[test]
26276    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
26277        // Pin the happy-path on the cross-slot side: every canonical
26278        // author shape `render` ever emits parses cleanly through the
26279        // shared codec on the `CircuitBreaker` slot. The
26280        // codec's accepted set (post-gate) is exactly its emitted set
26281        // for the integer-magnitude class.
26282        for window_lit in ["30s", "500ms", "2m", "1h"] {
26283            let payload = format!(
26284                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
26285                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26286                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
26287            );
26288            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
26289                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
26290            });
26291            assert_eq!(cb.max_failures, 5);
26292        }
26293    }
26294
26295    // ── rate_limit_codec: integer-magnitude gate ──
26296    //
26297    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
26298    // / 737a676 / d53c922 trajectory landed on every typed-duration /
26299    // typed-byte-size codec in caixa-core lifts onto the fifth typed
26300    // codec — `rate_limit_codec` — through the digit-only magnitude
26301    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
26302    // These tests pin the gate at the serde layer for `:politicas
26303    // :rate-limit` (the only typed slot the codec backs), and at the
26304    // codec-internal `parse` layer for the canonical positive cases.
26305
26306    #[test]
26307    fn rate_limit_serde_rejects_fractional_rate() {
26308        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
26309        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
26310        // wording, which didn't name the canonical-form remediation or
26311        // the round-trip drift the next emit would produce. Now refused
26312        // at deserialize with the canonical-form diagnostic naming the
26313        // offending `"1.5"` magnitude and the round-trip drift wording.
26314        let payload = r#"{"rateLimit":"1.5/s"}"#;
26315        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26316        let msg = err.to_string();
26317        assert!(
26318            msg.contains("not a non-negative integer"),
26319            "expected integer-magnitude diagnostic in {msg:?}"
26320        );
26321        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
26322        assert!(
26323            msg.contains("THEORY.md"),
26324            "missing render-determinism contract citation in {msg:?}"
26325        );
26326    }
26327
26328    #[test]
26329    fn rate_limit_serde_rejects_leading_plus_sign() {
26330        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
26331        // permissive-`+` parse), so `"+100/s"` silently parsed to
26332        // `RateLimit { 100, 1s }` and round-tripped through `render` to
26333        // `"100/s"` — a *different* canonical string on the next emit,
26334        // breaking the THEORY.md Part V render-determinism contract
26335        // exactly the way the peer duration codecs' `"+30s"` case did.
26336        // This is the load-bearing class the digit-only gate closes
26337        // beyond what `u32::from_str`'s strictness covers on its own.
26338        let payload = r#"{"rateLimit":"+100/s"}"#;
26339        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26340        let msg = err.to_string();
26341        assert!(
26342            msg.contains("not a non-negative integer"),
26343            "expected integer-magnitude diagnostic in {msg:?}"
26344        );
26345        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
26346    }
26347
26348    #[test]
26349    fn rate_limit_serde_rejects_leading_minus_sign() {
26350        // The signed-negative arm: `"-1/s"` lands on the
26351        // non-canonical-but-numeric branch via the `i64` fallback (the
26352        // `f64` parse also succeeds), surfacing the canonical-form
26353        // diagnostic. Replaces the prior value-laundered "not a u32"
26354        // wording with the unified diagnostic across signs.
26355        let payload = r#"{"rateLimit":"-1/s"}"#;
26356        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26357        let msg = err.to_string();
26358        assert!(
26359            msg.contains("not a non-negative integer"),
26360            "expected integer-magnitude diagnostic in {msg:?}"
26361        );
26362        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
26363    }
26364
26365    #[test]
26366    fn rate_limit_serde_rejects_decimal_shaped_integer() {
26367        // `"100.0/s"` is integer-valued numerically but not in the
26368        // codec's accepted set — `render` emits `"100/s"`, so the
26369        // round-trip would drift. Lifted to the canonical-form
26370        // diagnostic peer with the duration codec's `"1.0s"` case
26371        // (1c55a2a).
26372        let payload = r#"{"rateLimit":"100.0/s"}"#;
26373        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26374        let msg = err.to_string();
26375        assert!(
26376            msg.contains("not a non-negative integer"),
26377            "expected integer-magnitude diagnostic in {msg:?}"
26378        );
26379        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
26380    }
26381
26382    #[test]
26383    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
26384        // Non-numeric, non-digit-only input lands on the existing
26385        // narrower `"not a u32"` arm (preserved for diagnostic-shape
26386        // stability on the parser-shape footgun case). Pin this so a
26387        // future relaxation of the numeric-fallback predicate doesn't
26388        // silently collapse garbage onto the canonical-form arm — same
26389        // partition the peer duration codecs draw between
26390        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
26391        let payload = r#"{"rateLimit":"abc/s"}"#;
26392        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26393        let msg = err.to_string();
26394        assert!(
26395            msg.contains("not a u32"),
26396            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
26397        );
26398        assert!(
26399            !msg.contains("not a non-negative integer"),
26400            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
26401        );
26402    }
26403
26404    #[test]
26405    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
26406        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
26407        // u32's range. The digit-only gate passes; `u32::from_str`
26408        // fails on overflow. Surface that with the overflow-shaped
26409        // diagnostic naming the offending magnitude verbatim, peer
26410        // with `supervisor::duration_codec`'s overflow arm. Pinning
26411        // the wording so a future refactor doesn't silently collapse
26412        // overflow onto the canonical-form arm.
26413        let payload = r#"{"rateLimit":"4294967296/s"}"#;
26414        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26415        let msg = err.to_string();
26416        assert!(
26417            msg.contains("overflows u32"),
26418            "expected overflow diagnostic in {msg:?}"
26419        );
26420        assert!(
26421            msg.contains("\"4294967296\""),
26422            "missing offending magnitude in {msg:?}"
26423        );
26424    }
26425
26426    #[test]
26427    fn rate_limit_serde_rejects_leading_zero_magnitude() {
26428        // `"0100/s"` is digit-only, so the existing
26429        // non-digit-only / sign / fractional arm doesn't catch it —
26430        // `u32::from_str("0100")` returns `Ok(100)`, so before this
26431        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
26432        // round-tripped through `render` to `"100/s"` — a *different*
26433        // canonical string on the next emit, breaking the THEORY.md
26434        // Part V render-determinism contract exactly the way the
26435        // peer `"+100/s"` case did before the leading-`+` arm landed.
26436        // This is the load-bearing class the leading-zero gate closes
26437        // beyond what the existing digit-only / sign / fractional
26438        // gates cover, and the peer arm to the leading-`+` test
26439        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
26440        // canonical-form-drift axis.
26441        let payload = r#"{"rateLimit":"0100/s"}"#;
26442        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26443        let msg = err.to_string();
26444        assert!(
26445            msg.contains("non-canonical leading zero"),
26446            "expected leading-zero diagnostic in {msg:?}"
26447        );
26448        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
26449        assert!(
26450            msg.contains("THEORY.md"),
26451            "missing render-determinism contract citation in {msg:?}"
26452        );
26453    }
26454
26455    #[test]
26456    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
26457        // `"00/s"` is the degenerate leading-zero case — every byte
26458        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
26459        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
26460        // a *different* canonical string, same render-determinism
26461        // violation. The single-byte `"0/s"` itself is in the
26462        // accepted set (round-trips losslessly through `render`,
26463        // refused downstream by `PolicyRateLimitZero`); the
26464        // multi-byte `"00/s"` is not. Pins the boundary between the
26465        // accepted single-`0` and the rejected leading-zero class.
26466        let payload = r#"{"rateLimit":"00/s"}"#;
26467        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26468        let msg = err.to_string();
26469        assert!(
26470            msg.contains("non-canonical leading zero"),
26471            "expected leading-zero diagnostic in {msg:?}"
26472        );
26473        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
26474    }
26475
26476    #[test]
26477    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
26478        // Cross-window pin — the gate is window-agnostic; the
26479        // leading-zero class is a property of the magnitude, not the
26480        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
26481        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
26482        // single-window coverage extended across the three canonical
26483        // windows the codec accepts.
26484        let payload = r#"{"rateLimit":"007/h"}"#;
26485        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26486        let msg = err.to_string();
26487        assert!(
26488            msg.contains("non-canonical leading zero"),
26489            "expected leading-zero diagnostic in {msg:?}"
26490        );
26491        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
26492    }
26493
26494    #[test]
26495    fn rate_limit_serde_rejects_leading_whitespace() {
26496        // `" 100/s"` — the canonical paste-from-aligned-doc /
26497        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
26498        // the top-level `s.trim()` silently ate the leading space and
26499        // parsed the value to `RateLimit { 100, 1s }`, which then
26500        // round-tripped through `render` to `"100/s"` (a *different*
26501        // canonical string on the next emit) — the exact
26502        // canonical-form-drift class the leading-`+` / leading-zero
26503        // arms already close, extended to the whitespace byte class.
26504        let payload = r#"{"rateLimit":" 100/s"}"#;
26505        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26506        let msg = err.to_string();
26507        assert!(
26508            msg.contains("contains whitespace byte"),
26509            "expected whitespace diagnostic in {msg:?}"
26510        );
26511        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
26512        assert!(
26513            msg.contains("THEORY.md"),
26514            "missing render-determinism contract citation in {msg:?}"
26515        );
26516    }
26517
26518    #[test]
26519    fn rate_limit_serde_rejects_trailing_whitespace() {
26520        // `"100/s "` — the canonical shell-history / trailing-space
26521        // paste footgun. Before this gate the top-level `s.trim()`
26522        // silently ate the trailing space and parsed to
26523        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
26524        // next emit — same canonical-form drift as the leading-space
26525        // sibling, closed on the same whitespace-byte arm.
26526        let payload = r#"{"rateLimit":"100/s "}"#;
26527        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26528        let msg = err.to_string();
26529        assert!(
26530            msg.contains("contains whitespace byte"),
26531            "expected whitespace diagnostic in {msg:?}"
26532        );
26533        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
26534    }
26535
26536    #[test]
26537    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
26538        // `"100 / s"` — the canonical typographically-spaced author
26539        // shape (the same idiom every prose reference to a rate limit
26540        // renders as, mistakenly retained when the value is pasted
26541        // into a codec-shaped slot). Before this gate the per-part
26542        // `rate_str.trim()` / `unit.trim()` calls silently ate both
26543        // spaces on either side of `/` and parsed to
26544        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
26545        // codec's *internal* whitespace-tolerance vector, orthogonal
26546        // to the leading / trailing surface but the same canonical-
26547        // form-drift class. Pins the arm as strictly stronger than the
26548        // pre-existing top-level `s.trim()` behavior: it fires on
26549        // whitespace anywhere in the value, not just at the string
26550        // boundary.
26551        let payload = r#"{"rateLimit":"100 / s"}"#;
26552        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26553        let msg = err.to_string();
26554        assert!(
26555            msg.contains("contains whitespace byte"),
26556            "expected whitespace diagnostic in {msg:?}"
26557        );
26558        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
26559    }
26560
26561    #[test]
26562    fn rate_limit_serde_rejects_tab_byte() {
26563        // `"\t100/s"` — the canonical paste-from-indented-doc /
26564        // paste-from-YAML-block-scalar footgun where a tab byte leads
26565        // the magnitude. Pins that the gate covers tab (`0x09`) as
26566        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
26567        // members and both would be silently swallowed by `s.trim()`
26568        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
26569        // space alone to the full ASCII-whitespace set (space `0x20`,
26570        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
26571        // the tab arm as a representative of the non-space members.
26572        let payload = r#"{"rateLimit":"\t100/s"}"#;
26573        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26574        let msg = err.to_string();
26575        assert!(
26576            msg.contains("contains whitespace byte"),
26577            "expected whitespace diagnostic in {msg:?}"
26578        );
26579        assert!(
26580            msg.contains("0x09"),
26581            "missing offending tab byte in {msg:?}"
26582        );
26583    }
26584
26585    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
26586    //
26587    // Successor to the ASCII-whitespace arm (1ad7755) on
26588    // `rate_limit_codec` — closes the strictly-complementary class the
26589    // byte-scan cannot see, through the lifted
26590    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
26591
26592    #[test]
26593    fn rate_limit_serde_rejects_leading_nbsp() {
26594        // NBSP prefix — paste-from-typography footgun. Byte-scan
26595        // misses, `str::trim` silently strips it, value drifts to
26596        // `"100/s"` on next serialize.
26597        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
26598        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26599        let msg = err.to_string();
26600        assert!(
26601            msg.contains("non-ASCII Unicode whitespace character"),
26602            "expected non-ASCII whitespace diagnostic in {msg:?}"
26603        );
26604        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
26605    }
26606
26607    #[test]
26608    fn rate_limit_serde_rejects_internal_em_space() {
26609        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
26610        // paste-from-typography footgun on the `<integer>/<unit>`
26611        // shape.
26612        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
26613        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
26614        let msg = err.to_string();
26615        assert!(
26616            msg.contains("non-ASCII Unicode whitespace character"),
26617            "expected non-ASCII whitespace diagnostic in {msg:?}"
26618        );
26619        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
26620    }
26621
26622    #[test]
26623    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
26624        // Positive-control pin: every ASCII-only canonical form the
26625        // renderer emits stays accepted through the new arm.
26626        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
26627            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
26628            let p: MeshPolicy = serde_json::from_str(&payload)
26629                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
26630            assert!(p.rate_limit.is_some());
26631        }
26632    }
26633
26634    #[test]
26635    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
26636        // The boundary case — `"0/s"` is the canonical form
26637        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
26638        // it at the parse layer; the downstream
26639        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
26640        // `rate == 0` at the typed-validate layer above. Pins the
26641        // partition: the leading-zero gate at the codec layer does
26642        // not poach the rate-zero semantic-validation arm at the
26643        // typed-validate layer above (a future stricter codec must
26644        // not reject `"0/s"` here, or it'd collapse the diagnostic
26645        // partitioning that lets `PolicyRateLimitZero` name the
26646        // offending typed slot).
26647        let payload = r#"{"rateLimit":"0/s"}"#;
26648        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
26649            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
26650        });
26651        let rl = policy.rate_limit.expect("rate_limit must be Some");
26652        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
26653        assert_eq!(
26654            rl.window,
26655            Duration::from_secs(1),
26656            "single-`0` magnitude with `s` unit must parse to window=1s"
26657        );
26658    }
26659
26660    #[test]
26661    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
26662        // The complementary boundary pin — every magnitude
26663        // `render` emits starts with `[1-9]` (or is the single byte
26664        // `"0"`), so the canonical-form predicate is `(len == 1) ||
26665        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
26666        // '1'` case explicitly so a future tightening of the gate
26667        // (e.g. an over-eager "no leading digit < 5" rule, or a
26668        // mistakenly anchored start-of-magnitude byte check) lands
26669        // here before the canonical-forms-iterating test would catch
26670        // it.
26671        let payload = r#"{"rateLimit":"100/s"}"#;
26672        let policy: MeshPolicy = serde_json::from_str(payload)
26673            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
26674        let rl = policy.rate_limit.expect("rate_limit must be Some");
26675        assert_eq!(
26676            rl.rate, 100,
26677            "canonical-100 magnitude must parse to rate=100"
26678        );
26679    }
26680
26681    #[test]
26682    fn rate_limit_serde_accepts_integer_canonical_forms() {
26683        // Pin the happy-path: every canonical author shape `render`
26684        // ever emits parses cleanly through the codec post-gate. The
26685        // codec's accepted set (post-gate) is exactly its emitted set
26686        // for the integer-magnitude class — same property
26687        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
26688        // gates guarantee on the peer codecs. Iterating across rate
26689        // magnitudes (including `"0"`, which the codec accepts even
26690        // though `validate_politicas` rejects `rate == 0` at the typed
26691        // layer above) closes the codec contract at the parse layer
26692        // independently of the validate layer.
26693        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
26694            for unit_lit in ["s", "m", "h"] {
26695                let lit = format!("{rate_lit}/{unit_lit}");
26696                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
26697                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
26698                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
26699                });
26700                let rl = policy.rate_limit.expect("rate_limit must be Some");
26701                assert_eq!(
26702                    rl.rate,
26703                    rate_lit.parse::<u32>().unwrap(),
26704                    "rate mismatch for {lit:?}"
26705                );
26706            }
26707        }
26708    }
26709
26710    #[test]
26711    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
26712        // The structural property the gate enforces: serialize ∘
26713        // deserialize is the identity on every canonical author shape.
26714        // Peer of `parse_byte_size`'s and `parse_duration`'s
26715        // `_round_trips_through_render_for_every_canonical_form` tests
26716        // on the rate-limit axis. Before the gate, `"+100/s"` violated
26717        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
26718        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
26719        for rate in [1u32, 100, 5000, 1_000_000] {
26720            for (window, unit) in [
26721                (Duration::from_secs(1), "s"),
26722                (Duration::from_secs(60), "m"),
26723                (Duration::from_secs(3600), "h"),
26724            ] {
26725                let policy = MeshPolicy {
26726                    rate_limit: Some(RateLimit { rate, window }),
26727                    ..Default::default()
26728                };
26729                let json = serde_json::to_string(&policy).unwrap();
26730                let expected = format!("\"{rate}/{unit}\"");
26731                assert!(
26732                    json.contains(&expected),
26733                    "expected {expected:?} in {json:?}"
26734                );
26735                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
26736                assert_eq!(
26737                    back.rate_limit, policy.rate_limit,
26738                    "round-trip for {json:?}"
26739                );
26740            }
26741        }
26742    }
26743
26744    // ── self-membership cross-slot gate ──────────────────────────────
26745
26746    #[test]
26747    fn validate_no_self_membership_rejects_self_named_membro() {
26748        // An Aplicacao whose `:membros` lists its own `:nome` is a
26749        // one-node lacre-closure recursion — rejected, naming the parent.
26750        let membros = vec![
26751            membro("catalog", "^0.1"),
26752            membro("checkout", "^0.1"),
26753            membro("cart", "^0.1"),
26754        ];
26755        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
26756        assert!(
26757            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
26758            "got {err:?}"
26759        );
26760    }
26761
26762    #[test]
26763    fn validate_no_self_membership_accepts_distinct_membros() {
26764        // Positive control: distinct member names (including a member
26765        // that is itself an Aplicacao — recursive composition is valid,
26766        // MESH-COMPOSITION §V) pass the gate.
26767        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
26768        validate_no_self_membership(&membros, "checkout").unwrap();
26769    }
26770
26771    #[test]
26772    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
26773        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
26774        // `NoMembros` arm (the more-fundamental "graph must have nodes"
26775        // gate), not by this cross-slot self-edge gate. Keeping the
26776        // self-membership predicate vacuously-ok on the empty input
26777        // matches its supervisor-axis peer
26778        // (`validate_no_self_supervision_empty_children_is_ok`) and
26779        // makes the gate composable from any future call site (an M4
26780        // CR materializer's per-membros validator) without re-checking
26781        // emptiness.
26782        validate_no_self_membership(&[], "checkout").unwrap();
26783    }
26784
26785    #[test]
26786    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
26787        // Pinning the Display: the self-membership diagnostic must name
26788        // the offending caixa verbatim + the "lists itself" framing the
26789        // author can grep for, so the cluster-far failure surfaces at
26790        // build time with one-line remediation. Same diagnostic shape
26791        // as the supervisor-axis `ChildSupervisesSelf` peer.
26792        let membros = vec![membro("orquestra", "^0.1")];
26793        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
26794        let msg = err.to_string();
26795        assert!(
26796            msg.contains("orquestra"),
26797            "diagnostic must name the offending caixa nome (got: {msg:?})"
26798        );
26799        assert!(
26800            msg.contains("lists itself"),
26801            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
26802        );
26803    }
26804
26805    #[test]
26806    fn default_servico_port_constant_pins_canonical_8080_literal() {
26807        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
26808        // at the verbatim `8080` literal both consumers (the
26809        // `Entrada::port` serde default via [`default_port`] and the
26810        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
26811        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
26812        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
26813        // discipline (a085b26) on the per-renderer canonical-K8s-axis
26814        // string-constant axis: a future refactor that drifts the
26815        // constant out from under either consumer surfaces here ahead
26816        // of every per-renderer's first emission. The literal value
26817        // matches the well-known HTTP-alt port the `pleme-computeunit`
26818        // library chart already emits as its `trigger.service.port`
26819        // default — by construction the same value the substrate
26820        // assumes about every Servico's in-cluster L4 listener.
26821        assert_eq!(
26822            DEFAULT_SERVICO_PORT, 8080,
26823            "canonical Servico port literal must remain `8080` verbatim — \
26824             this is the value both the `Entrada::port` serde default and the \
26825             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
26826        );
26827    }
26828
26829    #[test]
26830    fn default_port_helper_returns_canonical_servico_port_constant() {
26831        // The bridge-arm — pins that the [`default_port`] helper
26832        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
26833        // attribute hooks routes through the lifted
26834        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
26835        // literal. A future refactor that re-introduces the `8080`
26836        // literal at the helper's return site (silently re-opening
26837        // the drift footgun this lift closed) surfaces here ahead of
26838        // every author-side `(:entrada (:host … :para …))` slot
26839        // without an explicit `:port`. Peer with the
26840        // `default_namespace_re_export_points_at_caixa_core_canonical`
26841        // pin on the caixa-mesh-side re-export axis.
26842        assert_eq!(
26843            default_port(),
26844            DEFAULT_SERVICO_PORT,
26845            "the serde-default helper must route through the lifted constant"
26846        );
26847    }
26848
26849    #[test]
26850    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
26851        // The end-to-end pin — an author-surface `(:entrada (:host …
26852        // :para …))` without an explicit `:port` slot deserializes to
26853        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
26854        // verbatim. Routes the canonical lifted constant through both
26855        // the serde-default machinery (the `#[serde(default =
26856        // "default_port")]` attribute) and the typed-value-shape
26857        // contract (the resulting [`Entrada::port`] value). A future
26858        // refactor that drifts either axis — replacing the serde
26859        // hook's helper, changing the typed slot's wire shape — would
26860        // surface here before any per-renderer's CNP / Gateway /
26861        // HTTPRoute emission consumed the drifted default.
26862        let entrada: Entrada =
26863            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
26864        assert_eq!(
26865            entrada.port, DEFAULT_SERVICO_PORT,
26866            "the serde default must materialize as the lifted canonical Servico port"
26867        );
26868    }
26869
26870    #[test]
26871    fn servico_port_min_pins_canonical_accept_set_floor() {
26872        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
26873        // verbatim `1` literal every typed `:entrada :port` acceptance
26874        // gate keys off. Peer with the
26875        // [`default_servico_port_constant_pins_canonical_8080_literal`]
26876        // discipline on the canonical-Servico-port-constant axis: a
26877        // future refactor that drifts the accept-set floor out from
26878        // under the sole consumer at [`AplicacaoSpec::validate`]'s
26879        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
26880        // every per-`:entrada` `EntradaPortZero` diagnostic. The
26881        // literal value matches the IANA-registered TCP/UDP port
26882        // space floor (`1..=65535` — port `0` is the "any ephemeral"
26883        // sentinel, not a well-defined destination the substrate's
26884        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
26885        // axis can honor).
26886        assert_eq!(
26887            SERVICO_PORT_MIN, 1,
26888            "canonical Servico port accept-set floor must remain `1` verbatim — \
26889             this is the value the `AplicacaoSpec::validate` gate at \
26890             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
26891        );
26892    }
26893
26894    #[test]
26895    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
26896        // The cross-const invariant pin — the substrate's canonical
26897        // default port must satisfy its own accept-set floor by
26898        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
26899        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
26900        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
26901        // override the operator pins through a future
26902        // `:placement :default-port` slot that lands out-of-range, a
26903        // per-edition Servico-port migration that lifted the floor
26904        // above the previous default without coordinating the pair —
26905        // would silently invalidate the serde-default emission at
26906        // every author-side `(:entrada (:host … :para …))` slot
26907        // without an explicit `:port`: the default port would fall
26908        // below the accept-set floor, the `AplicacaoSpec::validate`
26909        // gate would reject every default-carrying Aplicacao as
26910        // `EntradaPortZero`, and the substrate's typed
26911        // `(defcaixa … :kind Aplicacao)` surface would fail validate
26912        // on every Aplicacao whose author omitted `:entrada :port`
26913        // for the substrate's chosen default — a class of authoring-
26914        // surface footguns the compile-time pin structurally closes.
26915        // Peer with the
26916        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
26917        // (27f9b34) cross-const invariant pin discipline on the peer
26918        // canonical-Helm-per-values-block child-chart-enablement-toggle
26919        // axis pair.
26920        const {
26921            assert!(
26922                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
26923                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
26924                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
26925                 every default-carrying `(:entrada (:host … :para …))` slot \
26926                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
26927                 through the serde default hook and must pass the \
26928                 `AplicacaoSpec::validate` floor gate by construction",
26929            );
26930        }
26931    }
26932
26933    #[test]
26934    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
26935        // The gate-site pin — asserts the `AplicacaoSpec::validate`
26936        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
26937        // `EntradaPortZero` diagnostic on the below-floor input
26938        // `port: 0` (the only below-floor value the `u16` field can
26939        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
26940        // is the singleton `{0}`). A future refactor that drifts the
26941        // gate off the lifted const (silently re-introducing an
26942        // inline `if e.port == 0` byte-check) surfaces here — the
26943        // pin cannot distinguish `< 1` from `== 0` on the current
26944        // floor, but it *does* pin that the diagnostic fires on `0`
26945        // through whichever gate is wired, so any future accept-set
26946        // floor migration (a hypothetical unprivileged-only
26947        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
26948        // update this test alongside the const declaration —
26949        // structurally guaranteeing the gate + accept-set + pin
26950        // trio move together. Peer with the
26951        // [`rejects_zero_entrada_port`] behavioral pin on the same
26952        // per-`:entrada :port` axis — that pin asserts the pre-lift
26953        // behavioral contract (`port: 0` → `EntradaPortZero`); this
26954        // pin adds the structural link to the lifted floor const.
26955        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
26956        let mut s = three_member_spec();
26957        s.entrada.as_mut().unwrap().port = 0;
26958        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
26959    }
26960
26961    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
26962
26963    #[test]
26964    fn membro_serde_keys_match_lifted_membro_key_consts() {
26965        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
26966        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
26967        // name the exact camelCase JSON keys the
26968        // `#[serde(rename_all = "camelCase")]` attribute on
26969        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
26970        // that each canonical byte-sequence appears verbatim in the
26971        // JSON — a future accidental `rename_all = "snake_case"` /
26972        // `"kebab-case"` / verbatim-field-name flip at the derive
26973        // attribute (any of which would silently break every downstream
26974        // JSON consumer that reaches for one of the two consts via
26975        // `Value::get(...)`) surfaces here as a build-time test failure
26976        // at `aplicacao.rs`, not as an apply-time
26977        // `.get(<stale-canonical-const>)` returning `None` far from the
26978        // derive-attr drift's commit. Peer with the sibling
26979        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
26980        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
26981        // same discipline the SupervisorSpec top-level lift established,
26982        // extended here to the M3 [`Membro`] per-`:membros` axis.
26983        let m = Membro {
26984            caixa: "catalog".into(),
26985            versao: "^0.1".into(),
26986        };
26987        let json = serde_json::to_string(&m).unwrap();
26988        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26989            let quoted = format!("\"{key}\"");
26990            assert!(
26991                json.contains(&quoted),
26992                "serialized Membro must carry the lifted MEMBRO_KEY_* \
26993                 byte-sequence {quoted} verbatim in the JSON emission \
26994                 (got: {json})",
26995            );
26996        }
26997    }
26998
26999    #[test]
27000    fn membro_key_consts_are_pairwise_distinct() {
27001        // Cross-axis drift-detection pin: a future collapse of the two
27002        // canonical [`Membro`] per-entry byte-strings onto the same
27003        // value (e.g. an accidental copy-paste flip of
27004        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
27005        // silently reroute every downstream probe on one axis onto the
27006        // sibling axis's overlay entry and pass every propagation-probe
27007        // test that expected only the stale axis's value. Peer of the
27008        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
27009        // (40cc4e5).
27010        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
27011        for (i, a) in all.iter().enumerate() {
27012            for b in all.iter().skip(i + 1) {
27013                assert_ne!(
27014                    a, b,
27015                    "MEMBRO_KEY_* consts must be pairwise-distinct \
27016                     canonical byte-sequences — got `{a}` == `{b}`",
27017                );
27018            }
27019        }
27020    }
27021
27022    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
27023    //    URL-path fallback resolver every HTTPRoute-aware renderer
27024    //    reaching for a per-rule path-list resolution routes through.
27025    //    The four pin tests below fix the four-way accept-set the
27026    //    resolver must always honor: (:paths-non-empty-verbatim,
27027    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
27028    //    :paths-preserves-order-across-multiple-entries) — drift on any
27029    //    arm surfaces at caixa-core build time rather than at cluster-
27030    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
27031    //    sibling `:politicas` typed-primitive dispatch axis.
27032
27033    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
27034        Entrada {
27035            host: "example.com".into(),
27036            para: "cart".into(),
27037            paths: paths.into_iter().map(String::from).collect(),
27038            port: DEFAULT_SERVICO_PORT,
27039        }
27040    }
27041
27042    #[test]
27043    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
27044        // The typed `:entrada :paths` slot carries an author-declared
27045        // list — the resolver returns each entry verbatim, no
27046        // catch-all substitution. The canonical "author declared
27047        // paths, honor them verbatim" arm of the path-list dispatch.
27048        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
27049        assert_eq!(
27050            e.resolved_paths(),
27051            vec!["/api/cart", "/api/products"],
27052            "resolved_paths must return each `:entrada :paths` entry \
27053             verbatim when the typed slot is non-empty (got {:?})",
27054            e.resolved_paths(),
27055        );
27056    }
27057
27058    #[test]
27059    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
27060        // Empty `:entrada :paths` slot — the resolver substitutes the
27061        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
27062        // catch-all fallback verbatim. Pins the empty-arm of the
27063        // resolver's four-way accept-set against a future silent
27064        // detour that returned an empty Vec (which would emit an
27065        // HTTPRoute with zero rules — silently dropping every
27066        // external `:entrada` flow at admission time), routed to a
27067        // different fallback shape, or dropped the catch-all
27068        // altogether.
27069        let e = entrada_with_paths(vec![]);
27070        assert_eq!(
27071            e.resolved_paths(),
27072            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
27073            "resolved_paths on empty `:entrada :paths` must fall back \
27074             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
27075             all — got {:?}",
27076            e.resolved_paths(),
27077        );
27078    }
27079
27080    #[test]
27081    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
27082        // Single-entry `:entrada :paths` — the resolver returns the
27083        // single declared path verbatim, NOT the catch-all fallback
27084        // (author declared a path, honor it — the empty-arm and the
27085        // len-1 arm are semantically distinct axes of the resolver's
27086        // accept-set). Pins that the resolver treats "author declared
27087        // one path" as authored input, not as the empty case.
27088        let e = entrada_with_paths(vec!["/api/only"]);
27089        assert_eq!(
27090            e.resolved_paths(),
27091            vec!["/api/only"],
27092            "resolved_paths on single-entry `:entrada :paths` must \
27093             return the declared path verbatim, NOT the catch-all \
27094             fallback (got {:?})",
27095            e.resolved_paths(),
27096        );
27097    }
27098
27099    #[test]
27100    fn resolved_paths_preserves_author_declared_order() {
27101        // The `:entrada :paths` list is author-ordered — the resolver
27102        // preserves the author's declaration order verbatim, since
27103        // per-rule dispatch order at the K8s Gateway API HTTPRoute
27104        // consumer is significant (first-match-wins under the
27105        // path-prefix matcher). Pins against a future silent
27106        // re-sort / dedup / normalize detour that reordered author
27107        // input.
27108        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
27109        assert_eq!(
27110            e.resolved_paths(),
27111            vec!["/z/last", "/a/first", "/m/mid"],
27112            "resolved_paths must preserve author-declared `:entrada \
27113             :paths` order verbatim — got {:?}",
27114            e.resolved_paths(),
27115        );
27116    }
27117
27118    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
27119    //    slot `&[String]` slice accessor every per-`:entrada` consumer
27120    //    that must see the author's declaration verbatim (not the
27121    //    fallback-applied projection the sibling `resolved_paths`
27122    //    returns) routes through. The three pin tests below fix the
27123    //    accept-set the accessor must honor: (:non-empty-byte-equal,
27124    //    :empty-projects-empty-slice, :preserves-author-declared-order)
27125    //    — drift on any arm surfaces at caixa-core build time rather
27126    //    than at cluster-apply time. Peer discipline with the sibling
27127    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
27128    //    peer M3 mesh-slot `Vec<String>`-carry axis.
27129
27130    #[test]
27131    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
27132        // Byte-equal pin: [`Entrada::paths`] must project the raw
27133        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
27134        // slice borrowed from the typed slot's own [`Vec<String>`]
27135        // storage — no re-ordering, no dedup, no per-entry normalization,
27136        // no fallback substitution (the fallback-applying projection is
27137        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
27138        // a future silent detour that re-normalized the list, dropped
27139        // duplicates the [`AplicacaoSpec::validate`]
27140        // `EntradaPathDuplicate` refusal already rejects at build time,
27141        // or (most severe) accidentally routed through the fallback-
27142        // applying sibling and returned the substrate catch-all when
27143        // the author declared an empty list — collapsing the raw-slot
27144        // and fallback-applied axes into one and breaking the
27145        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
27146        //
27147        // Peer of the sibling
27148        // [`Placement::clusters`]-shape byte-equal pin
27149        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27150        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
27151        let fixtures: Vec<Vec<String>> = vec![
27152            Vec::new(),
27153            vec!["/api/cart".into()],
27154            vec!["/api/cart".into(), "/api/products".into()],
27155            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
27156        ];
27157        for paths in fixtures {
27158            let e = Entrada {
27159                host: "example.com".into(),
27160                para: "cart".into(),
27161                paths: paths.clone(),
27162                port: DEFAULT_SERVICO_PORT,
27163            };
27164            assert_eq!(
27165                e.paths(),
27166                paths.as_slice(),
27167                "Entrada::paths must return :entrada :paths verbatim \
27168                 (got {:?}, expected {:?})",
27169                e.paths(),
27170                paths.as_slice(),
27171            );
27172            assert_eq!(
27173                e.paths(),
27174                e.paths.as_slice(),
27175                "Entrada::paths accessor and .paths.as_slice() field \
27176                 access must byte-equal — the accessor is the substrate-\
27177                 primitive typed dispatch every downstream per-`:entrada` \
27178                 raw-slot path-list consumer must route through",
27179            );
27180            assert_eq!(
27181                e.paths().len(),
27182                e.paths.len(),
27183                "Entrada::paths().len() must byte-equal self.paths.len() \
27184                 — a length drift would silently split the paired \
27185                 pre-flight cascade-head `.is_empty()` probe input in \
27186                 the sibling [`Entrada::resolved_paths`] resolver from \
27187                 the per-entry validate loop's traversal input in \
27188                 [`AplicacaoSpec::validate`]",
27189            );
27190        }
27191    }
27192
27193    #[test]
27194    fn resolved_paths_reads_through_lifted_paths_accessor() {
27195        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
27196        // pre-flight `.paths().is_empty()` cascade-head probe (which
27197        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
27198        // catch-all fallback arm when the accessor projects the empty
27199        // slice) and the per-entry `.paths().iter().map(String::as_str)`
27200        // projection (which must reach every entry in the same order
27201        // the accessor projects, so the sibling
27202        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
27203        // per-entry projection stay in lockstep by construction) must
27204        // both key off the lifted accessor. Pins the two-site coherence
27205        // by exercising each production consumer end-to-end: (1) the
27206        // catch-all-fallback arm under the empty slice, (2) the
27207        // author-declared-verbatim arm under a two-entry cohort whose
27208        // per-entry projection must byte-equal the input's per-entry
27209        // author-declared paths in the author's declared order.
27210        //
27211        // Peer of the sibling M3
27212        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
27213        // `validate_placement_reads_through_lifted_clusters_accessor`
27214        // on the sibling `Placement::clusters` reader-site convergence.
27215        let empty = entrada_with_paths(vec![]);
27216        assert_eq!(
27217            empty.resolved_paths(),
27218            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
27219            "resolved_paths on empty :entrada :paths must trip the \
27220             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
27221             catch-all fallback — routing through the lifted paths() \
27222             accessor must not silently drop the fallback arm",
27223        );
27224
27225        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
27226        assert_eq!(
27227            declared.resolved_paths(),
27228            vec!["/api/cart", "/api/products"],
27229            "resolved_paths on non-empty :entrada :paths must return each \
27230             entry verbatim in the author's declared order — routing \
27231             through the lifted paths() accessor must not silently \
27232             reorder or drop entries",
27233        );
27234        // Byte-equal pin against the raw-slot accessor to keep the
27235        // fallback-applying resolver's per-entry projection input in
27236        // lockstep with the raw-slot accessor's projection.
27237        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
27238        assert_eq!(
27239            declared.resolved_paths(),
27240            raw_projected,
27241            "resolved_paths non-empty projection must byte-equal the \
27242             lifted paths() accessor's per-entry String::as_str projection \
27243             — the two projections share the same input slice by \
27244             construction, so any drift here would surface a silent \
27245             re-ordering / dedup / normalization detour in the resolver",
27246        );
27247    }
27248
27249    #[test]
27250    fn validate_reads_through_lifted_entrada_paths_accessor() {
27251        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
27252        // per-entry value-shape gate's `for p in e.paths()` traversal
27253        // (which must reach every entry in the same order the accessor
27254        // projects, so both the per-entry `EntradaPathEmpty` /
27255        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
27256        // the duplicate-detection HashSet insert that trips
27257        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
27258        // projection) must route through the lifted accessor. Pins the
27259        // coherence by exercising each production consumer end-to-end:
27260        // (1) the `EntradaPathEmpty` refusal fires on the second entry
27261        // of a two-entry cohort whose head is valid but tail is empty
27262        // (which requires the loop to reach the second entry through
27263        // the accessor), and (2) the `EntradaPathDuplicate` refusal
27264        // fires on the second entry of a two-entry cohort that shares
27265        // a path (which requires the loop to reach both entries — a
27266        // first-entry-only projection would silently pass since the
27267        // dedup HashSet has room for the first insert).
27268        //
27269        // Peer of the sibling
27270        // `validate_placement_reads_through_lifted_clusters_accessor`
27271        // on the sibling `Placement::clusters` reader-site convergence.
27272        let base = crate::AplicacaoSpec {
27273            membros: vec![crate::Membro {
27274                caixa: "cart".into(),
27275                versao: "^0.1".into(),
27276            }],
27277            contratos: Vec::new(),
27278            politicas: crate::MeshPolicy::default(),
27279            placement: crate::Placement {
27280                estrategia: crate::PlacementStrategy::SingleNode,
27281                clusters: vec!["rio".into()],
27282                shard_key: None,
27283                affinity: None,
27284            },
27285            entrada: Some(Entrada {
27286                host: "example.com".into(),
27287                para: "cart".into(),
27288                paths: vec!["/api/cart".into(), String::new()],
27289                port: DEFAULT_SERVICO_PORT,
27290            }),
27291        };
27292        assert_eq!(
27293            base.validate(),
27294            Err(crate::AplicacaoError::EntradaPathEmpty),
27295            "validate must trip EntradaPathEmpty on the second entry of \
27296             a two-entry cohort — routing through the lifted paths() \
27297             accessor must not silently short-circuit the loop at the \
27298             valid head entry",
27299        );
27300
27301        let mut dup = base;
27302        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
27303        assert_eq!(
27304            dup.validate(),
27305            Err(crate::AplicacaoError::EntradaPathDuplicate {
27306                path: "/api/cart".into(),
27307            }),
27308            "validate must trip EntradaPathDuplicate on the second entry \
27309             of a two-entry cohort that shares a path — routing through \
27310             the lifted paths() accessor must not silently short-circuit \
27311             the dedup HashSet insert at the first entry",
27312        );
27313    }
27314
27315    // ── Entrada::hostname / Entrada::hostnames — the substrate-
27316    //    canonical per-`:entrada` DNS-hostname resolver pair every
27317    //    Gateway-API-aware renderer reaching for a per-listener
27318    //    singular `hostname:` filter (Gateway) or a per-route plural
27319    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
27320    //    The three pin tests below fix the two-way accept-set the pair
27321    //    must always honor: (:singular-byte-equal-to-host,
27322    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
27323    //    on any arm surfaces at caixa-core build time rather than at
27324    //    cluster-apply time when the API server refuses the HTTPRoute
27325    //    for non-intersecting hostname filters. Peer discipline with
27326    //    the sibling `resolved_paths` accept-set pin block above on the
27327    //    per-`:entrada` path-list resolver axis.
27328
27329    fn entrada_with_host(host: &str) -> Entrada {
27330        Entrada {
27331            host: host.into(),
27332            para: "cart".into(),
27333            paths: Vec::new(),
27334            port: DEFAULT_SERVICO_PORT,
27335        }
27336    }
27337
27338    #[test]
27339    fn hostname_returns_entrada_host_byte_equal() {
27340        // The canonical singular-axis pin: [`Entrada::hostname`] must
27341        // return the `:entrada :host` field byte-for-byte, borrowed
27342        // from the typed slot's own [`String`] storage. Pins against a
27343        // future silent detour that re-normalized the host (an
27344        // accidental `.to_lowercase()` — validate_entrada_host already
27345        // enforces lowercase, so any re-normalization is redundant + a
27346        // drift surface between the validator and the accessor), a
27347        // trailing-`.` fully-qualified DNS shape substitution, or a
27348        // Punycode round-trip that lowered a Unicode host through IDNA.
27349        let e = entrada_with_host("checkout.quero.cloud");
27350        assert_eq!(
27351            e.hostname(),
27352            "checkout.quero.cloud",
27353            "Entrada::hostname must return :entrada :host verbatim \
27354             (got {:?})",
27355            e.hostname(),
27356        );
27357        assert_eq!(
27358            e.hostname(),
27359            e.host.as_str(),
27360            "Entrada::hostname must byte-equal the .host field access",
27361        );
27362    }
27363
27364    #[test]
27365    fn hostnames_returns_singleton_of_hostname_accessor() {
27366        // The pair-invariant pin: [`Entrada::hostnames`] must always
27367        // return exactly `vec![hostname()]` — the singleton list whose
27368        // sole entry is the substrate's canonical per-`:entrada`
27369        // singular hostname. Pins the two-consumer coherence axis: the
27370        // Gateway listener's singular `hostname:` filter and the
27371        // HTTPRoute's plural `spec.hostnames[]` filter list must
27372        // agree, else the Gateway API v1.x conformance layer rejects
27373        // the HTTPRoute at attach time with
27374        // `Accepted:False/NoMatchingParent` (the parent Gateway's
27375        // listener hostname doesn't intersect the route's hostname
27376        // filter list) — a divergence whose apply-time symptom is far
27377        // from any single-site commit and never surfaces in the
27378        // emitted YAML. Pinning the pair-invariant here makes any
27379        // future accidental split (an accidental `.to_string() + "."`
27380        // trailing-`.` on the plural side that didn't land on the
27381        // singular side, an accidental prefix stripping on one axis,
27382        // an accidental wildcard prepend the SNI fan-out overlay
27383        // authors on the plural side without a paired singular
27384        // migration) trip at caixa-core build time.
27385        let e = entrada_with_host("checkout.quero.cloud");
27386        assert_eq!(
27387            e.hostnames(),
27388            vec![e.hostname()],
27389            "Entrada::hostnames must return `vec![hostname()]` under \
27390             the pair-invariant — got {:?} vs. singleton {:?}",
27391            e.hostnames(),
27392            vec![e.hostname()],
27393        );
27394    }
27395
27396    #[test]
27397    fn hostnames_is_singleton_under_single_host_author_surface() {
27398        // The singleton-shape pin: under today's single-hostname-per-
27399        // `:entrada` author surface (the `:host` slot is a single
27400        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
27401        // must always return a list of length exactly one. Pins
27402        // against a future silent detour that returned an empty list
27403        // (which would emit an HTTPRoute with `spec.hostnames: []` —
27404        // matching every incoming Host header regardless of the
27405        // Aplicacao's declared ingress apex, silently over-matching
27406        // every foreign VirtualHost the parent Gateway also fronts) or
27407        // a duplicated entry (which the Gateway API v1.x parser
27408        // accepts as a `[]-length-2 list of equal hostnames]` but
27409        // whose semantics differ from the intended singleton). The
27410        // author-surface extension point ("a future `:entrada
27411        // :alt-hosts` list overlay" the docstring names) is the sole
27412        // future axis that flips this pin — that migration will re-
27413        // author this test to pin the new plural cardinality.
27414        let e = entrada_with_host("checkout.quero.cloud");
27415        assert_eq!(
27416            e.hostnames().len(),
27417            1,
27418            "Entrada::hostnames must be a singleton under today's \
27419             single-hostname-per-`:entrada` author surface — got \
27420             length {}: {:?}",
27421            e.hostnames().len(),
27422            e.hostnames(),
27423        );
27424    }
27425
27426    // ── Entrada::destination — the substrate-canonical per-`:entrada`
27427    //    destination-Servico scalar accessor every Gateway-API
27428    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
27429    //    discriminator arg (HTTPRoute name composer) or a per-rule
27430    //    `backendRefs[0].name` axis routes through. The two pin tests
27431    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
27432    //    either arm surfaces at caixa-core build time rather than at
27433    //    cluster-apply time when an HTTPRoute's `metadata.name` and
27434    //    `backendRefs[]` silently disagree on which destination Servico
27435    //    the ingress fronts. Peer discipline with the sibling
27436    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
27437    //    blocks above on the per-`:entrada` path-list / DNS-hostname
27438    //    resolver axes.
27439
27440    #[test]
27441    fn destination_returns_entrada_para_byte_equal() {
27442        // The canonical destination-scalar pin: [`Entrada::destination`]
27443        // must return the `:entrada :para` field byte-for-byte, borrowed
27444        // from the typed slot's own [`String`] storage. Pins against a
27445        // future silent detour that re-normalized the destination (an
27446        // accidental `.to_lowercase()` — the destination Servico is
27447        // already validated as a DNS-1123 label upstream, so any
27448        // re-normalization is redundant + a drift surface between the
27449        // validator and the accessor), a namespace-prefix rewrite (an
27450        // accidental `format!("{namespace}/{para}")` per-CR fully-
27451        // qualified rewrite that didn't land on the peer axis), or a
27452        // per-cluster suffix stamp the operator authors on one
27453        // consumer without the other.
27454        for para in ["cart", "checkout", "catalog", "orders-v2"] {
27455            let e = Entrada {
27456                host: "checkout.quero.cloud".into(),
27457                para: para.into(),
27458                paths: Vec::new(),
27459                port: DEFAULT_SERVICO_PORT,
27460            };
27461            assert_eq!(
27462                e.destination(),
27463                para,
27464                "Entrada::destination must return :entrada :para verbatim \
27465                 (got {:?}, expected {para:?})",
27466                e.destination(),
27467            );
27468            assert_eq!(
27469                e.destination(),
27470                e.para.as_str(),
27471                "Entrada::destination must byte-equal the .para field access",
27472            );
27473        }
27474    }
27475
27476    #[test]
27477    fn destination_borrows_from_entrada_para_storage() {
27478        // The borrow-not-copy pin: [`Entrada::destination`] must
27479        // return a `&str` slice that borrows from the typed slot's
27480        // own [`String`] storage — same-address invariant with
27481        // `entrada.para.as_str()`. Pins against a future silent detour
27482        // that allocated a fresh `String` (`self.para.clone()` in the
27483        // body would type-check but silently drop the borrow, and
27484        // every downstream consumer that assumed the returned slice
27485        // outlives `&self` would break on a stale-reference use-after-
27486        // free). Peer with the sibling `hostname_returns_entrada_
27487        // host_byte_equal` on the singular-DNS-hostname axis.
27488        let e = entrada_with_host("checkout.quero.cloud");
27489        let dest = e.destination();
27490        let para_slice = e.para.as_str();
27491        assert_eq!(
27492            dest.as_ptr(),
27493            para_slice.as_ptr(),
27494            "Entrada::destination must borrow from the .para String's \
27495             backing storage — a fresh allocation here means the \
27496             accessor no longer names the substrate-primitive typed \
27497             dispatch and every downstream consumer would silently \
27498             carry a detached copy",
27499        );
27500        assert_eq!(
27501            dest.len(),
27502            para_slice.len(),
27503            "Entrada::destination and .para.as_str() must byte-equal in \
27504             length as well as in address",
27505        );
27506    }
27507
27508    #[test]
27509    fn port_returns_entrada_port_verbatim_across_permutations() {
27510        // The canonical L4-port-scalar pin: [`Entrada::port`] must
27511        // return the `:entrada :port` field verbatim as a `u16` across
27512        // every author-declared value in the validated accept-set
27513        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
27514        // silent detour that clamped the port (an accidental
27515        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
27516        // land on the peer [`AplicacaoSpec::port_for_destination`]
27517        // resolver), rewrote it through a per-cluster port-remap table
27518        // the operator authors on one consumer without the other, or
27519        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
27520        // serde-default value (which would silently collapse the
27521        // distinction between "author explicitly declared `:port 8080`"
27522        // and "author omitted the slot and inherited the default" the
27523        // future per-cluster override slot depends on). Peer with the
27524        // sibling `destination_returns_entrada_para_byte_equal` +
27525        // `hostname_returns_entrada_host_byte_equal` pins on the
27526        // per-`:entrada` `&str` scalar axes.
27527        for port in [
27528            SERVICO_PORT_MIN,
27529            DEFAULT_SERVICO_PORT,
27530            8443u16,
27531            9090u16,
27532            u16::MAX,
27533        ] {
27534            let e = Entrada {
27535                host: "checkout.quero.cloud".into(),
27536                para: "cart".into(),
27537                paths: Vec::new(),
27538                port,
27539            };
27540            assert_eq!(
27541                e.port(),
27542                port,
27543                "Entrada::port must return :entrada :port verbatim \
27544                 (got {}, expected {port})",
27545                e.port(),
27546            );
27547            assert_eq!(
27548                e.port(),
27549                e.port,
27550                "Entrada::port accessor and .port field access must \
27551                 byte-equal — the accessor is the substrate-primitive \
27552                 typed dispatch every downstream L4-port consumer must \
27553                 route through",
27554            );
27555        }
27556    }
27557
27558    #[test]
27559    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
27560        // Two-consumer coherence pin: the
27561        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
27562        // (which reads through [`Entrada::port`] to compare against
27563        // [`SERVICO_PORT_MIN`]) and the
27564        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
27565        // through [`Entrada::port`] to emit the per-destination
27566        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
27567        // lifted accessor, so any future rebrand on the typed slot's
27568        // reader shape lands at exactly one place. Pins the two-site
27569        // coherence by exercising a below-floor port through validate
27570        // (which must reject) and a validated in-accept-set port through
27571        // port_for_destination (which must emit the same value the
27572        // accessor returns).
27573        let mut spec = three_member_spec();
27574        if let Some(e) = spec.entrada.as_mut() {
27575            e.port = 0;
27576        }
27577        assert_eq!(
27578            spec.validate().unwrap_err(),
27579            AplicacaoError::EntradaPortZero,
27580            "validate must reject `:entrada :port 0` through the lifted \
27581             Entrada::port accessor — port zero lies below \
27582             SERVICO_PORT_MIN and the validator routes through port() \
27583             to name the floor",
27584        );
27585
27586        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
27587            let mut spec = three_member_spec();
27588            if let Some(e) = spec.entrada.as_mut() {
27589                e.port = port;
27590            }
27591            spec.validate().expect(
27592                "entrada with in-accept-set :port must validate — the \
27593                 structural-floor gate reads through Entrada::port",
27594            );
27595            let entrada_ref = spec.entrada().expect(":entrada present");
27596            assert_eq!(
27597                spec.port_for_destination(entrada_ref.destination()),
27598                entrada_ref.port(),
27599                "port_for_destination(entrada.destination()) must equal \
27600                 entrada.port() — the two consumers of the per-:entrada \
27601                 L4-port axis (validator, per-destination resolver) both \
27602                 route through Entrada::port",
27603            );
27604        }
27605    }
27606
27607    #[test]
27608    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
27609        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
27610        // must return the `:contratos :de` field byte-for-byte, borrowed
27611        // from the typed slot's own [`String`] storage. Peer of the
27612        // sibling `destination_returns_entrada_para_byte_equal` pin on
27613        // the per-`:entrada` axis — same "the substrate-primitive
27614        // accessor must byte-equal the raw field access verbatim across
27615        // every author-declared value" discipline extended to the
27616        // per-`:contratos` caller arm. Pins against a future silent
27617        // detour that re-normalized the caller (an accidental
27618        // `.to_lowercase()` — every `:contratos :de` is validated as a
27619        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
27620        // re-normalization is redundant + a drift surface between the
27621        // validator and the accessor), a namespace-prefix rewrite (an
27622        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
27623        // rewrite that didn't land on the peer axis), or a per-cluster
27624        // suffix stamp the operator authors on one consumer without the
27625        // other.
27626        for de in ["cart", "checkout", "catalog", "orders-v2"] {
27627            let c = WitContract {
27628                de: de.into(),
27629                para: "downstream".into(),
27630                wit: "wasi:http/proxy".into(),
27631                endpoint: Some("/lookup".into()),
27632                subject: None,
27633                slot: None,
27634            };
27635            assert_eq!(
27636                c.source(),
27637                de,
27638                "WitContract::source must return :contratos :de verbatim \
27639                 (got {:?}, expected {de:?})",
27640                c.source(),
27641            );
27642            assert_eq!(
27643                c.source(),
27644                c.de.as_str(),
27645                "WitContract::source must byte-equal the .de field access",
27646            );
27647        }
27648    }
27649
27650    #[test]
27651    fn wit_contract_source_borrows_from_de_storage() {
27652        // The borrow-not-copy pin: [`WitContract::source`] must return a
27653        // `&str` slice that borrows from the typed slot's own [`String`]
27654        // storage — same-address invariant with `c.de.as_str()`. Pins
27655        // against a future silent detour that allocated a fresh `String`
27656        // (`self.de.clone()` in the body would type-check but silently
27657        // drop the borrow, and every downstream consumer that assumed
27658        // the returned slice outlives `&self` would break on a stale-
27659        // reference use-after-free). Peer of the sibling
27660        // `destination_borrows_from_entrada_para_storage` on the
27661        // per-`:entrada` axis.
27662        let c = WitContract {
27663            de: "cart".into(),
27664            para: "catalog".into(),
27665            wit: "wasi:http/proxy".into(),
27666            endpoint: Some("/lookup".into()),
27667            subject: None,
27668            slot: None,
27669        };
27670        let src = c.source();
27671        let de_slice = c.de.as_str();
27672        assert_eq!(
27673            src.as_ptr(),
27674            de_slice.as_ptr(),
27675            "WitContract::source must borrow from the .de String's \
27676             backing storage — a fresh allocation here means the \
27677             accessor no longer names the substrate-primitive typed \
27678             dispatch and every downstream consumer would silently \
27679             carry a detached copy",
27680        );
27681        assert_eq!(
27682            src.len(),
27683            de_slice.len(),
27684            "WitContract::source and .de.as_str() must byte-equal in \
27685             length as well as in address",
27686        );
27687    }
27688
27689    #[test]
27690    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
27691        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
27692        // must return the `:contratos :para` field byte-for-byte,
27693        // borrowed from the typed slot's own [`String`] storage. Peer of
27694        // the sibling `destination_returns_entrada_para_byte_equal` on
27695        // the per-`:entrada` axis — both accessors name "the destination-
27696        // Servico byte-string" concept on their respective mesh-slot
27697        // atoms (per-ingress apex vs. per-typed-edge callee) and both
27698        // must project the underlying `.para` field verbatim so every
27699        // downstream renderer that composes them with peer accessors
27700        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
27701        // per-edge L4 port emit site) reads the same byte-string the
27702        // author declared.
27703        for para in ["catalog", "payment", "orders", "inventory-v3"] {
27704            let c = WitContract {
27705                de: "cart".into(),
27706                para: para.into(),
27707                wit: "wasi:http/proxy".into(),
27708                endpoint: Some("/lookup".into()),
27709                subject: None,
27710                slot: None,
27711            };
27712            assert_eq!(
27713                c.destination(),
27714                para,
27715                "WitContract::destination must return :contratos :para \
27716                 verbatim (got {:?}, expected {para:?})",
27717                c.destination(),
27718            );
27719            assert_eq!(
27720                c.destination(),
27721                c.para.as_str(),
27722                "WitContract::destination must byte-equal the .para \
27723                 field access",
27724            );
27725        }
27726    }
27727
27728    #[test]
27729    fn wit_contract_destination_borrows_from_para_storage() {
27730        // The borrow-not-copy pin: [`WitContract::destination`] must
27731        // return a `&str` slice that borrows from the typed slot's own
27732        // [`String`] storage — same-address invariant with
27733        // `c.para.as_str()`. Peer of the sibling
27734        // `destination_borrows_from_entrada_para_storage` on the
27735        // per-`:entrada` axis.
27736        let c = WitContract {
27737            de: "cart".into(),
27738            para: "catalog".into(),
27739            wit: "wasi:http/proxy".into(),
27740            endpoint: Some("/lookup".into()),
27741            subject: None,
27742            slot: None,
27743        };
27744        let dest = c.destination();
27745        let para_slice = c.para.as_str();
27746        assert_eq!(
27747            dest.as_ptr(),
27748            para_slice.as_ptr(),
27749            "WitContract::destination must borrow from the .para \
27750             String's backing storage — a fresh allocation here means \
27751             the accessor no longer names the substrate-primitive typed \
27752             dispatch and every downstream consumer would silently \
27753             carry a detached copy",
27754        );
27755        assert_eq!(
27756            dest.len(),
27757            para_slice.len(),
27758            "WitContract::destination and .para.as_str() must byte-equal \
27759             in length as well as in address",
27760        );
27761    }
27762
27763    #[test]
27764    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
27765        // The canonical per-`:contratos` WIT-world-reference scalar pin:
27766        // [`WitContract::world_ref`] must return the `:contratos :wit`
27767        // field byte-for-byte, borrowed from the typed slot's own
27768        // [`String`] storage. Sibling of the peer per-`:contratos`
27769        // [`WitContract::source`] / [`WitContract::destination`]
27770        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
27771        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
27772        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
27773        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
27774        // "the substrate-primitive accessor must byte-equal the raw
27775        // field access verbatim across every author-declared value"
27776        // discipline extended to the per-`:contratos` WIT-world arm.
27777        // Pins against a future silent detour that re-canonicalized the
27778        // WIT world reference (an accidental `.to_lowercase()` pass that
27779        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
27780        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
27781        // gate is already lowercase-prefixed so any re-normalization is
27782        // redundant + a drift surface between the validator and the
27783        // accessor), an M4-promotion-shape rewrite that formatted a
27784        // typed WIT-world enum through [`Display`] and silently drifted
27785        // the printer output from the source `caixa.lisp`, or a per-
27786        // cluster WIT-alias rewrite that didn't land on the peer field-
27787        // access sites. Five values sweep the shape-dispatch accept-set
27788        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
27789        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
27790        // `wasi:keyvalue/`).
27791        for (wit, endpoint, subject, slot) in [
27792            ("wasi:http/proxy", Some("/lookup"), None, None),
27793            ("http:proxy", Some("/health"), None, None),
27794            ("nats:pub-sub", None, Some("orders.paid"), None),
27795            ("kafka:events", None, Some("checkout-events"), None),
27796            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
27797        ] {
27798            let c = WitContract {
27799                de: "cart".into(),
27800                para: "downstream".into(),
27801                wit: wit.into(),
27802                endpoint: endpoint.map(str::to_string),
27803                subject: subject.map(str::to_string),
27804                slot: slot.map(str::to_string),
27805            };
27806            assert_eq!(
27807                c.world_ref(),
27808                wit,
27809                "WitContract::world_ref must return :contratos :wit \
27810                 verbatim (got {:?}, expected {wit:?})",
27811                c.world_ref(),
27812            );
27813            assert_eq!(
27814                c.world_ref(),
27815                c.wit.as_str(),
27816                "WitContract::world_ref must byte-equal the .wit field \
27817                 access",
27818            );
27819        }
27820    }
27821
27822    #[test]
27823    fn wit_contract_world_ref_borrows_from_wit_storage() {
27824        // The borrow-not-copy pin: [`WitContract::world_ref`] must
27825        // return a `&str` slice that borrows from the typed slot's own
27826        // [`String`] storage — same-address invariant with
27827        // `c.wit.as_str()`. Pins against a future silent detour that
27828        // allocated a fresh `String` (`self.wit.clone()` in the body
27829        // would type-check but silently drop the borrow, and every
27830        // downstream consumer that assumed the returned slice outlives
27831        // `&self` would break on a stale-reference use-after-free — the
27832        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
27833        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
27834        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
27835        // / [`is_pubsub`][WitContract::is_pubsub] /
27836        // [`is_store`][WitContract::is_store] methods route through —
27837        // each borrow from the WitContract's own storage and each would
27838        // silently misbehave if this accessor produced a detached copy).
27839        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
27840        // [`WitContract::destination`] and per-`:entrada`
27841        // [`Entrada::destination`] / [`Entrada::hostname`] and
27842        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
27843        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
27844        let c = WitContract {
27845            de: "cart".into(),
27846            para: "catalog".into(),
27847            wit: "wasi:http/proxy".into(),
27848            endpoint: Some("/lookup".into()),
27849            subject: None,
27850            slot: None,
27851        };
27852        let world = c.world_ref();
27853        let wit_slice = c.wit.as_str();
27854        assert_eq!(
27855            world.as_ptr(),
27856            wit_slice.as_ptr(),
27857            "WitContract::world_ref must borrow from the .wit String's \
27858             backing storage — a fresh allocation here means the \
27859             accessor no longer names the substrate-primitive typed \
27860             dispatch and every downstream consumer would silently carry \
27861             a detached copy",
27862        );
27863        assert_eq!(
27864            world.len(),
27865            wit_slice.len(),
27866            "WitContract::world_ref and .wit.as_str() must byte-equal in \
27867             length as well as in address",
27868        );
27869    }
27870
27871    #[test]
27872    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
27873        // Sibling-triple invariant pin composing all three per-`:contratos`
27874        // substrate-primitive typed dispatches — [`WitContract::source`]
27875        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
27876        // [`WitContract::world_ref`] — at the joint
27877        // `(source(), destination(), world_ref())` call shape every
27878        // renderer that fans on per-edge caller-callee-shape identity
27879        // keys off. The invariant, evaluated per-contract:
27880        //
27881        //   (c.source(), c.destination(), c.world_ref())
27882        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
27883        //
27884        // Closes the last unlifted per-`:contratos` scalar axis — every
27885        // downstream consumer that reads the triple now routes through
27886        // exactly three typed dispatches on the substrate primitive,
27887        // not two typed + one open-coded field access. A future refactor
27888        // that silently split any one accessor's projection (an
27889        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
27890        // canonicalization that didn't reach the peer `source`/
27891        // `destination` arms, an accidental `source()` per-cluster
27892        // caller-alias rewrite that didn't land on the `world_ref` peer)
27893        // surfaces at caixa-core build time. Peer of the sibling per-
27894        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
27895        // per-`:entrada` `(hostname(), destination())` (6db982c /
27896        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
27897        // axes, extended to the per-`:contratos` triple.
27898        for (de, para, wit, endpoint, subject, slot) in [
27899            (
27900                "cart",
27901                "catalog",
27902                "wasi:http/proxy",
27903                Some("/lookup"),
27904                None,
27905                None,
27906            ),
27907            (
27908                "checkout",
27909                "orders",
27910                "nats:pub-sub",
27911                None,
27912                Some("orders.paid"),
27913                None,
27914            ),
27915            (
27916                "cart",
27917                "kv",
27918                "wasi:keyvalue/store",
27919                None,
27920                None,
27921                Some("carts/{cart_id}"),
27922            ),
27923            (
27924                "orders-v2",
27925                "inventory-v3",
27926                "http:proxy",
27927                Some("/reserve"),
27928                None,
27929                None,
27930            ),
27931        ] {
27932            let c = WitContract {
27933                de: de.into(),
27934                para: para.into(),
27935                wit: wit.into(),
27936                endpoint: endpoint.map(str::to_string),
27937                subject: subject.map(str::to_string),
27938                slot: slot.map(str::to_string),
27939            };
27940            assert_eq!(
27941                (c.source(), c.destination(), c.world_ref()),
27942                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
27943                "(WitContract::source, ::destination, ::world_ref) must \
27944                 project (.de, .para, .wit) verbatim across every author-\
27945                 declared triple (got ({:?}, {:?}, {:?}), expected \
27946                 ({de:?}, {para:?}, {wit:?}))",
27947                c.source(),
27948                c.destination(),
27949                c.world_ref(),
27950            );
27951        }
27952    }
27953
27954    #[test]
27955    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
27956        // The canonical per-`:contratos` owned-form caller-callee-pair
27957        // pin: [`WitContract::edge_pair`] must return the
27958        // `(source(), destination())` tuple in owned form byte-for-byte,
27959        // projected through the lifted [`WitContract::source`] /
27960        // [`WitContract::destination`] scalar accessors. Pins the
27961        // composite-projection invariant on the per-`:contratos`
27962        // mesh-slot atom — every author-declared `(de, para)` pair must
27963        // round-trip verbatim through the substrate primitive's typed
27964        // dispatch, so the nine [`AplicacaoError`] diagnostic-
27965        // construction sites the accessor now feeds
27966        // ([`AplicacaoError::EmptyWit`],
27967        // [`AplicacaoError::ContratoEndpointEmpty`],
27968        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
27969        // [`AplicacaoError::ContratoEndpointInvalid`],
27970        // [`AplicacaoError::ContratoSubjectEmpty`],
27971        // [`AplicacaoError::ContratoSubjectInvalid`],
27972        // [`AplicacaoError::ContratoSlotEmpty`],
27973        // [`AplicacaoError::ContratoSlotInvalid`],
27974        // [`AplicacaoError::ContratoDuplicate`]) all read the same
27975        // `(de, para)` label pair every author sees at the source
27976        // `caixa.lisp`. Pins against a future silent detour that swapped
27977        // the `.0` / `.1` arms (an accidental `(destination(),
27978        // source())` re-order in the body would silently invert every
27979        // downstream diagnostic's `de:` / `para:` label pair, silently
27980        // reversing the direction of every operator-facing typed error
27981        // arrow), a fresh-allocation shape drift (an accidental
27982        // `.to_string()` on one arm but not the other would leave the
27983        // owned/borrowed pair mismatched vs. the sibling `source()` /
27984        // `destination()` returns), or an M4 per-cluster caller/callee-
27985        // alias rewrite that landed on `source()` without reaching
27986        // `destination()` (or vice versa). Peer of the sibling per-
27987        // `:contratos` `(source, destination, world_ref)` triple
27988        // pin above on the mesh-slot-atom scalar-value axes, extended
27989        // to the owned-form pair-projection axis.
27990        for (de, para, wit, endpoint, subject, slot) in [
27991            (
27992                "cart",
27993                "catalog",
27994                "wasi:http/proxy",
27995                Some("/lookup"),
27996                None,
27997                None,
27998            ),
27999            (
28000                "checkout",
28001                "orders",
28002                "nats:pub-sub",
28003                None,
28004                Some("orders.paid"),
28005                None,
28006            ),
28007            (
28008                "cart",
28009                "kv",
28010                "wasi:keyvalue/store",
28011                None,
28012                None,
28013                Some("carts/{cart_id}"),
28014            ),
28015            (
28016                "orders-v2",
28017                "inventory-v3",
28018                "http:proxy",
28019                Some("/reserve"),
28020                None,
28021                None,
28022            ),
28023        ] {
28024            let c = WitContract {
28025                de: de.into(),
28026                para: para.into(),
28027                wit: wit.into(),
28028                endpoint: endpoint.map(str::to_string),
28029                subject: subject.map(str::to_string),
28030                slot: slot.map(str::to_string),
28031            };
28032            assert_eq!(
28033                c.edge_pair(),
28034                (de.to_string(), para.to_string()),
28035                "WitContract::edge_pair must return (:contratos :de, \
28036                 :contratos :para) as an owned tuple verbatim (got {:?}, \
28037                 expected ({de:?}, {para:?}))",
28038                c.edge_pair(),
28039            );
28040        }
28041    }
28042
28043    #[test]
28044    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
28045        // The composition pin: [`WitContract::edge_pair`] must return
28046        // exactly `(source().to_string(), destination().to_string())` —
28047        // the owned form of the sibling accessor pair — so any future
28048        // refactor that silently re-authored the caller-arm / callee-arm
28049        // projection to bypass the lifted scalar accessors (an accidental
28050        // `(self.de.clone(), self.para.clone())` regression back to the
28051        // raw field-access shape, an M4-typed-caller-enum `Display`
28052        // re-canonicalization on `source()` that didn't reach
28053        // `edge_pair()`, a per-cluster alias rewrite the operator lands
28054        // on `destination()` without reaching this composite projection)
28055        // trips at caixa-core build time. Pins the "typed dispatch
28056        // composes with typed dispatch, not with raw field access"
28057        // discipline every downstream diagnostic-construction site now
28058        // routes through — a `de:` / `para:` label pair whose
28059        // projection silently drifted off the substrate primitive's
28060        // scalar accessors would silently split the diagnostic's self-
28061        // locating signal from the source `caixa.lisp` author's view.
28062        // Peer of the sibling per-`:politicas` `is_empty` /
28063        // `validate_politicas` accessor-routing-pin family on the M3
28064        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
28065        let c = WitContract {
28066            de: "cart".into(),
28067            para: "catalog".into(),
28068            wit: "wasi:http/proxy".into(),
28069            endpoint: Some("/lookup".into()),
28070            subject: None,
28071            slot: None,
28072        };
28073        assert_eq!(
28074            c.edge_pair(),
28075            (c.source().to_string(), c.destination().to_string()),
28076            "WitContract::edge_pair must compose exactly \
28077             (source().to_string(), destination().to_string()) — a \
28078             bypass of either sibling accessor here would silently \
28079             decouple the composite-projection axis from the \
28080             substrate-primitive scalar accessors every downstream \
28081             consumer routes through",
28082        );
28083    }
28084
28085    #[test]
28086    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
28087     {
28088        // The canonical per-`:contratos` owned-form
28089        // caller-callee-world-ref-triple pin:
28090        // [`WitContract::edge_triple`] must return the
28091        // `(source(), destination(), world_ref())` tuple in owned form
28092        // byte-for-byte, projected through the lifted
28093        // [`WitContract::source`] / [`WitContract::destination`] /
28094        // [`WitContract::world_ref`] scalar accessors. Pins the
28095        // composite-projection invariant on the per-`:contratos`
28096        // mesh-slot atom — every author-declared `(de, para, wit)`
28097        // triple must round-trip verbatim through the substrate
28098        // primitive's typed dispatch, so the nine
28099        // [`AplicacaoError`] diagnostic-construction sites the
28100        // accessor now feeds (the [`WitTarget`]-dispatch's eight
28101        // wrong-target / missing-target / invalid-wit / capability-
28102        // with-payload arms in [`WitContract::target`], plus the
28103        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
28104        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
28105        // read the same `(de, para, wit)` triple every author sees at
28106        // the source `caixa.lisp`. Pins against a future silent
28107        // detour that swapped any two arms (an accidental `(destination(),
28108        // source(), world_ref())` re-order in the body would silently
28109        // invert every downstream diagnostic's `de:` / `para:` label
28110        // pair, silently reversing the direction of every operator-
28111        // facing typed error arrow), a fresh-allocation shape drift
28112        // (an accidental `.to_string()` skipped on one arm would leave
28113        // the owned/borrowed triple mismatched vs. the sibling
28114        // `source()` / `destination()` / `world_ref()` returns), or an
28115        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
28116        // canonicalization pass that landed on one accessor without
28117        // reaching the peers. Peer of the sibling per-`:contratos`
28118        // caller-callee-pair
28119        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
28120        // pin on the mesh-slot-atom composite-projection axis,
28121        // extended to the triple-projection axis.
28122        for (de, para, wit, endpoint, subject, slot) in [
28123            (
28124                "cart",
28125                "catalog",
28126                "wasi:http/proxy",
28127                Some("/lookup"),
28128                None,
28129                None,
28130            ),
28131            (
28132                "checkout",
28133                "orders",
28134                "nats:pub-sub",
28135                None,
28136                Some("orders.paid"),
28137                None,
28138            ),
28139            (
28140                "cart",
28141                "kv",
28142                "wasi:keyvalue/store",
28143                None,
28144                None,
28145                Some("carts/{cart_id}"),
28146            ),
28147            (
28148                "orders-v2",
28149                "inventory-v3",
28150                "http:proxy",
28151                Some("/reserve"),
28152                None,
28153                None,
28154            ),
28155        ] {
28156            let c = WitContract {
28157                de: de.into(),
28158                para: para.into(),
28159                wit: wit.into(),
28160                endpoint: endpoint.map(str::to_string),
28161                subject: subject.map(str::to_string),
28162                slot: slot.map(str::to_string),
28163            };
28164            assert_eq!(
28165                c.edge_triple(),
28166                (de.to_string(), para.to_string(), wit.to_string()),
28167                "WitContract::edge_triple must return (:contratos :de, \
28168                 :contratos :para, :contratos :wit) as an owned triple \
28169                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
28170                c.edge_triple(),
28171            );
28172        }
28173    }
28174
28175    #[test]
28176    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
28177        // The composition pin: [`WitContract::edge_triple`] must return
28178        // exactly `(source().to_string(), destination().to_string(),
28179        // world_ref().to_string())` — the owned form of the sibling
28180        // scalar-accessor triple — so any future refactor that silently
28181        // re-authored one arm's projection to bypass the lifted scalar
28182        // accessors (an accidental `(self.de.clone(), self.para.clone(),
28183        // self.wit.clone())` regression back to the raw field-access
28184        // shape the internal `edge` closure and the ContratoDuplicate
28185        // diagnostic both carried before this lift landed, an
28186        // M4-typed-caller-enum `Display` re-canonicalization on
28187        // `source()` that didn't reach `edge_triple()`, a per-cluster
28188        // alias rewrite the operator lands on `destination()` /
28189        // `world_ref()` without reaching this composite projection)
28190        // trips at caixa-core build time. Pins the "typed dispatch
28191        // composes with typed dispatch, not with raw field access"
28192        // discipline every downstream diagnostic-construction site now
28193        // routes through — a `de:` / `para:` / `wit:` triple whose
28194        // projection silently drifted off the substrate primitive's
28195        // scalar accessors would silently split the diagnostic's self-
28196        // locating signal from the source `caixa.lisp` author's view.
28197        // Peer of the sibling per-`:contratos` edge_pair composition-
28198        // pin above on the mesh-slot-atom composite-projection axis.
28199        let c = WitContract {
28200            de: "cart".into(),
28201            para: "catalog".into(),
28202            wit: "wasi:http/proxy".into(),
28203            endpoint: Some("/lookup".into()),
28204            subject: None,
28205            slot: None,
28206        };
28207        assert_eq!(
28208            c.edge_triple(),
28209            (
28210                c.source().to_string(),
28211                c.destination().to_string(),
28212                c.world_ref().to_string(),
28213            ),
28214            "WitContract::edge_triple must compose exactly \
28215             (source().to_string(), destination().to_string(), \
28216             world_ref().to_string()) — a bypass of any sibling accessor \
28217             here would silently decouple the composite-projection axis \
28218             from the substrate-primitive scalar accessors every \
28219             downstream consumer routes through",
28220        );
28221    }
28222
28223    #[test]
28224    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
28225        // The canonical semantics-pin: [`WitContract::edge_triple`] must
28226        // project the full `(de, para, wit)` identity of a `:contratos`
28227        // edge — the sub-triple every triple-carrying
28228        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
28229        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
28230        // missing-target, capability-with-payload, invalid-wit, and the
28231        // duplicate-gate). Rejects a drift in shape (an accidental
28232        // silent detour that returned a `(de, para)` pair or added an
28233        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
28234        // would trip here because the return type would no longer
28235        // pattern-match the eight `let (de, para, wit) = edge();`
28236        // destructures the [`WitContract::target`] dispatch feeds off
28237        // + the paired duplicate-gate `let (de, para, wit) =
28238        // c.edge_triple();` destructure in
28239        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
28240        // `:contratos` caller-callee-pair pin above extended to the
28241        // triple projection surface: closes the "one composite
28242        // accessor per typed diagnostic-construction sub-tuple"
28243        // discipline on the per-`:contratos` mesh-slot-atom axis.
28244        let c = WitContract {
28245            de: "checkout".into(),
28246            para: "orders".into(),
28247            wit: "nats:pub-sub".into(),
28248            endpoint: None,
28249            subject: Some("orders.paid".into()),
28250            slot: None,
28251        };
28252        let (de, para, wit) = c.edge_triple();
28253        assert_eq!(de, "checkout");
28254        assert_eq!(para, "orders");
28255        assert_eq!(wit, "nats:pub-sub");
28256    }
28257
28258    #[test]
28259    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
28260     {
28261        // The composition pin: [`WitContract::identity`] must return
28262        // exactly `(source(), destination(), world_ref(), endpoint(),
28263        // subject(), slot())` — the borrowed form of the six-scalar-
28264        // accessor identity axis. Any future refactor that silently
28265        // re-authored one arm's projection to bypass a scalar accessor
28266        // (a `self.de.as_str()` regression back to raw field access on
28267        // any of the three required arms, a `self.endpoint.as_deref()`
28268        // regression on any of the three optional arms, an M4 per-
28269        // cluster caller/callee-alias rewrite the operator lands on
28270        // `source()` / `destination()` without reaching this composite
28271        // projection) trips at caixa-core build time. Sweeps four
28272        // permutations of the WIT-shape × payload lattice — HTTP with
28273        // endpoint, pub-sub with subject, store with slot, payload-less
28274        // capability — so every payload arm is exercised. Peer of the
28275        // sibling per-`:contratos`
28276        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
28277        // composition pin on the mesh-slot-atom composite-projection
28278        // axis; extends the discipline from the (de, para, wit) prefix
28279        // onto the full-identity axis carrying the three payload arms.
28280        for (de, para, wit, endpoint, subject, slot) in [
28281            (
28282                "cart",
28283                "catalog",
28284                "wasi:http/proxy",
28285                Some("/lookup"),
28286                None,
28287                None,
28288            ),
28289            (
28290                "checkout",
28291                "orders",
28292                "nats:pub-sub",
28293                None,
28294                Some("orders.paid"),
28295                None,
28296            ),
28297            (
28298                "cart",
28299                "kv",
28300                "wasi:keyvalue/store",
28301                None,
28302                None,
28303                Some("carts/{cart_id}"),
28304            ),
28305            ("audit", "sink", "wasi:logging", None, None, None),
28306        ] {
28307            let c = WitContract {
28308                de: de.into(),
28309                para: para.into(),
28310                wit: wit.into(),
28311                endpoint: endpoint.map(str::to_owned),
28312                subject: subject.map(str::to_owned),
28313                slot: slot.map(str::to_owned),
28314            };
28315            assert_eq!(
28316                c.identity(),
28317                (
28318                    c.source(),
28319                    c.destination(),
28320                    c.world_ref(),
28321                    c.endpoint(),
28322                    c.subject(),
28323                    c.slot(),
28324                ),
28325                "WitContract::identity must compose exactly \
28326                 (source(), destination(), world_ref(), endpoint(), \
28327                 subject(), slot()) — a bypass of any sibling accessor \
28328                 here would silently decouple the identity-projection \
28329                 axis from the substrate-primitive scalar accessors \
28330                 every dedup-key consumer routes through",
28331            );
28332        }
28333    }
28334
28335    #[test]
28336    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
28337        // The canonical semantics-pin: [`WitContract::identity`] must
28338        // project the six-axis (de, para, wit, endpoint, subject, slot)
28339        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
28340        // gate keys off — two `WitContract`s that agree on all six axes
28341        // are the same typed edge declared twice, the graph-edge
28342        // analogue of duplicate `:membros` / `:placement :clusters` /
28343        // `:entrada :paths` entries. Rejects a shape drift (an
28344        // accidental silent detour that returned a prefix tuple or
28345        // added an extra field) by pattern-matching the six-arm shape.
28346        // Peer of the sibling per-`:contratos`
28347        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
28348        // pin extended from the (de, para, wit) prefix onto the full
28349        // six-axis identity that the dedup key rides.
28350        let c = WitContract {
28351            de: "cart".into(),
28352            para: "catalog".into(),
28353            wit: "wasi:http/proxy".into(),
28354            endpoint: Some("/products/:id".into()),
28355            subject: None,
28356            slot: None,
28357        };
28358        let (de, para, wit, endpoint, subject, slot) = c.identity();
28359        assert_eq!(de, "cart");
28360        assert_eq!(para, "catalog");
28361        assert_eq!(wit, "wasi:http/proxy");
28362        assert_eq!(endpoint, Some("/products/:id"));
28363        assert_eq!(subject, None);
28364        assert_eq!(slot, None);
28365
28366        // Two byte-identical contracts must produce equal identities —
28367        // the dedup key's foundational invariant.
28368        let c2 = c.clone();
28369        assert_eq!(c.identity(), c2.identity());
28370
28371        // Any change on any of the six axes must break the identity —
28372        // sweeps by mutating one axis at a time.
28373        let mut mutated = c.clone();
28374        mutated.de = "search".into();
28375        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
28376        let mut mutated = c.clone();
28377        mutated.para = "warehouse".into();
28378        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
28379        let mut mutated = c.clone();
28380        mutated.wit = "http:legacy".into();
28381        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
28382        let mut mutated = c.clone();
28383        mutated.endpoint = Some("/search".into());
28384        assert_ne!(
28385            c.identity(),
28386            mutated.identity(),
28387            "endpoint axis must partition"
28388        );
28389        let mut mutated = c.clone();
28390        mutated.subject = Some("orders.paid".into());
28391        assert_ne!(
28392            c.identity(),
28393            mutated.identity(),
28394            "subject axis must partition"
28395        );
28396        let mut mutated = c;
28397        mutated.slot = Some("carts/{id}".into());
28398        assert_ne!(mutated.identity().5, None, "slot axis must partition");
28399    }
28400
28401    #[test]
28402    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
28403        // The canonical per-`:contratos` structural-self-edge pin:
28404        // [`WitContract::is_self_loop`] must return `true` when the
28405        // `:de` and `:para` fields agree byte-for-byte, across every
28406        // WIT-shape variant the per-edge shape family carries. Pins
28407        // the shape-agnostic identity-space partition the
28408        // [`AplicacaoSpec::validate`] self-edge gate at
28409        // caixa-core/src/aplicacao.rs:5559 fires against — all four
28410        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
28411        // under the same one predicate. Four permutations sweep the
28412        // accept-set: HTTP with endpoint, pub-sub with subject, KV
28413        // store with slot, and payload-less capability.
28414        for (nome, wit, endpoint, subject, slot) in [
28415            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
28416            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
28417            (
28418                "kv",
28419                "wasi:keyvalue/store",
28420                None,
28421                None,
28422                Some("carts/{cart_id}"),
28423            ),
28424            ("audit", "wasi:logging", None, None, None),
28425        ] {
28426            let c = WitContract {
28427                de: nome.into(),
28428                para: nome.into(),
28429                wit: wit.into(),
28430                endpoint: endpoint.map(str::to_string),
28431                subject: subject.map(str::to_string),
28432                slot: slot.map(str::to_string),
28433            };
28434            assert!(
28435                c.is_self_loop(),
28436                "WitContract::is_self_loop must return true when \
28437                 :contratos :de == :contratos :para (got false on \
28438                 {nome:?} under {wit:?})",
28439            );
28440        }
28441    }
28442
28443    #[test]
28444    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
28445        // The complement pin: [`WitContract::is_self_loop`] must return
28446        // `false` on every well-shaped inter-Servico contract (the
28447        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
28448        // names — "Servico A calls Servico B" between two distinct
28449        // graph nodes). Pins against a future silent detour that
28450        // inverted the predicate (an accidental `!= ` swap for `==`
28451        // would silently reject every legitimate inter-Servico edge
28452        // and admit every self-edge — the exact inversion of the
28453        // author-intended shape). Four permutations sweep the same
28454        // WIT-shape accept-set the sibling positive-arm test carries.
28455        for (de, para, wit, endpoint, subject, slot) in [
28456            (
28457                "cart",
28458                "catalog",
28459                "wasi:http/proxy",
28460                Some("/lookup"),
28461                None,
28462                None,
28463            ),
28464            (
28465                "checkout",
28466                "orders",
28467                "nats:pub-sub",
28468                None,
28469                Some("orders.paid"),
28470                None,
28471            ),
28472            (
28473                "cart",
28474                "kv",
28475                "wasi:keyvalue/store",
28476                None,
28477                None,
28478                Some("carts/{cart_id}"),
28479            ),
28480            ("audit", "sink", "wasi:logging", None, None, None),
28481        ] {
28482            let c = WitContract {
28483                de: de.into(),
28484                para: para.into(),
28485                wit: wit.into(),
28486                endpoint: endpoint.map(str::to_string),
28487                subject: subject.map(str::to_string),
28488                slot: slot.map(str::to_string),
28489            };
28490            assert!(
28491                !c.is_self_loop(),
28492                "WitContract::is_self_loop must return false when \
28493                 :contratos :de differs from :contratos :para (got true \
28494                 on {de:?} → {para:?} under {wit:?})",
28495            );
28496        }
28497    }
28498
28499    #[test]
28500    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
28501        // The composition pin: [`WitContract::is_self_loop`] must
28502        // resolve to exactly `self.source() == self.destination()` —
28503        // the equality probe of the sibling scalar-accessor pair — so
28504        // any future refactor that silently re-authored the predicate
28505        // to bypass the lifted scalar accessors (an accidental
28506        // `self.de == self.para` regression back to the raw field-
28507        // access shape, an M4-typed-caller-enum identity-comparison
28508        // rule that landed on `source()` without reaching
28509        // `destination()`, a per-cluster alias rewrite the operator
28510        // pins on `destination()` without reaching this predicate)
28511        // trips at caixa-core build time. Pins the "typed dispatch
28512        // composes with typed dispatch, not with raw field access"
28513        // discipline the sibling [`WitContract::edge_pair`] /
28514        // [`WitContract::edge_triple`] composite-projection accessors
28515        // already carry, extended onto the per-edge endpoint-equality
28516        // predicate axis. Positive and complement arms both fire.
28517        let self_edge = WitContract {
28518            de: "cart".into(),
28519            para: "cart".into(),
28520            wit: "wasi:http/proxy".into(),
28521            endpoint: Some("/lookup".into()),
28522            subject: None,
28523            slot: None,
28524        };
28525        assert_eq!(
28526            self_edge.is_self_loop(),
28527            self_edge.source() == self_edge.destination(),
28528            "WitContract::is_self_loop must compose exactly \
28529             `source() == destination()` — a bypass of either sibling \
28530             accessor here would silently decouple the endpoint-\
28531             equality predicate from the substrate-primitive scalar \
28532             accessors every downstream consumer routes through",
28533        );
28534        let inter_edge = WitContract {
28535            de: "cart".into(),
28536            para: "catalog".into(),
28537            wit: "wasi:http/proxy".into(),
28538            endpoint: Some("/lookup".into()),
28539            subject: None,
28540            slot: None,
28541        };
28542        assert_eq!(
28543            inter_edge.is_self_loop(),
28544            inter_edge.source() == inter_edge.destination(),
28545            "WitContract::is_self_loop must compose exactly \
28546             `source() == destination()` on the complement arm too",
28547        );
28548    }
28549
28550    #[test]
28551    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
28552        // The composition pin: [`WitContract::target`]'s invalid-wit
28553        // value-shape gate must feed the reason string through the
28554        // lifted [`WitContract::world_ref`] scalar accessor — the same
28555        // typed dispatch on the substrate primitive every peer
28556        // per-`:contratos` payload-carrier extraction in the same
28557        // method body already routes through
28558        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
28559        // [`WitContract::subject`] on the pub-sub-arm target extraction,
28560        // [`WitContract::slot`] on the store-arm target extraction) and
28561        // every peer composite-projection accessor
28562        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
28563        // [`WitContract::identity`]) already composes from. Any future
28564        // refactor that silently re-authored the gate to bypass the
28565        // lifted accessor (an accidental `&self.wit` regression back to
28566        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
28567        // re-canonicalization on `world_ref()` that didn't reach this
28568        // gate, a per-CR lowercasing canonicalization pass the M4
28569        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
28570        // per-tenant that lands on `world_ref()` without reaching this
28571        // gate) would silently split the invalid-wit diagnostic reason
28572        // from the substrate-primitive projection every downstream
28573        // consumer routes through. Same "typed dispatch composes with
28574        // typed dispatch, not with raw field access" discipline the
28575        // sibling
28576        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
28577        // pin already carries on the endpoint-equality predicate axis,
28578        // extended onto the invalid-wit value-shape gate axis inside
28579        // the same [`WitContract::target`] body. Closes the last
28580        // unlifted raw-field-access site inside `impl WitContract`.
28581        //
28582        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
28583        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
28584        // to a capability-only edge; the value-shape gate rejects it
28585        // through [`crate::render::is_wit_world_ref`] on the substrate
28586        // primitive's ASCII-lowercase-only accept-set, with a
28587        // parser-shaped reason string the test asserts round-trips
28588        // byte-for-byte between the direct-dispatch call (through the
28589        // predicate on the accessor's projection) and the
28590        // [`WitContract::target`] gate's produced reason field.
28591        let c = WitContract {
28592            de: "cart".into(),
28593            para: "catalog".into(),
28594            wit: "WASI:HTTP/proxy".into(),
28595            endpoint: Some("/lookup".into()),
28596            subject: None,
28597            slot: None,
28598        };
28599        let err = c.target().unwrap_err();
28600        let AplicacaoError::ContratoWitInvalid {
28601            ref de,
28602            ref para,
28603            ref wit,
28604            ref reason,
28605        } = err
28606        else {
28607            panic!("expected ContratoWitInvalid, got {err:?}");
28608        };
28609        assert_eq!(de, "cart");
28610        assert_eq!(para, "catalog");
28611        assert_eq!(wit, "WASI:HTTP/proxy");
28612        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
28613        assert_eq!(
28614            *reason, expected_reason,
28615            "WitContract::target's invalid-wit value-shape gate reason \
28616             must compose exactly is_wit_world_ref(self.world_ref()) — \
28617             a bypass here (e.g. a raw `&self.wit` field-access \
28618             regression, or a divergent predicate on a different \
28619             projection) would silently decouple the invalid-wit \
28620             diagnostic's reason field from the substrate-primitive \
28621             scalar accessor every peer per-`:contratos` extraction in \
28622             the same method body already routes through",
28623        );
28624    }
28625
28626    #[test]
28627    fn wit_contract_is_self_loop_predicate_is_const_fn() {
28628        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
28629        // caller-callee identity-space predicate's `const`-eval-surface
28630        // posture. The wrapper below dispatches through
28631        // [`WitContract::is_self_loop`] and is well-formed only when the
28632        // callee is itself `pub const fn` — any future accidental
28633        // downgrade to non-`const` fails the wrapper at caixa-core build
28634        // time with E0015 (`cannot call non-const method`), strictly
28635        // stronger than a runtime `assert!` and strictly stronger than a
28636        // module-scope `const _: () = assert!(…)` pin (the type's
28637        // `String` / `Option<String>` carriers rule out `const`-context
28638        // value construction; the `const fn` wrapper is the load-bearing
28639        // shape that side-steps the destructor-in-const restriction on
28640        // the value axis while still pinning the `const`-fn posture on
28641        // the callee — mirror of the sibling
28642        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
28643        // (279823b) and
28644        // [`wit_contract_identity_projection_accessor_is_const_fn`]
28645        // (1ab648c) pins' discipline verbatim on the peer scalar-
28646        // accessor and composite-projection surfaces). Closes the last
28647        // unlifted per-`:contratos` shape/identity predicate on the
28648        // const-eval surface — the peer WIT-shape-partition family
28649        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
28650        // [`WitContract::is_store`] / [`WitContract::is_capability`]
28651        // already carried the `pub const fn` posture on the peer
28652        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
28653        // this pin extends the same posture onto the caller-callee
28654        // identity-space partition. Sweeps every WIT-shape arm on both
28655        // the equal-endpoints (self-edge) and distinct-endpoints
28656        // (inter-edge) arms of the identity-space partition, plus one
28657        // same-length distinct-byte pair to pin the mid-loop `!=` arm
28658        // past the leading length-mismatch shortcut.
28659        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
28660            c.is_self_loop()
28661        }
28662        let mk = |de: &str, para: &str, wit: &str| WitContract {
28663            de: de.into(),
28664            para: para.into(),
28665            wit: wit.into(),
28666            endpoint: None,
28667            subject: None,
28668            slot: None,
28669        };
28670        for (nome, wit) in [
28671            ("cart", "wasi:http/proxy"),
28672            ("checkout", "nats:pub-sub"),
28673            ("kv", "wasi:keyvalue/store"),
28674            ("audit", "wasi:logging"),
28675        ] {
28676            let self_edge = mk(nome, nome, wit);
28677            assert!(
28678                is_self_loop_via_const_fn(&self_edge),
28679                "self-edge {nome:?} under {wit:?}"
28680            );
28681            assert_eq!(
28682                is_self_loop_via_const_fn(&self_edge),
28683                self_edge.is_self_loop()
28684            );
28685        }
28686        for (de, para, wit) in [
28687            ("cart", "catalog", "wasi:http/proxy"),
28688            ("checkout", "orders", "nats:pub-sub"),
28689            ("cart", "kv", "wasi:keyvalue/store"),
28690            ("audit", "sink", "wasi:logging"),
28691        ] {
28692            let inter_edge = mk(de, para, wit);
28693            assert!(
28694                !is_self_loop_via_const_fn(&inter_edge),
28695                "inter-edge {de:?}→{para:?} under {wit:?}",
28696            );
28697            assert_eq!(
28698                is_self_loop_via_const_fn(&inter_edge),
28699                inter_edge.is_self_loop()
28700            );
28701        }
28702        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
28703        // past the leading `a.len() != b.len()` shortcut so the const-fn
28704        // wrapper exercises every arm of the byte-slice equality loop.
28705        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
28706        assert!(
28707            !is_self_loop_via_const_fn(&same_len_pair),
28708            "same-length distinct-byte"
28709        );
28710        assert_eq!(
28711            is_self_loop_via_const_fn(&same_len_pair),
28712            same_len_pair.is_self_loop()
28713        );
28714    }
28715
28716    #[test]
28717    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
28718        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
28719        // pin: [`WitContract::endpoint`] must return the `:contratos
28720        // :endpoint` field byte-for-byte, borrowed from the typed slot's
28721        // own `Option<String>` storage. Peer of the sibling
28722        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
28723        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
28724        // mesh-slot `Option<String>` optional-scalar axes — same "the
28725        // substrate-primitive accessor must byte-equal the raw field
28726        // access verbatim across every author-declared value" discipline
28727        // extended to the per-`:contratos` HTTP-payload-carrier arm.
28728        // Pins against a future silent detour that re-canonicalized the
28729        // endpoint (an accidental percent-encoding pass that didn't
28730        // reach the peer field-access site at the dedup key, a per-CR
28731        // fully-qualified prefix rewrite the operator authors on one
28732        // consumer without the other, or an M4 typed-path-template
28733        // `Display` re-canonicalization that silently drifted the
28734        // printer output from the source `caixa.lisp`). Four values
28735        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
28736        // gate upstream admits (short root-path, dashed, param-shaped,
28737        // deep-hierarchy).
28738        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
28739            let c = WitContract {
28740                de: "cart".into(),
28741                para: "catalog".into(),
28742                wit: "wasi:http/proxy".into(),
28743                endpoint: Some(endpoint.into()),
28744                subject: None,
28745                slot: None,
28746            };
28747            assert_eq!(
28748                c.endpoint(),
28749                Some(endpoint),
28750                "WitContract::endpoint must return :contratos :endpoint \
28751                 verbatim (got {:?}, expected Some({endpoint:?}))",
28752                c.endpoint(),
28753            );
28754            assert_eq!(
28755                c.endpoint(),
28756                c.endpoint.as_deref(),
28757                "WitContract::endpoint must byte-equal the .endpoint \
28758                 field's `.as_deref()` projection",
28759            );
28760        }
28761    }
28762
28763    #[test]
28764    fn wit_contract_endpoint_none_when_field_is_none() {
28765        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
28766        // payload-carrier accessor pin: when the typed slot is absent —
28767        // the canonical shape under a non-HTTP `:wit` world per the
28768        // [`WitContract::target`]-enforced shape ↔ target partition
28769        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
28770        // carries `:slot`, [`WitTarget::Capability`] carries none) —
28771        // [`WitContract::endpoint`] must return `None`. Pins against a
28772        // future silent detour that projected the absent slot to a
28773        // `Some("")` empty-string default (the canonical `Option<String>`
28774        // → `String` collapse footgun the sibling M2
28775        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
28776        // emptiness predicates already guard on the peer M2 typed-slot
28777        // surfaces), a `Some("None")` stringified-None round-trip, or a
28778        // `Some` arm whose contents were derived from a sibling slot (an
28779        // accidental fallback to the `:subject` / `:slot` payload that
28780        // read the pub-sub / store payload into the endpoint axis).
28781        // Three contracts sweep the accept-set every non-HTTP `:wit`
28782        // world lands on — pub-sub NATS, key/value, and payload-less
28783        // capability.
28784        for (wit, subject, slot) in [
28785            ("nats:pub-sub", Some("orders.paid"), None),
28786            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
28787            ("wasi:cli/environment", None, None),
28788        ] {
28789            let c = WitContract {
28790                de: "cart".into(),
28791                para: "downstream".into(),
28792                wit: wit.into(),
28793                endpoint: None,
28794                subject: subject.map(str::to_string),
28795                slot: slot.map(str::to_string),
28796            };
28797            assert!(
28798                c.endpoint().is_none(),
28799                "WitContract::endpoint must return None when the typed \
28800                 slot is absent under :wit {wit:?} (got {:?})",
28801                c.endpoint(),
28802            );
28803            assert_eq!(
28804                c.endpoint(),
28805                c.endpoint.as_deref(),
28806                "WitContract::endpoint must byte-equal the .endpoint \
28807                 field's `.as_deref()` projection in the absent arm",
28808            );
28809        }
28810    }
28811
28812    #[test]
28813    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
28814        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
28815        // an `Option<&str>` whose `Some` arm borrows from the typed
28816        // slot's own [`String`] storage — same-address invariant with
28817        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
28818        // detour that allocated a fresh `String`
28819        // (`self.endpoint.clone().map(...)` in the body would type-check
28820        // but silently drop the borrow, and every downstream consumer
28821        // that assumed the returned slice outlives `&self` would break
28822        // on a stale-reference use-after-free — the [`WitContract::target`]
28823        // Http-arm payload extraction rebinds the returned `Option<&str>`
28824        // through `.ok_or_else(...)` and threads the `&str` payload into
28825        // [`WitTarget::Http { endpoint: &'a str }`], the
28826        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
28827        // [`ContratoIdentity`] dedup key threads the returned
28828        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
28829        // from the WitContract's own storage and each would silently
28830        // misbehave if this accessor produced a detached copy). Peer of
28831        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
28832        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
28833        // shaped optional-scalar axes — first extension of the
28834        // `Option<&str>` borrow-not-copy discipline onto the
28835        // per-`:contratos` HTTP-shaped payload-carrier axis.
28836        let c = WitContract {
28837            de: "cart".into(),
28838            para: "catalog".into(),
28839            wit: "wasi:http/proxy".into(),
28840            endpoint: Some("/lookup".into()),
28841            subject: None,
28842            slot: None,
28843        };
28844        let ep = c.endpoint().expect("Some arm");
28845        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
28846        assert_eq!(
28847            ep.as_ptr(),
28848            storage_slice.as_ptr(),
28849            "WitContract::endpoint must borrow from the .endpoint \
28850             String's backing storage — a fresh allocation here means \
28851             the accessor no longer names the substrate-primitive typed \
28852             dispatch and every downstream consumer would silently \
28853             carry a detached copy",
28854        );
28855        assert_eq!(
28856            ep.len(),
28857            storage_slice.len(),
28858            "WitContract::endpoint and .endpoint.as_deref() must byte-\
28859             equal in length as well as in address",
28860        );
28861    }
28862
28863    #[test]
28864    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
28865        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
28866        // pin: [`WitContract::subject`] must return the `:contratos
28867        // :subject` field byte-for-byte, borrowed from the typed slot's
28868        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
28869        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
28870        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
28871        // optional-scalar axis — same "the substrate-primitive accessor
28872        // must byte-equal the raw field access verbatim across every
28873        // author-declared value" discipline extended to the pub-sub arm.
28874        // Pins against a future silent detour that re-canonicalized the
28875        // subject (an accidental `.to_lowercase()` normalization that
28876        // didn't reach the peer field-access site at the dedup key, a
28877        // per-CR fully-qualified prefix rewrite the operator authors on
28878        // one consumer without the other, or an M4 typed-subject-template
28879        // `Display` re-canonicalization that silently drifted the printer
28880        // output from the source `caixa.lisp`). Four values sweep the
28881        // NATS accept-set every pub-sub author-declared subject lands on
28882        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
28883        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
28884            let c = WitContract {
28885                de: "cart".into(),
28886                para: "notifier".into(),
28887                wit: "nats:pub-sub".into(),
28888                endpoint: None,
28889                subject: Some(subject.into()),
28890                slot: None,
28891            };
28892            assert_eq!(
28893                c.subject(),
28894                Some(subject),
28895                "WitContract::subject must return :contratos :subject \
28896                 verbatim (got {:?}, expected Some({subject:?}))",
28897                c.subject(),
28898            );
28899            assert_eq!(
28900                c.subject(),
28901                c.subject.as_deref(),
28902                "WitContract::subject must byte-equal the .subject \
28903                 field's `.as_deref()` projection",
28904            );
28905        }
28906    }
28907
28908    #[test]
28909    fn wit_contract_subject_none_when_field_is_none() {
28910        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
28911        // shaped payload-carrier accessor pin: when the typed slot is
28912        // absent — the canonical shape under a non-pub-sub `:wit` world
28913        // per the [`WitContract::target`]-enforced shape ↔ target
28914        // partition ([`WitTarget::Http`] carries `:endpoint`,
28915        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
28916        // carries none) — [`WitContract::subject`] must return `None`.
28917        // Pins against a future silent detour that projected the absent
28918        // slot to a `Some("")` empty-string default (the canonical
28919        // `Option<String>` → `String` collapse footgun the sibling M2
28920        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
28921        // emptiness predicates already guard on the peer M2 typed-slot
28922        // surfaces), a `Some("None")` stringified-None round-trip, or a
28923        // `Some` arm whose contents were derived from a sibling slot (an
28924        // accidental fallback to the `:endpoint` / `:slot` payload that
28925        // read the HTTP / store payload into the subject axis). Three
28926        // contracts sweep the accept-set every non-pub-sub `:wit` world
28927        // lands on — HTTP proxy, key/value store, and payload-less
28928        // capability.
28929        for (wit, endpoint, slot) in [
28930            ("wasi:http/proxy", Some("/lookup"), None),
28931            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
28932            ("wasi:cli/environment", None, None),
28933        ] {
28934            let c = WitContract {
28935                de: "cart".into(),
28936                para: "downstream".into(),
28937                wit: wit.into(),
28938                endpoint: endpoint.map(str::to_string),
28939                subject: None,
28940                slot: slot.map(str::to_string),
28941            };
28942            assert!(
28943                c.subject().is_none(),
28944                "WitContract::subject must return None when the typed \
28945                 slot is absent under :wit {wit:?} (got {:?})",
28946                c.subject(),
28947            );
28948            assert_eq!(
28949                c.subject(),
28950                c.subject.as_deref(),
28951                "WitContract::subject must byte-equal the .subject \
28952                 field's `.as_deref()` projection in the absent arm",
28953            );
28954        }
28955    }
28956
28957    #[test]
28958    fn wit_contract_subject_borrows_from_subject_storage() {
28959        // The borrow-not-copy pin: [`WitContract::subject`] must return
28960        // an `Option<&str>` whose `Some` arm borrows from the typed
28961        // slot's own [`String`] storage — same-address invariant with
28962        // `c.subject.as_deref().unwrap()`. Pins against a future silent
28963        // detour that allocated a fresh `String`
28964        // (`self.subject.clone().map(...)` in the body would type-check
28965        // but silently drop the borrow, and every downstream consumer
28966        // that assumed the returned slice outlives `&self` would break
28967        // on a stale-reference use-after-free — the [`WitContract::target`]
28968        // PubSub-arm payload extraction rebinds the returned
28969        // `Option<&str>` through `.ok_or_else(...)` and threads the
28970        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
28971        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
28972        // [`ContratoIdentity`] dedup key threads the returned
28973        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
28974        // from the WitContract's own storage and each would silently
28975        // misbehave if this accessor produced a detached copy). Peer of
28976        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
28977        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
28978        // shaped optional-scalar axis — second extension of the
28979        // `Option<&str>` borrow-not-copy discipline onto the
28980        // per-`:contratos` payload-carrier family, this time on the
28981        // pub-sub arm.
28982        let c = WitContract {
28983            de: "cart".into(),
28984            para: "notifier".into(),
28985            wit: "nats:pub-sub".into(),
28986            endpoint: None,
28987            subject: Some("orders.paid".into()),
28988            slot: None,
28989        };
28990        let sub = c.subject().expect("Some arm");
28991        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
28992        assert_eq!(
28993            sub.as_ptr(),
28994            storage_slice.as_ptr(),
28995            "WitContract::subject must borrow from the .subject \
28996             String's backing storage — a fresh allocation here means \
28997             the accessor no longer names the substrate-primitive typed \
28998             dispatch and every downstream consumer would silently \
28999             carry a detached copy",
29000        );
29001        assert_eq!(
29002            sub.len(),
29003            storage_slice.len(),
29004            "WitContract::subject and .subject.as_deref() must byte-\
29005             equal in length as well as in address",
29006        );
29007    }
29008
29009    #[test]
29010    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
29011        // The canonical per-`:contratos` key/value-store-shaped
29012        // `:slot`-scalar pin: [`WitContract::slot`] must return the
29013        // `:contratos :slot` field byte-for-byte, borrowed from the
29014        // typed slot's own `Option<String>` storage. Peer of the
29015        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
29016        // [`WitContract::subject`] (90de675) accessor pins on the M3
29017        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
29018        // optional-scalar axis — same "the substrate-primitive
29019        // accessor must byte-equal the raw field access verbatim
29020        // across every author-declared value" discipline extended to
29021        // the store arm. Pins against a future silent detour that
29022        // re-canonicalized the slot template (an accidental
29023        // `.to_lowercase()` bucket-prefix normalization that didn't
29024        // reach the peer field-access site at the dedup key, a per-CR
29025        // fully-qualified prefix rewrite the operator authors on one
29026        // consumer without the other, or an M4 typed-key-template
29027        // `Display` re-canonicalization that silently drifted the
29028        // printer output from the source `caixa.lisp`). Four values
29029        // sweep the wasi:keyvalue accept-set every store-shaped
29030        // author-declared slot lands on (flat bucket, single-param
29031        // template, multi-param template, nested-hierarchy template).
29032        for slot in [
29033            "sessions",
29034            "carts/{cart_id}",
29035            "orders/{tenant}/{order_id}",
29036            "cache/tenant-a/orders/{id}",
29037        ] {
29038            let c = WitContract {
29039                de: "cart".into(),
29040                para: "kv".into(),
29041                wit: "wasi:keyvalue/store".into(),
29042                endpoint: None,
29043                subject: None,
29044                slot: Some(slot.into()),
29045            };
29046            assert_eq!(
29047                c.slot(),
29048                Some(slot),
29049                "WitContract::slot must return :contratos :slot \
29050                 verbatim (got {:?}, expected Some({slot:?}))",
29051                c.slot(),
29052            );
29053            assert_eq!(
29054                c.slot(),
29055                c.slot.as_deref(),
29056                "WitContract::slot must byte-equal the .slot field's \
29057                 `.as_deref()` projection",
29058            );
29059        }
29060    }
29061
29062    #[test]
29063    fn wit_contract_slot_none_when_field_is_none() {
29064        // The absent-`:slot` arm of the per-`:contratos` store-shaped
29065        // payload-carrier accessor pin: when the typed slot is absent —
29066        // the canonical shape under a non-store `:wit` world per the
29067        // [`WitContract::target`]-enforced shape ↔ target partition
29068        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
29069        // carries `:subject`, [`WitTarget::Capability`] carries none) —
29070        // [`WitContract::slot`] must return `None`. Pins against a
29071        // future silent detour that projected the absent slot to a
29072        // `Some("")` empty-string default (the canonical
29073        // `Option<String>` → `String` collapse footgun the sibling M2
29074        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
29075        // emptiness predicates already guard on the peer M2 typed-slot
29076        // surfaces), a `Some("None")` stringified-None round-trip, or
29077        // a `Some` arm whose contents were derived from a sibling
29078        // slot (an accidental fallback to the `:endpoint` / `:subject`
29079        // payload that read the HTTP / pub-sub payload into the store
29080        // axis). Three contracts sweep the accept-set every non-store
29081        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
29082        // payload-less capability.
29083        for (wit, endpoint, subject) in [
29084            ("wasi:http/proxy", Some("/lookup"), None),
29085            ("nats:pub-sub", None, Some("orders.paid")),
29086            ("wasi:cli/environment", None, None),
29087        ] {
29088            let c = WitContract {
29089                de: "cart".into(),
29090                para: "downstream".into(),
29091                wit: wit.into(),
29092                endpoint: endpoint.map(str::to_string),
29093                subject: subject.map(str::to_string),
29094                slot: None,
29095            };
29096            assert!(
29097                c.slot().is_none(),
29098                "WitContract::slot must return None when the typed \
29099                 slot is absent under :wit {wit:?} (got {:?})",
29100                c.slot(),
29101            );
29102            assert_eq!(
29103                c.slot(),
29104                c.slot.as_deref(),
29105                "WitContract::slot must byte-equal the .slot field's \
29106                 `.as_deref()` projection in the absent arm",
29107            );
29108        }
29109    }
29110
29111    #[test]
29112    fn wit_contract_slot_borrows_from_slot_storage() {
29113        // The borrow-not-copy pin: [`WitContract::slot`] must return
29114        // an `Option<&str>` whose `Some` arm borrows from the typed
29115        // slot's own [`String`] storage — same-address invariant with
29116        // `c.slot.as_deref().unwrap()`. Pins against a future silent
29117        // detour that allocated a fresh `String`
29118        // (`self.slot.clone().map(...)` in the body would type-check
29119        // but silently drop the borrow, and every downstream consumer
29120        // that assumed the returned slice outlives `&self` would
29121        // break on a stale-reference use-after-free — the
29122        // [`WitContract::target`] Store-arm payload extraction rebinds
29123        // the returned `Option<&str>` through `.ok_or_else(...)` and
29124        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
29125        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
29126        // [`ContratoIdentity`] dedup key threads the returned
29127        // `Option<&str>` into the six-tuple's store arm — each borrow
29128        // from the WitContract's own storage and each would silently
29129        // misbehave if this accessor produced a detached copy). Peer
29130        // of the sibling per-`:contratos` [`WitContract::endpoint`]
29131        // (7020470) / [`WitContract::subject`] (90de675)
29132        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
29133        // shaped optional-scalar axis — third and final extension of
29134        // the `Option<&str>` borrow-not-copy discipline onto the
29135        // per-`:contratos` payload-carrier family, this time on the
29136        // store arm.
29137        let c = WitContract {
29138            de: "cart".into(),
29139            para: "kv".into(),
29140            wit: "wasi:keyvalue/store".into(),
29141            endpoint: None,
29142            subject: None,
29143            slot: Some("carts/{cart_id}".into()),
29144        };
29145        let slot = c.slot().expect("Some arm");
29146        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
29147        assert_eq!(
29148            slot.as_ptr(),
29149            storage_slice.as_ptr(),
29150            "WitContract::slot must borrow from the .slot String's \
29151             backing storage — a fresh allocation here means the \
29152             accessor no longer names the substrate-primitive typed \
29153             dispatch and every downstream consumer would silently \
29154             carry a detached copy",
29155        );
29156        assert_eq!(
29157            slot.len(),
29158            storage_slice.len(),
29159            "WitContract::slot and .slot.as_deref() must byte-equal \
29160             in length as well as in address",
29161        );
29162    }
29163
29164    #[test]
29165    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
29166        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
29167        // [`Membro::nome`] must return the `:membros :caixa` field
29168        // byte-for-byte, borrowed from the typed slot's own [`String`]
29169        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
29170        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
29171        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
29172        // slot-atom scalar-value axes — same "the substrate-primitive
29173        // accessor must byte-equal the raw field access verbatim across
29174        // every author-declared value" discipline extended to the
29175        // per-`:membros` member-identity arm. Pins against a future
29176        // silent detour that re-normalized the member identity (an
29177        // accidental `.to_lowercase()` — every `:membros :caixa` is
29178        // validated as a DNS-1123 label upstream via
29179        // [`validate_membro_caixa`], so any re-normalization is
29180        // redundant + a drift surface between the validator and the
29181        // accessor), a namespace-prefix rewrite (an accidental
29182        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
29183        // rewrite that didn't land on the peer axes), or a per-cluster
29184        // alias stamp the operator authors on one consumer without the
29185        // other. Four values sweep the accept-set the DNS-1123 gate
29186        // upstream admits (short single-word / dashed / v-suffixed
29187        // member names).
29188        for name in ["cart", "checkout", "catalog", "orders-v2"] {
29189            let m = Membro {
29190                caixa: name.into(),
29191                versao: "^0.1".into(),
29192            };
29193            assert_eq!(
29194                m.nome(),
29195                name,
29196                "Membro::nome must return :membros :caixa verbatim \
29197                 (got {:?}, expected {name:?})",
29198                m.nome(),
29199            );
29200            assert_eq!(
29201                m.nome(),
29202                m.caixa.as_str(),
29203                "Membro::nome must byte-equal the .caixa field access",
29204            );
29205        }
29206    }
29207
29208    #[test]
29209    fn membro_nome_borrows_from_caixa_storage() {
29210        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
29211        // slice that borrows from the typed slot's own [`String`]
29212        // storage — same-address invariant with `m.caixa.as_str()`. Pins
29213        // against a future silent detour that allocated a fresh `String`
29214        // (`self.caixa.clone()` in the body would type-check but
29215        // silently drop the borrow, and every downstream consumer that
29216        // assumed the returned slice outlives `&self` would break on a
29217        // stale-reference use-after-free — the `HashSet<&str>` collector
29218        // at [`AplicacaoSpec::validate`]'s `names` seed, the
29219        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
29220        // [`AplicacaoSpec::detect_sync_cycles`], the
29221        // [`crate::render::insert_first_seen`] dedup key at
29222        // [`AplicacaoSpec::validate_membros`] — each borrow from the
29223        // Membro's own storage and each would silently misbehave if
29224        // this accessor produced a detached copy). Peer of the sibling
29225        // per-`:contratos` [`WitContract::source`] /
29226        // [`WitContract::destination`] and per-`:entrada`
29227        // [`Entrada::destination`] borrow-invariant pins on the mesh-
29228        // slot-atom scalar-value axes.
29229        let m = Membro {
29230            caixa: "checkout".into(),
29231            versao: "^0.1".into(),
29232        };
29233        let name = m.nome();
29234        let caixa_slice = m.caixa.as_str();
29235        assert_eq!(
29236            name.as_ptr(),
29237            caixa_slice.as_ptr(),
29238            "Membro::nome must borrow from the .caixa String's backing \
29239             storage — a fresh allocation here means the accessor no \
29240             longer names the substrate-primitive typed dispatch and \
29241             every downstream consumer would silently carry a detached \
29242             copy",
29243        );
29244        assert_eq!(
29245            name.len(),
29246            caixa_slice.len(),
29247            "Membro::nome and .caixa.as_str() must byte-equal in length \
29248             as well as in address",
29249        );
29250    }
29251
29252    #[test]
29253    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
29254        // The canonical per-`:membros` member-`:versao`-scalar pin:
29255        // [`Membro::versao_requirement`] must return the
29256        // `:membros :versao` field byte-for-byte, borrowed from the typed
29257        // slot's own [`String`] storage. Sibling of the peer
29258        // `membro_nome_returns_caixa_byte_equal_across_permutations`
29259        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
29260        // — same "the substrate-primitive accessor must byte-equal the
29261        // raw field access verbatim across every author-declared value"
29262        // discipline extended to the per-`:membros` member-`:versao`
29263        // requirement-string arm. Pins against a future silent detour
29264        // that re-canonicalized the requirement (an accidental
29265        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
29266        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
29267        // drifted the printer output away from the source `caixa.lisp`,
29268        // an accidental whitespace trim on `"^ 0.1"` that no consumer
29269        // ever produced from the field-access side, an accidental
29270        // per-cluster lacre-projected concrete-version rewrite that
29271        // didn't land on the peer field-access sites). Five values sweep
29272        // the accept-set the shared
29273        // [`crate::render::require_valid_versao_requirement`] gate
29274        // admits (caret / tilde / exact / wildcard / bare-major).
29275        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
29276            let m = Membro {
29277                caixa: "cart".into(),
29278                versao: req.into(),
29279            };
29280            assert_eq!(
29281                m.versao_requirement(),
29282                req,
29283                "Membro::versao_requirement must return :membros :versao \
29284                 verbatim (got {:?}, expected {req:?})",
29285                m.versao_requirement(),
29286            );
29287            assert_eq!(
29288                m.versao_requirement(),
29289                m.versao.as_str(),
29290                "Membro::versao_requirement must byte-equal the .versao \
29291                 field access",
29292            );
29293        }
29294    }
29295
29296    #[test]
29297    fn membro_versao_requirement_borrows_from_versao_storage() {
29298        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
29299        // return a `&str` slice that borrows from the typed slot's own
29300        // [`String`] storage — same-address invariant with
29301        // `m.versao.as_str()`. Pins against a future silent detour that
29302        // allocated a fresh `String` (`self.versao.clone()` in the body
29303        // would type-check but silently drop the borrow, and every
29304        // downstream consumer that assumed the returned slice outlives
29305        // `&self` would break on a stale-reference use-after-free). Peer
29306        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
29307        // per-`:contratos` [`WitContract::source`] /
29308        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
29309        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
29310        // the mesh-slot-atom scalar-value axes.
29311        let m = Membro {
29312            caixa: "checkout".into(),
29313            versao: "^0.1".into(),
29314        };
29315        let req = m.versao_requirement();
29316        let versao_slice = m.versao.as_str();
29317        assert_eq!(
29318            req.as_ptr(),
29319            versao_slice.as_ptr(),
29320            "Membro::versao_requirement must borrow from the .versao \
29321             String's backing storage — a fresh allocation here means \
29322             the accessor no longer names the substrate-primitive typed \
29323             dispatch and every downstream consumer would silently carry \
29324             a detached copy",
29325        );
29326        assert_eq!(
29327            req.len(),
29328            versao_slice.len(),
29329            "Membro::versao_requirement and .versao.as_str() must byte-\
29330             equal in length as well as in address",
29331        );
29332    }
29333
29334    #[test]
29335    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
29336        // Sibling-pair invariant pin composing both per-`:membros`
29337        // substrate-primitive typed dispatches — [`Membro::nome`]
29338        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
29339        // `(nome(), versao_requirement())` call shape every renderer
29340        // that fans on per-member identity + version pin keys off. The
29341        // invariant, evaluated per-member:
29342        //
29343        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
29344        //
29345        // Closes the last unlifted per-`:membros` scalar axis — every
29346        // downstream consumer that reads the pair now routes through
29347        // exactly two typed dispatches on the substrate primitive, not
29348        // one typed + one open-coded field access. A future refactor
29349        // that silently split either accessor's projection (an
29350        // accidental `nome()` namespace-prefix rewrite that didn't
29351        // reach the peer, an accidental `versao_requirement()` lacre-
29352        // projected concrete-version rewrite that didn't land on the
29353        // `nome()` peer) surfaces at caixa-core build time. Peer of the
29354        // sibling per-`:entrada` `(hostname(), destination())` and
29355        // per-`:contratos` `(source(), destination())` pair invariants
29356        // on the mesh-slot-atom scalar-value axes.
29357        for (caixa, versao) in [
29358            ("cart", "^0.1"),
29359            ("checkout", "~0.1.2"),
29360            ("catalog", "0.1.0"),
29361            ("orders-v2", "*"),
29362        ] {
29363            let m = Membro {
29364                caixa: caixa.into(),
29365                versao: versao.into(),
29366            };
29367            assert_eq!(
29368                (m.nome(), m.versao_requirement()),
29369                (m.caixa.as_str(), m.versao.as_str()),
29370                "(Membro::nome, Membro::versao_requirement) must project \
29371                 (.caixa, .versao) verbatim across every author-declared \
29372                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
29373                m.nome(),
29374                m.versao_requirement(),
29375            );
29376        }
29377    }
29378
29379    #[test]
29380    fn validate_membros_empty_gate_routes_through_nome_accessor() {
29381        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
29382        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
29383        // not the raw `.caixa` field access. Structurally: setting
29384        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
29385        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
29386        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
29387        // (i.e. the empty string) — so the emptiness predicate the
29388        // refusal arm reaches under is the accessor-projected value,
29389        // not a peer field that would silently drift under a future
29390        // accessor-side rewrite.
29391        //
29392        // Pins against a future silent detour that (a) re-derived the
29393        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
29394        // instead of `self.nome().is_empty()`, silently disagreeing with
29395        // every peer consumer (the `validate_membro_caixa(m.nome())`
29396        // per-slot helper — which now owns the emptiness arm outright —
29397        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
29398        // below, and the emit-side per-`programs[]` entry-`name:` at
29399        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
29400        // per-tenant alias arm the caller was unaware of, silently
29401        // rewriting an author-declared `:caixa "checkout"` to `""` —
29402        // the raw-field-access gate would fail-open while the
29403        // accessor-routed peer consumers would fail-closed, splitting
29404        // the diagnostic from the actual failure surface.
29405        //
29406        // Peer of the sibling
29407        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
29408        // (c0110f1) composition pin — same "the shape-gate predicate
29409        // must route through the substrate-primitive typed dispatch"
29410        // discipline extended onto the per-`:membros` empty-`:caixa`
29411        // refusal-arm axis. Closes the last unlifted `.caixa` production-
29412        // code read site on `Membro` — after this converge every
29413        // caixa-core `.caixa` field access outside the accessor's own
29414        // body is either a test-side field-setter (in-module tests
29415        // constructing invalid-shape inputs) or a doc-comment reference.
29416        let mut s = three_member_spec();
29417        s.membros[1].caixa = String::new();
29418        assert!(
29419            s.membros[1].nome().is_empty(),
29420            "Membro::nome must byte-equal the .caixa field access — an \
29421             accessor-side detour that no longer projects the raw field \
29422             would silently split this drift-detection test from the \
29423             validate() refusal arm",
29424        );
29425        assert_eq!(
29426            s.membros[1].nome(),
29427            s.membros[1].caixa.as_str(),
29428            "Membro::nome and .caixa.as_str() must byte-equal on an \
29429             empty-`:caixa` entry — the emptiness gate keys off the \
29430             accessor by construction",
29431        );
29432        assert_eq!(
29433            s.validate().unwrap_err(),
29434            AplicacaoError::MembroCaixaEmpty,
29435            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
29436             on an entry whose accessor-projected `nome()` is empty",
29437        );
29438    }
29439
29440    #[test]
29441    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
29442        // Convergence pin, paired with the deletion of the redundant
29443        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
29444        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
29445        // after the collapse, the `MembroCaixaEmpty` refusal on every
29446        // empty-`:caixa` per-member input is owned solely by the shared
29447        // [`validate_membro_caixa`] helper — the same per-slot substrate
29448        // primitive routing empty + shape arms uniformly onto
29449        // [`crate::render::require_valid_dns_1123_label`] that every
29450        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
29451        // on `:placement :clusters`, [`validate_entrada_para`] on
29452        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
29453        // :de`/`:para`) already funnels its own empty arm through.
29454        //
29455        // Two arms pin the collapse:
29456        //
29457        //   (1) The per-slot helper called with the empty string returns
29458        //       byte-equal to the previous inline arm's diagnostic — so
29459        //       a future rebrand of [`validate_membro_caixa`] that
29460        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
29461        //       empty input (an inadvertent switch to
29462        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
29463        //       `on_invalid` arm, an accidental re-routing to a shared
29464        //       `MembroError::Empty` under a future error-hierarchy
29465        //       flattening) would silently split the drift from the
29466        //       [`validate_membros`] caller and surface the wrong
29467        //       diagnostic on the author-facing empty-`:caixa` footgun.
29468        //
29469        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
29470        //       anywhere in the `:membros` fan-out still trips
29471        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
29472        //       no outer inline guard needed. Same shape as the
29473        //       whole-spec arm on [`validate_placement_cluster`] /
29474        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
29475        //       one substrate primitive per axis, folding empty + shape.
29476        //
29477        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
29478        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
29479        // MeshPolicy::validate) already extend across the M3 mesh-slot
29480        // family — closes the last per-slot gate on the family carrying
29481        // an inline empty guard duplicating its own helper.
29482        assert_eq!(
29483            validate_membro_caixa(""),
29484            Err(AplicacaoError::MembroCaixaEmpty),
29485            "validate_membro_caixa must own the empty arm outright — a \
29486             regression here would silently split MembroCaixaEmpty from \
29487             validate_membros' end-to-end refusal shape after the outer \
29488             inline `if m.nome().is_empty()` guard collapse",
29489        );
29490        let mut s = three_member_spec();
29491        s.membros[0].caixa = String::new();
29492        assert_eq!(
29493            s.validate().unwrap_err(),
29494            AplicacaoError::MembroCaixaEmpty,
29495            "an empty-`:caixa` :membros head entry must trip \
29496             MembroCaixaEmpty end-to-end via validate() with the outer \
29497             inline guard removed — the per-slot helper alone is now \
29498             load-bearing",
29499        );
29500        let mut s = three_member_spec();
29501        s.membros[2].caixa = String::new();
29502        assert_eq!(
29503            s.validate().unwrap_err(),
29504            AplicacaoError::MembroCaixaEmpty,
29505            "an empty-`:caixa` :membros tail entry must trip \
29506             MembroCaixaEmpty end-to-end via validate() with the outer \
29507             inline guard removed — the per-slot helper alone reaches \
29508             every fan-out position",
29509        );
29510    }
29511
29512    #[test]
29513    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
29514        // The canonical per-`:placement` Akka-cluster-sharding
29515        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
29516        // the `:placement :shard-key` field byte-for-byte, borrowed
29517        // from the typed slot's own `Option<String>` storage. Peer of
29518        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
29519        // per-`:contratos` [`WitContract::source`] /
29520        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
29521        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
29522        // slot-atom scalar-value axes — same "the substrate-primitive
29523        // accessor must byte-equal the raw field access verbatim across
29524        // every author-declared value" discipline extended to the
29525        // per-`:placement` Akka-cluster-sharding key extractor arm.
29526        // Pins against a future silent detour that re-normalized the
29527        // key (an accidental `.to_lowercase()` — every non-empty
29528        // `:shard-key` is validated as a printable-ASCII single-token
29529        // reference upstream via [`validate_placement_shard_key`], so
29530        // any re-normalization is redundant + a drift surface between
29531        // the validator and the accessor), a per-cluster alias rewrite
29532        // the operator authors on one consumer without the other, or an
29533        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
29534        // that didn't land on the peer field-access sites. Four values
29535        // sweep the accept-set the shape gate admits — bare identifier,
29536        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
29537        // the four canonical Akka-style entity-id extractor shapes the
29538        // future M4 cluster-sharding reconciler hashes.
29539        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
29540            let p = Placement {
29541                estrategia: PlacementStrategy::Sharded,
29542                clusters: vec!["rio".into()],
29543                affinity: None,
29544                shard_key: Some(key.into()),
29545            };
29546            assert_eq!(
29547                p.shard_key(),
29548                Some(key),
29549                "Placement::shard_key must return :placement :shard-key \
29550                 verbatim (got {:?}, expected Some({key:?}))",
29551                p.shard_key(),
29552            );
29553            assert_eq!(
29554                p.shard_key(),
29555                p.shard_key.as_deref(),
29556                "Placement::shard_key must byte-equal the .shard_key \
29557                 field's `.as_deref()` projection",
29558            );
29559        }
29560    }
29561
29562    #[test]
29563    fn placement_shard_key_none_when_field_is_none() {
29564        // The absent-`:shard-key` arm of the per-`:placement`
29565        // Akka-cluster-sharding accessor pin: when the typed slot is
29566        // absent — the canonical shape under `:estrategia Replicated` /
29567        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
29568        // enforced `shard_key.is_some() == matches!(estrategia,
29569        // Sharded)` partition — [`Placement::shard_key`] must return
29570        // `None`. Pins against a future silent detour that projected
29571        // the absent slot to a `Some("")` empty-string default (the
29572        // canonical `Option<String>` → `String` collapse footgun the
29573        // sibling M2 [`crate::LimitsSpec::is_empty`] /
29574        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
29575        // already guard on the peer M2 typed-slot surfaces), a
29576        // `Some("None")` stringified-None round-trip, or a `Some` arm
29577        // whose contents were derived from a sibling slot (an
29578        // accidental fallback to `estrategia.as_str()` that read the
29579        // strategy discriminator into the key axis). Two placements
29580        // sweep the accept-set every `validate`-passing non-`Sharded`
29581        // shape lands on — `Replicated` (Erlang/OTP distributed-app
29582        // takeover) and `SingleNode` (single-node hosting).
29583        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
29584            let p = Placement {
29585                estrategia,
29586                clusters: vec!["rio".into()],
29587                affinity: None,
29588                shard_key: None,
29589            };
29590            assert!(
29591                p.shard_key().is_none(),
29592                "Placement::shard_key must return None when the typed \
29593                 slot is absent under :estrategia {estrategia:?} (got {:?})",
29594                p.shard_key(),
29595            );
29596            assert_eq!(
29597                p.shard_key(),
29598                p.shard_key.as_deref(),
29599                "Placement::shard_key must byte-equal the .shard_key \
29600                 field's `.as_deref()` projection in the absent arm",
29601            );
29602        }
29603    }
29604
29605    #[test]
29606    fn placement_shard_key_borrows_from_shard_key_storage() {
29607        // The borrow-not-copy pin: [`Placement::shard_key`] must return
29608        // an `Option<&str>` whose `Some` arm borrows from the typed
29609        // slot's own [`String`] storage — same-address invariant with
29610        // `p.shard_key.as_deref().unwrap()`. Pins against a future
29611        // silent detour that allocated a fresh `String`
29612        // (`self.shard_key.clone().map(...)` in the body would type-
29613        // check but silently drop the borrow, and every downstream
29614        // consumer that assumed the returned slice outlives `&self`
29615        // would break on a stale-reference use-after-free — the
29616        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
29617        // gate's `Some(k)`-bound match arm reads `k: &str` under the
29618        // accessor's return type and would silently misbehave if this
29619        // accessor produced a detached copy). Peer of the sibling
29620        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
29621        // [`WitContract::source`] / [`WitContract::destination`]
29622        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
29623        // (6db982c) borrow-invariant pins on the mesh-slot-atom
29624        // scalar-value axes — first extension of the discipline onto
29625        // an `Option<String>`-shaped optional-scalar axis.
29626        let p = Placement {
29627            estrategia: PlacementStrategy::Sharded,
29628            clusters: vec!["rio".into()],
29629            affinity: None,
29630            shard_key: Some("tenantId".into()),
29631        };
29632        let key = p.shard_key().expect("Some arm");
29633        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
29634        assert_eq!(
29635            key.as_ptr(),
29636            storage_slice.as_ptr(),
29637            "Placement::shard_key must borrow from the .shard_key \
29638             String's backing storage — a fresh allocation here means \
29639             the accessor no longer names the substrate-primitive typed \
29640             dispatch and every downstream consumer would silently \
29641             carry a detached copy",
29642        );
29643        assert_eq!(
29644            key.len(),
29645            storage_slice.len(),
29646            "Placement::shard_key and .shard_key.as_deref() must byte-\
29647             equal in length as well as in address",
29648        );
29649    }
29650
29651    #[test]
29652    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
29653        // The canonical per-`:placement` M3-Adaptive-compression-hint
29654        // scalar pin: [`Placement::affinity`] must return the
29655        // `:placement :affinity` field byte-for-byte, borrowed from the
29656        // typed slot's own `Option<String>` storage. Peer of the sibling
29657        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
29658        // pin on the sibling `Option<&str>` optional-scalar axis — same
29659        // "the substrate-primitive accessor must byte-equal the raw
29660        // field access verbatim across every author-declared value"
29661        // discipline extended to the peer per-`:placement` M3-Adaptive-
29662        // compression-hint arm. Pins against a future silent detour
29663        // that re-normalized the hint (an accidental `.to_lowercase()`
29664        // — every `:affinity` is already validated as a DNS-1123 label
29665        // upstream via [`validate_placement_affinity`], so any re-
29666        // normalization is redundant + a drift surface between the
29667        // validator and the accessor), a per-cluster alias rewrite the
29668        // operator authors on one consumer without the other, or an
29669        // accidental hint-family collapse (`low-latency` → `latency`
29670        // that dropped the qualifier prefix). Four values sweep the
29671        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
29672        // canonical adaptive-compression-weight biases the future M4
29673        // placement engine reads.
29674        for hint in [
29675            "data-locality",
29676            "low-latency",
29677            "high-throughput",
29678            "cost-optimized",
29679        ] {
29680            let p = Placement {
29681                estrategia: PlacementStrategy::Replicated,
29682                clusters: vec!["rio".into()],
29683                affinity: Some(hint.into()),
29684                shard_key: None,
29685            };
29686            assert_eq!(
29687                p.affinity(),
29688                Some(hint),
29689                "Placement::affinity must return :placement :affinity \
29690                 verbatim (got {:?}, expected Some({hint:?}))",
29691                p.affinity(),
29692            );
29693            assert_eq!(
29694                p.affinity(),
29695                p.affinity.as_deref(),
29696                "Placement::affinity must byte-equal the .affinity \
29697                 field's `.as_deref()` projection",
29698            );
29699        }
29700    }
29701
29702    #[test]
29703    fn placement_affinity_none_when_field_is_none() {
29704        // The absent-`:affinity` arm of the per-`:placement`
29705        // M3-Adaptive-compression-hint accessor pin: when the typed
29706        // slot is absent — the canonical shape of an Aplicacao that
29707        // leaves the compression weighting up to the placement engine's
29708        // cluster-default arm — [`Placement::affinity`] must return
29709        // `None`. Pins against a future silent detour that projected
29710        // the absent slot to a `Some("")` empty-string default (the
29711        // canonical `Option<String>` → `String` collapse footgun the
29712        // sibling M2 [`crate::LimitsSpec::is_empty`] /
29713        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
29714        // already guard on the peer M2 typed-slot surfaces), a
29715        // `Some("None")` stringified-None round-trip, a `Some` arm
29716        // whose contents were derived from a sibling slot (an
29717        // accidental fallback to `estrategia.as_str()` that read the
29718        // strategy discriminator into the hint axis), or a
29719        // `Some("default")` implicit-default that would silently biases
29720        // the routing without the author having written one. Three
29721        // placements sweep the accept-set every `validate`-passing
29722        // `:affinity None` shape lands on — one per PlacementStrategy
29723        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
29724        // with a shard-key), since `:affinity` is orthogonal to
29725        // `:estrategia` in the typed grammar.
29726        for (estrategia, shard_key) in [
29727            (PlacementStrategy::SingleNode, None),
29728            (PlacementStrategy::Replicated, None),
29729            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
29730        ] {
29731            let p = Placement {
29732                estrategia,
29733                clusters: vec!["rio".into()],
29734                affinity: None,
29735                shard_key,
29736            };
29737            assert!(
29738                p.affinity().is_none(),
29739                "Placement::affinity must return None when the typed \
29740                 slot is absent under :estrategia {estrategia:?} (got {:?})",
29741                p.affinity(),
29742            );
29743            assert_eq!(
29744                p.affinity(),
29745                p.affinity.as_deref(),
29746                "Placement::affinity must byte-equal the .affinity \
29747                 field's `.as_deref()` projection in the absent arm",
29748            );
29749        }
29750    }
29751
29752    #[test]
29753    fn placement_affinity_borrows_from_affinity_storage() {
29754        // The borrow-not-copy pin: [`Placement::affinity`] must return
29755        // an `Option<&str>` whose `Some` arm borrows from the typed
29756        // slot's own [`String`] storage — same-address invariant with
29757        // `p.affinity.as_deref().unwrap()`. Pins against a future
29758        // silent detour that allocated a fresh `String`
29759        // (`self.affinity.clone().map(...)` in the body would type-
29760        // check but silently drop the borrow, and every downstream
29761        // consumer that assumed the returned slice outlives `&self`
29762        // would break on a stale-reference use-after-free — the
29763        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
29764        // gate reads the accessor's `&str` return through the
29765        // [`validate_placement_affinity`] `&str` parameter and would
29766        // silently misbehave if this accessor produced a detached
29767        // copy). Peer of the sibling per-`:placement`
29768        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
29769        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
29770        // extends the discipline onto the sibling per-`:placement`
29771        // M3-Adaptive-compression-hint arm.
29772        let p = Placement {
29773            estrategia: PlacementStrategy::Replicated,
29774            clusters: vec!["rio".into()],
29775            affinity: Some("data-locality".into()),
29776            shard_key: None,
29777        };
29778        let hint = p.affinity().expect("Some arm");
29779        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
29780        assert_eq!(
29781            hint.as_ptr(),
29782            storage_slice.as_ptr(),
29783            "Placement::affinity must borrow from the .affinity \
29784             String's backing storage — a fresh allocation here means \
29785             the accessor no longer names the substrate-primitive typed \
29786             dispatch and every downstream consumer would silently \
29787             carry a detached copy",
29788        );
29789        assert_eq!(
29790            hint.len(),
29791            storage_slice.len(),
29792            "Placement::affinity and .affinity.as_deref() must byte-\
29793             equal in length as well as in address",
29794        );
29795    }
29796
29797    #[test]
29798    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
29799        // The canonical per-`:placement` distribution-strategy-scalar
29800        // pin: [`Placement::estrategia`] must return the `:placement
29801        // :estrategia` field verbatim as a [`PlacementStrategy`],
29802        // `Copy`-projected from the typed slot's own `PlacementStrategy`
29803        // storage across every variant in the closed accept-set
29804        // (`SingleNode` — Erlang/OTP distributed-app takeover;
29805        // `Replicated` — active-active across every named cluster;
29806        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
29807        // against a future silent detour that re-derived the strategy
29808        // from a peer axis (an accidental fallback to
29809        // `if shard_key.is_some() { Sharded } else { Replicated }`
29810        // collapse that read the shard-key axis into the strategy
29811        // discriminator), a variant remap the operator authors on one
29812        // consumer without the other, or a stale-derive detour that
29813        // substituted [`PlacementStrategy::default`] when the field
29814        // held any explicit variant (which would silently collapse the
29815        // distinction between "author explicitly declared `:estrategia
29816        // Replicated`" and "author omitted the slot and inherited the
29817        // default" the future per-cluster override slot depends on).
29818        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
29819        // pin on the `Copy`-return `u16` scalar axis — same "the
29820        // substrate-primitive accessor must byte-equal the raw field
29821        // access verbatim across every author-declared value" discipline
29822        // extended onto the per-`:placement` distribution-strategy
29823        // `Copy`-composite-enum scalar axis.
29824        for estrategia in [
29825            PlacementStrategy::SingleNode,
29826            PlacementStrategy::Replicated,
29827            PlacementStrategy::Sharded,
29828        ] {
29829            // Route the paired `:shard-key` fixture-builder through the
29830            // typed cross-slot invariant predicate
29831            // [`PlacementStrategy::requires_shard_key`] rather than the
29832            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
29833            // arm-identity predicate — same discipline the sibling
29834            // `placement_strategy_variants_round_trip` fixture builder now
29835            // reads through.
29836            let shard_key = estrategia
29837                .requires_shard_key()
29838                .then(|| "tenantId".to_string());
29839            let p = Placement {
29840                estrategia,
29841                clusters: vec!["rio".into()],
29842                affinity: None,
29843                shard_key,
29844            };
29845            assert_eq!(
29846                p.estrategia(),
29847                estrategia,
29848                "Placement::estrategia must return :placement :estrategia \
29849                 verbatim (got {:?}, expected {estrategia:?})",
29850                p.estrategia(),
29851            );
29852            assert_eq!(
29853                p.estrategia(),
29854                p.estrategia,
29855                "Placement::estrategia accessor and .estrategia field \
29856                 access must byte-equal — the accessor is the substrate-\
29857                 primitive typed dispatch every downstream distribution-\
29858                 strategy consumer must route through",
29859            );
29860        }
29861    }
29862
29863    #[test]
29864    fn validate_placement_reads_through_lifted_estrategia_accessor() {
29865        // Three-consumer coherence pin: the
29866        // [`AplicacaoSpec::validate_placement`]
29867        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
29868        // `estrategia:` field (which reads through
29869        // [`Placement::estrategia`] to name the strategy the empty
29870        // `:clusters` list was declared against), the same method's
29871        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
29872        // reads through [`Placement::estrategia`] to fan across the
29873        // shape-gate cascades), and the non-`Sharded`-arm
29874        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
29875        // `estrategia:` field (which reads through
29876        // [`Placement::estrategia`] to name the strategy the declared-
29877        // but-inert `:shard-key` was authored under) must all key off
29878        // the lifted accessor, so any future rebrand on the typed
29879        // slot's reader shape lands at exactly one place. Pins the
29880        // three-site coherence by exercising each error surface end-
29881        // to-end and asserting the surfaced `estrategia:` field byte-
29882        // equals the accessor's return. Peer of the sibling per-
29883        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
29884        // pin on the M3 mesh-slot `Copy`-return scalar axis.
29885
29886        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
29887        // whose `estrategia:` field must byte-equal the accessor's return
29888        // for every variant in the closed accept-set.
29889        for estrategia in [
29890            PlacementStrategy::SingleNode,
29891            PlacementStrategy::Replicated,
29892            PlacementStrategy::Sharded,
29893        ] {
29894            let mut spec = three_member_spec();
29895            spec.placement.estrategia = estrategia;
29896            spec.placement.clusters = Vec::new();
29897            // Route the paired `:shard-key` spec-mutator through the typed
29898            // cross-slot invariant predicate
29899            // [`PlacementStrategy::requires_shard_key`] rather than the
29900            // [`gen_platform::IsVariant`]-derived
29901            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
29902            // same discipline the sibling
29903            // `placement_strategy_variants_round_trip` and
29904            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
29905            // fixture builders now read through.
29906            spec.placement.shard_key = estrategia
29907                .requires_shard_key()
29908                .then(|| "tenantId".to_string());
29909            let err = spec.validate().unwrap_err();
29910            match err {
29911                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
29912                    assert_eq!(
29913                        e,
29914                        spec.placement.estrategia(),
29915                        "PlacementWithoutClusters.estrategia must byte-equal \
29916                         Placement::estrategia() — the error carrier reads \
29917                         through the lifted accessor",
29918                    );
29919                }
29920                other => panic!(
29921                    "expected PlacementWithoutClusters, got {other:?} for \
29922                     estrategia={estrategia:?}"
29923                ),
29924            }
29925        }
29926
29927        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
29928        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
29929        // must byte-equal the accessor's return for both non-`Sharded`
29930        // strategies.
29931        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
29932            let mut spec = three_member_spec();
29933            spec.placement.estrategia = estrategia;
29934            spec.placement.shard_key = Some("tenantId".into());
29935            let err = spec.validate().unwrap_err();
29936            match err {
29937                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
29938                    assert_eq!(
29939                        e,
29940                        spec.placement.estrategia(),
29941                        "ShardKeyOnNonSharded.estrategia must byte-equal \
29942                         Placement::estrategia() — the non-Sharded-arm \
29943                         refusal reads through the lifted accessor",
29944                    );
29945                }
29946                other => panic!(
29947                    "expected ShardKeyOnNonSharded, got {other:?} for \
29948                     estrategia={estrategia:?}"
29949                ),
29950            }
29951        }
29952    }
29953
29954    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
29955    //
29956    // The [`Placement::clusters`] accessor lift is the second slice-return
29957    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
29958    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
29959    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
29960    // below cover (1) the accessor's byte-equal projection against the raw
29961    // field access across the empty / singleton / cohort fixtures the
29962    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
29963    // and the per-cluster validate loop fan between, and (2) the two-
29964    // consumer coherence of the paired pre-flight refusal probe and the
29965    // per-cluster validate loop routing through the accessor on both arms.
29966
29967    #[test]
29968    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
29969        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
29970        // [`Placement::clusters`] must return the `:placement :clusters`
29971        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
29972        // the same backing buffer the raw `self.clusters.as_slice()`
29973        // field access borrows from, byte-equal across every
29974        // representative fixture in the accept-set — the empty slice
29975        // (the pre-validation sentinel every
29976        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
29977        // the singleton slice (the minimal `SingleNode`-shape cohort),
29978        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
29979        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
29980        //
29981        // Pins against a future silent detour that returned
29982        // `&Vec<String>` (which would type-check but leak the storage-
29983        // side `Vec`'s grow/push/reserve surface no consumer of the
29984        // typed view reaches for), a fresh-allocated `Vec<String>` copy
29985        // (which would type-check via a coercion but silently break
29986        // every downstream caller that relied on the slice sharing the
29987        // backing buffer's identity), or an out-of-order or length-
29988        // drifted projection (which would silently split the paired
29989        // pre-flight `.is_empty()` refusal probe's input from the per-
29990        // cluster validate loop's traversal input).
29991        //
29992        // Peer of the sibling M2
29993        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
29994        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
29995        // `:supervisor` static-child-list axis, extended onto the M3
29996        // per-`:placement` distribution-target-list `Vec`-carry axis.
29997        let fixtures: Vec<Vec<String>> = vec![
29998            Vec::new(),
29999            vec!["rio".into()],
30000            vec!["rio".into(), "mar".into()],
30001            vec!["rio".into(), "mar".into(), "plo".into()],
30002        ];
30003        for clusters in fixtures {
30004            let p = Placement {
30005                clusters: clusters.clone(),
30006                ..Placement::default()
30007            };
30008            assert_eq!(
30009                p.clusters(),
30010                clusters.as_slice(),
30011                "Placement::clusters must return :placement :clusters \
30012                 verbatim (got {:?}, expected {:?})",
30013                p.clusters(),
30014                clusters.as_slice(),
30015            );
30016            assert_eq!(
30017                p.clusters(),
30018                p.clusters.as_slice(),
30019                "Placement::clusters accessor and .clusters.as_slice() \
30020                 field access must byte-equal — the accessor is the \
30021                 substrate-primitive typed dispatch every downstream \
30022                 cluster-pool consumer must route through",
30023            );
30024            assert_eq!(
30025                p.clusters().len(),
30026                p.clusters.len(),
30027                "Placement::clusters().len() must byte-equal \
30028                 self.clusters.len() — a length-drift would silently \
30029                 split the paired pre-flight `.is_empty()` refusal \
30030                 probe input from the per-cluster validate loop's \
30031                 traversal input",
30032            );
30033        }
30034    }
30035
30036    #[test]
30037    fn validate_placement_reads_through_lifted_clusters_accessor() {
30038        // Two-consumer coherence pin: the
30039        // [`AplicacaoSpec::validate_placement`] pre-flight
30040        // `self.placement.clusters().is_empty()` refusal probe (which
30041        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
30042        // the accessor projects the empty slice) and the per-cluster
30043        // validate loop's `for c in self.placement.clusters()`
30044        // traversal (which must reach every entry in the same order
30045        // the accessor projects, so both the per-entry value-shape
30046        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
30047        // and the duplicate-detection HashSet insert that trips
30048        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
30049        // accessor's projection) must both key off the lifted
30050        // accessor, so any future rebrand on the typed slot's reader
30051        // shape lands at exactly one place. Pins the two-site
30052        // coherence by exercising each production consumer end-to-end:
30053        // (1) the `PlacementWithoutClusters` refusal under the empty
30054        // slice, (2) the `PlacementClusterInvalid` refusal fires on
30055        // the second entry of a two-cluster cohort whose head is
30056        // valid but tail is not (which requires the loop to reach the
30057        // second entry through the accessor), and (3) the
30058        // `PlacementClusterDuplicate` refusal fires on the second
30059        // entry of a two-cluster cohort that shares a name (which
30060        // requires the loop to reach both entries — a first-entry-only
30061        // projection would silently pass since the dedup HashSet has
30062        // room for the first insert).
30063        //
30064        // Peer of the sibling M2
30065        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
30066        // (bc92bce) coherence pin on the per-`:supervisor` static-
30067        // child-list axis, extended onto the M3 per-`:placement`
30068        // distribution-target-list `Vec`-carry axis.
30069
30070        // (1) Pre-flight `.is_empty()` probe: the empty slice must
30071        // trip `PlacementWithoutClusters`.
30072        let mut spec = three_member_spec();
30073        spec.placement.clusters = Vec::new();
30074        match spec.validate().unwrap_err() {
30075            AplicacaoError::PlacementWithoutClusters { .. } => {}
30076            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
30077        }
30078        assert!(
30079            spec.placement.clusters().is_empty(),
30080            "the pre-flight refusal input must be the empty slice per \
30081             the accessor's projection",
30082        );
30083
30084        // (2) Per-cluster validate loop: a two-cluster cohort with an
30085        // invalid tail entry must trip `PlacementClusterInvalid` on
30086        // the tail — the loop must reach the second entry through
30087        // the accessor.
30088        let mut spec = three_member_spec();
30089        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
30090        match spec.validate().unwrap_err() {
30091            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
30092                assert_eq!(
30093                    cluster, "BAD_CLUSTER",
30094                    "PlacementClusterInvalid.cluster must carry the \
30095                     tail entry the loop reached through the accessor",
30096                );
30097            }
30098            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
30099        }
30100        assert_eq!(
30101            spec.placement.clusters().len(),
30102            2,
30103            "the per-cluster validate loop's traversal input must be \
30104             a two-element slice per the accessor's projection",
30105        );
30106
30107        // (3) Per-cluster validate loop: a two-cluster cohort that
30108        // shares a name must trip `PlacementClusterDuplicate` on the
30109        // second entry — the loop must reach both entries through the
30110        // accessor for the dedup HashSet's second insert to collide.
30111        let mut spec = three_member_spec();
30112        spec.placement.clusters = vec!["rio".into(), "rio".into()];
30113        match spec.validate().unwrap_err() {
30114            AplicacaoError::PlacementClusterDuplicate { cluster } => {
30115                assert_eq!(
30116                    cluster, "rio",
30117                    "PlacementClusterDuplicate.cluster must carry the \
30118                     shared cluster name verbatim",
30119                );
30120            }
30121            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
30122        }
30123        assert_eq!(
30124            spec.placement.clusters().len(),
30125            2,
30126            "the per-cluster validate loop's traversal input must be \
30127             a two-element slice per the accessor's projection",
30128        );
30129    }
30130
30131    #[test]
30132    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
30133        // The canonical per-`:membros` member-list-slice-shape pin:
30134        // [`AplicacaoSpec::membros`] must return the `:membros` typed
30135        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
30136        // same backing buffer the raw `self.membros.as_slice()` field
30137        // access borrows from, byte-equal across every representative
30138        // fixture in the accept-set — the empty slice (the pre-
30139        // validation sentinel every [`AplicacaoError::NoMembros`]
30140        // refusal keys off), the singleton slice (the minimal one-
30141        // Servico Aplicacao shape), and multi-entry cohorts (the peer
30142        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
30143        // load-bearing identity of the application graph).
30144        //
30145        // Pins against a future silent detour that returned
30146        // `&Vec<Membro>` (which would type-check but leak the storage-
30147        // side `Vec`'s grow/push/reserve surface no consumer of the
30148        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
30149        // (which would type-check via a coercion but silently break
30150        // every downstream caller that relied on the slice sharing the
30151        // backing buffer's identity), or an out-of-order or length-
30152        // drifted projection (which would silently split the paired
30153        // `HashSet<&str>` name-set seed's collect input from the
30154        // pre-flight `.is_empty()` refusal probe's input from the per-
30155        // member validate loop's traversal input from the
30156        // programs.yaml emitter's per-entry fan-out loop's input from
30157        // the `feira app graph` per-member print traversal's input).
30158        //
30159        // Peer of the sibling M2
30160        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
30161        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
30162        // `:supervisor` static-child-list axis and the sibling M3
30163        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
30164        // (a6e18d7) `&[String]` byte-equal pin on the per-
30165        // `:placement` distribution-target-list axis — extends the
30166        // slice-return-accessor byte-equal-projection discipline onto
30167        // the outermost M3 mesh-slot type's per-Aplicacao member-list
30168        // `Vec`-carry axis.
30169        let fixtures: Vec<Vec<Membro>> = vec![
30170            Vec::new(),
30171            vec![membro("catalog", "^0.1")],
30172            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
30173            vec![
30174                membro("catalog", "^0.1"),
30175                membro("cart", "^0.1"),
30176                membro("payment", "^0.2"),
30177            ],
30178        ];
30179        for membros in fixtures {
30180            let s = AplicacaoSpec {
30181                membros: membros.clone(),
30182                contratos: Vec::new(),
30183                politicas: MeshPolicy::default(),
30184                placement: Placement::default(),
30185                entrada: None,
30186            };
30187            assert_eq!(
30188                s.membros(),
30189                membros.as_slice(),
30190                "AplicacaoSpec::membros must return :membros verbatim \
30191                 (got {:?}, expected {:?})",
30192                s.membros(),
30193                membros.as_slice(),
30194            );
30195            assert_eq!(
30196                s.membros(),
30197                s.membros.as_slice(),
30198                "AplicacaoSpec::membros accessor and .membros.as_slice() \
30199                 field access must byte-equal — the accessor is the \
30200                 substrate-primitive typed dispatch every downstream \
30201                 member-list consumer must route through",
30202            );
30203            assert_eq!(
30204                s.membros().len(),
30205                s.membros.len(),
30206                "AplicacaoSpec::membros().len() must byte-equal \
30207                 self.membros.len() — a length-drift would silently \
30208                 split the paired `HashSet<&str>` name-set seed's \
30209                 collect input from the pre-flight `.is_empty()` \
30210                 refusal probe input from the per-member validate \
30211                 loop's traversal input",
30212            );
30213        }
30214    }
30215
30216    #[test]
30217    fn validate_reads_through_lifted_membros_accessor() {
30218        // Three-consumer coherence pin: the
30219        // [`AplicacaoSpec::validate_membros`] pre-flight
30220        // `self.membros().is_empty()` refusal probe (which must trip
30221        // [`AplicacaoError::NoMembros`] when the accessor projects the
30222        // empty slice), the same method's per-member validate loop's
30223        // `for m in self.membros()` traversal (which must reach every
30224        // entry in the same order the accessor projects, so both the
30225        // per-entry empty-`:caixa` gate that trips
30226        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
30227        // detection `insert_first_seen` that trips
30228        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
30229        // projection), and the peer [`AplicacaoSpec::validate`]'s
30230        // `HashSet<&str>` name-set seed's
30231        // `self.membros().iter().map(Membro::nome).collect()` collect
30232        // input (which every `:contratos` `:de` / `:para` membership
30233        // lookup rejects an unknown name against) must all three key
30234        // off the lifted accessor, so any future rebrand on the typed
30235        // slot's reader shape lands at exactly one place. Pins the
30236        // three-site coherence by exercising each production consumer
30237        // end-to-end: (1) the `NoMembros` refusal under the empty
30238        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
30239        // second entry of a two-member cohort whose head is valid but
30240        // tail has an empty `:caixa` (which requires the loop to
30241        // reach the second entry through the accessor), and (3) the
30242        // `MembroDuplicate` refusal fires on the second entry of a
30243        // two-member cohort that shares a `:caixa` name (which
30244        // requires the loop to reach both entries through the
30245        // accessor for the dedup HashSet's second insert to collide).
30246        //
30247        // Peer of the sibling M2
30248        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
30249        // (bc92bce) coherence pin on the per-`:supervisor` static-
30250        // child-list axis and the sibling M3
30251        // `validate_placement_reads_through_lifted_clusters_accessor`
30252        // (a6e18d7) coherence pin on the per-`:placement` distribution-
30253        // target-list axis — extends the slice-return-accessor
30254        // multi-consumer coherence discipline onto the outermost M3
30255        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
30256
30257        // (1) Pre-flight `.is_empty()` probe: the empty slice must
30258        // trip `NoMembros`.
30259        let mut spec = three_member_spec();
30260        spec.membros = Vec::new();
30261        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
30262        assert!(
30263            spec.membros().is_empty(),
30264            "the pre-flight refusal input must be the empty slice per \
30265             the accessor's projection",
30266        );
30267
30268        // (2) Per-member validate loop: a two-member cohort with an
30269        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
30270        // the tail — the loop must reach the second entry through
30271        // the accessor.
30272        let mut spec = three_member_spec();
30273        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
30274        assert_eq!(
30275            spec.validate().unwrap_err(),
30276            AplicacaoError::MembroCaixaEmpty,
30277        );
30278        assert_eq!(
30279            spec.membros().len(),
30280            2,
30281            "the per-member validate loop's traversal input must be \
30282             a two-element slice per the accessor's projection",
30283        );
30284
30285        // (3) Per-member validate loop: a two-member cohort that
30286        // shares a `:caixa` name must trip `MembroDuplicate` on the
30287        // second entry — the loop must reach both entries through the
30288        // accessor for the dedup HashSet's second insert to collide.
30289        let mut spec = three_member_spec();
30290        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
30291        match spec.validate().unwrap_err() {
30292            AplicacaoError::MembroDuplicate { caixa } => {
30293                assert_eq!(
30294                    caixa, "catalog",
30295                    "MembroDuplicate.caixa must carry the shared \
30296                     member name verbatim",
30297                );
30298            }
30299            other => panic!("expected MembroDuplicate, got {other:?}"),
30300        }
30301        assert_eq!(
30302            spec.membros().len(),
30303            2,
30304            "the per-member validate loop's traversal input must be \
30305             a two-element slice per the accessor's projection",
30306        );
30307    }
30308
30309    #[test]
30310    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
30311        // The canonical per-`:contratos` contract-list-slice-shape pin:
30312        // [`AplicacaoSpec::contratos`] must return the `:contratos`
30313        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
30314        // slice-view over the same backing buffer the raw
30315        // `self.contratos.as_slice()` field access borrows from, byte-
30316        // equal across every representative fixture in the accept-set —
30317        // the empty slice (the pre-validation "internal-only mesh" shape
30318        // an Aplicacao whose members exchange no typed edges renders
30319        // through), the singleton slice (the minimal one-edge Aplicacao
30320        // shape), and multi-entry cohorts (the peer multi-edge shapes
30321        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
30322        // of the application graph).
30323        //
30324        // Pins against a future silent detour that returned
30325        // `&Vec<WitContract>` (which would type-check but leak the
30326        // storage-side `Vec`'s grow/push/reserve surface no consumer of
30327        // the typed view reaches for), a fresh-allocated
30328        // `Vec<WitContract>` copy (which would type-check via a coercion
30329        // but silently break every downstream caller that relied on the
30330        // slice sharing the backing buffer's identity), or an out-of-
30331        // order or length-drifted projection (which would silently split
30332        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
30333        // seed's traversal input from the `detect_sync_cycles` per-edge
30334        // adjacency-list seed's traversal input from the
30335        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
30336        // BTreeMap grouping loop's traversal input from the
30337        // `feira app graph` per-contract print traversal's input).
30338        //
30339        // Peer of the immediately-adjacent sibling M3
30340        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
30341        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
30342        // node-list axis, the sibling M3
30343        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
30344        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
30345        // distribution-target-list axis, and the sibling M2
30346        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
30347        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
30348        // `:supervisor` static-child-list axis — extends the slice-
30349        // return-accessor byte-equal-projection discipline onto the
30350        // outermost M3 mesh-slot type's per-Aplicacao contract-list
30351        // `Vec`-carry axis, closing the last unlifted per-
30352        // `AplicacaoSpec` `Vec`-carry axis.
30353        let fixtures: Vec<Vec<WitContract>> = vec![
30354            Vec::new(),
30355            vec![contract_http("cart", "catalog", "/products/:id")],
30356            vec![
30357                contract_http("cart", "catalog", "/products/:id"),
30358                contract_http("cart", "payment", "/charge"),
30359            ],
30360            vec![
30361                contract_http("cart", "catalog", "/products/:id"),
30362                contract_http("cart", "payment", "/charge"),
30363                contract_http("payment", "catalog", "/audit"),
30364            ],
30365        ];
30366        for contratos in fixtures {
30367            let s = AplicacaoSpec {
30368                membros: vec![
30369                    membro("catalog", "^0.1"),
30370                    membro("cart", "^0.1"),
30371                    membro("payment", "^0.2"),
30372                ],
30373                contratos: contratos.clone(),
30374                politicas: MeshPolicy::default(),
30375                placement: Placement::default(),
30376                entrada: None,
30377            };
30378            assert_eq!(
30379                s.contratos(),
30380                contratos.as_slice(),
30381                "AplicacaoSpec::contratos must return :contratos verbatim \
30382                 (got {:?}, expected {:?})",
30383                s.contratos(),
30384                contratos.as_slice(),
30385            );
30386            assert_eq!(
30387                s.contratos(),
30388                s.contratos.as_slice(),
30389                "AplicacaoSpec::contratos accessor and \
30390                 .contratos.as_slice() field access must byte-equal — \
30391                 the accessor is the substrate-primitive typed dispatch \
30392                 every downstream contract-list consumer must route \
30393                 through",
30394            );
30395            assert_eq!(
30396                s.contratos().len(),
30397                s.contratos.len(),
30398                "AplicacaoSpec::contratos().len() must byte-equal \
30399                 self.contratos.len() — a length-drift would silently \
30400                 split the paired per-edge validate-loop's traversal \
30401                 input from the sync-cycle adjacency-list seed's \
30402                 traversal input from the cilium_network_policies \
30403                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
30404                 input from the `feira app graph` per-contract print \
30405                 traversal's input",
30406            );
30407        }
30408    }
30409
30410    #[test]
30411    fn validate_reads_through_lifted_contratos_accessor() {
30412        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
30413        // per-`:contratos` validate-loop's `for c in self.contratos()`
30414        // traversal (which must reach every entry in the same order the
30415        // accessor projects, so both the per-entry
30416        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
30417        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
30418        // dedup `HashSet` insert key off the accessor's projection),
30419        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
30420        // `for c in self.contratos()` adjacency-list seed (which drives
30421        // the sync-subgraph deadlock-detection gate via
30422        // [`AplicacaoError::SyncCycle`]), and the peer
30423        // [`caixa_mesh::cilium_network_policies`]'s
30424        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
30425        // grouping loop (which drives the per-CNP fan-out) must all
30426        // three key off the lifted accessor, so any future rebrand on
30427        // the typed slot's reader shape lands at exactly one place. Pins
30428        // the three-site coherence by exercising the two caixa-core
30429        // production consumers end-to-end: (1) the empty-`:contratos`
30430        // slice must validate without a per-edge diagnostic (the
30431        // per-edge loop is a no-op under the empty projection), (2) the
30432        // `ContratoMemberMissing` refusal fires on the second entry of a
30433        // two-edge cohort whose head references a valid member but tail
30434        // references a phantom name (which requires the loop to reach
30435        // the second entry through the accessor), and (3) the
30436        // `SyncCycle` refusal fires on a self-referential two-edge
30437        // cohort through the sync-cycle detector's peer projection
30438        // (which requires the detector to iterate the accessor's
30439        // projection to add the back-edge to its adjacency list).
30440        //
30441        // Peer of the sibling M3
30442        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
30443        // three-consumer coherence pin on the per-`:membros` node-list
30444        // axis and the sibling M3
30445        // `validate_placement_reads_through_lifted_clusters_accessor`
30446        // (a6e18d7) coherence pin on the per-`:placement` distribution-
30447        // target-list axis — extends the slice-return-accessor multi-
30448        // consumer coherence discipline onto the outermost M3 mesh-slot
30449        // type's per-Aplicacao contract-list `Vec`-carry axis.
30450
30451        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
30452        // and no per-edge diagnostic surfaces. Validate succeeds on
30453        // the well-formed `:membros` head.
30454        let mut spec = three_member_spec();
30455        spec.contratos = Vec::new();
30456        assert!(
30457            spec.validate().is_ok(),
30458            "empty :contratos must validate — the per-edge loop is a \
30459             no-op under the accessor's empty projection",
30460        );
30461        assert!(
30462            spec.contratos().is_empty(),
30463            "the per-edge validate loop's traversal input must be the \
30464             empty slice per the accessor's projection",
30465        );
30466
30467        // (2) Per-edge validate loop: a two-edge cohort whose tail
30468        // references a phantom `:para` member must trip
30469        // `ContratoMemberMissing` on the tail — the loop must reach
30470        // the second entry through the accessor for the membership
30471        // lookup to fail on the phantom name.
30472        let mut spec = three_member_spec();
30473        spec.contratos = vec![
30474            contract_http("cart", "catalog", "/products/:id"),
30475            contract_http("cart", "phantom", "/x"),
30476        ];
30477        let err = spec.validate().unwrap_err();
30478        assert!(
30479            matches!(
30480                err,
30481                AplicacaoError::ContratoMemberMissing { ref caixa }
30482                    if caixa == "phantom"
30483            ),
30484            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
30485        );
30486        assert_eq!(
30487            spec.contratos().len(),
30488            2,
30489            "the per-edge validate loop's traversal input must be \
30490             a two-element slice per the accessor's projection",
30491        );
30492
30493        // (3) Sync-cycle detector: a two-edge synchronous cohort
30494        // whose second edge closes the sync-subgraph back onto the
30495        // first must trip [`AplicacaoError::ContratoCycle`] — the
30496        // detector must iterate the accessor's projection to add
30497        // both edges to its adjacency list, so a length-drift on
30498        // the accessor's projection would silently disagree with
30499        // the sync-cycle detector on which edge closes the loop.
30500        // Peer projection to the `validate` per-edge loop above:
30501        // the sync-cycle detector routes through the same lifted
30502        // accessor, so a rebrand of the reader shape lands at one
30503        // place. Uses a two-edge cohort (cart → catalog → cart)
30504        // because the per-edge `ContratoSelfLoop` gate fires before
30505        // the sync-cycle detector on a single self-referential edge
30506        // (`cart → cart`) — the cycle-detector's input must be a
30507        // multi-edge cohort for its per-edge traversal input to be
30508        // observably wider than the per-edge validate loop's input.
30509        let mut spec = three_member_spec();
30510        spec.contratos = vec![
30511            contract_http("cart", "catalog", "/products/:id"),
30512            contract_http("catalog", "cart", "/callback"),
30513        ];
30514        let err = spec.validate().unwrap_err();
30515        assert!(
30516            matches!(err, AplicacaoError::ContratoCycle { .. }),
30517            "expected ContratoCycle from the sync-cycle detector on a \
30518             two-edge back-edge cohort, got {err:?}",
30519        );
30520        assert_eq!(
30521            spec.contratos().len(),
30522            2,
30523            "the sync-cycle detector's traversal input must be a \
30524             two-element slice per the accessor's projection",
30525        );
30526    }
30527
30528    #[test]
30529    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
30530        // The canonical per-`:politicas` outer-composite-reference-shape
30531        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
30532        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
30533        // the same backing storage the raw `&self.politicas` field
30534        // access borrows from, byte-equal across every representative
30535        // fixture in the accept-set — the default `MeshPolicy` (the
30536        // author-empty "no policy on any axis" shape whose
30537        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
30538        // shapes carrying one axis at a time
30539        // (`{mtls_required, timeout, retries, circuit_breaker,
30540        // rate_limit}` — the minimal five-axis fan-out over the
30541        // per-axis lifted accessor family every downstream mesh-artifact
30542        // emitter dispatches on), and the multi-axis composite (the
30543        // canonical `three_member_spec` fixture's `{timeout, retries,
30544        // mtls_required}` triple — the load-bearing shape every
30545        // Aplicacao-scoped fixture in this suite constructs).
30546        //
30547        // Pins against a future silent detour that returned a fresh-
30548        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
30549        // impl but silently break every downstream caller that relied
30550        // on the reference sharing the composite's backing identity), a
30551        // reference to an operator-resolved overlay (the future
30552        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
30553        // acknowledges — its resolution must land at exactly this
30554        // accessor body, not silently divert the raw slot away from a
30555        // second consumer), or an axis-shuffled projection (a future
30556        // detour that swapped `timeout` and `retries` through the
30557        // accessor would silently split the paired `validate_politicas`
30558        // per-axis bracket-dispatch's traversal input from the peer
30559        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
30560        // emitter's fan-out input from the peer
30561        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
30562        // overlay emitter's fan-out input).
30563        //
30564        // Peer of the sibling M3
30565        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
30566        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
30567        // node-list `Vec`-carry axis and the sibling M3
30568        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
30569        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
30570        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
30571        // accessor byte-equal-projection discipline onto the outermost
30572        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
30573        // reference axis, the first `&Composite`-return accessor on the
30574        // outer [`AplicacaoSpec`] type.
30575        let fixtures: Vec<MeshPolicy> = vec![
30576            MeshPolicy::default(),
30577            MeshPolicy {
30578                mtls_required: Some(true),
30579                ..MeshPolicy::default()
30580            },
30581            MeshPolicy {
30582                mtls_required: Some(false),
30583                ..MeshPolicy::default()
30584            },
30585            MeshPolicy {
30586                timeout: Some(Duration::from_secs(30)),
30587                ..MeshPolicy::default()
30588            },
30589            MeshPolicy {
30590                retries: Some(3),
30591                ..MeshPolicy::default()
30592            },
30593            MeshPolicy {
30594                circuit_breaker: Some(CircuitBreaker {
30595                    max_failures: 5,
30596                    window: Duration::from_secs(30),
30597                }),
30598                ..MeshPolicy::default()
30599            },
30600            MeshPolicy {
30601                rate_limit: Some(RateLimit {
30602                    rate: 100,
30603                    window: Duration::from_secs(1),
30604                }),
30605                ..MeshPolicy::default()
30606            },
30607            MeshPolicy {
30608                timeout: Some(Duration::from_secs(30)),
30609                retries: Some(3),
30610                mtls_required: Some(true),
30611                ..MeshPolicy::default()
30612            },
30613        ];
30614        for politicas in fixtures {
30615            let s = AplicacaoSpec {
30616                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
30617                contratos: Vec::new(),
30618                politicas: politicas.clone(),
30619                placement: Placement::default(),
30620                entrada: None,
30621            };
30622            assert_eq!(
30623                *s.politicas(),
30624                politicas,
30625                "AplicacaoSpec::politicas must return :politicas verbatim \
30626                 (got {:?}, expected {:?})",
30627                s.politicas(),
30628                politicas,
30629            );
30630            assert!(
30631                std::ptr::eq(s.politicas(), &s.politicas),
30632                "AplicacaoSpec::politicas accessor and &self.politicas \
30633                 field access must borrow the same backing storage — \
30634                 the accessor is the substrate-primitive typed dispatch \
30635                 every downstream mesh-policy composite consumer must \
30636                 route through, and a reference-identity split would \
30637                 silently break every consumer that relied on the \
30638                 borrow sharing the composite's storage",
30639            );
30640            assert_eq!(
30641                s.politicas().is_empty(),
30642                s.politicas.is_empty(),
30643                "AplicacaoSpec::politicas().is_empty() must byte-equal \
30644                 self.politicas.is_empty() — an emptiness-drift would \
30645                 silently split the paired `validate_politicas` \
30646                 per-axis bracket-dispatch's seed from the peer \
30647                 caixa-mesh CNP mTLS-overlay emitter's key from the \
30648                 peer caixa-mesh HTTPRoute timeout+retry overlay \
30649                 emitter's key",
30650            );
30651        }
30652    }
30653
30654    #[test]
30655    fn validate_politicas_reads_through_lifted_politicas_accessor() {
30656        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
30657        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
30658        // followed by the per-axis fan-out `p.timeout()` /
30659        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
30660        // the lifted axis-level accessor family) must key off the
30661        // lifted outer accessor, so any future rebrand on the typed
30662        // slot's outer-composite reader shape lands at exactly one
30663        // place. Pins the multi-axis coherence by exercising each
30664        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
30665        // a `Some(Duration::ZERO)` timeout under the outer accessor's
30666        // reference projection, (2) `PolicyRetriesZero` fires on a
30667        // `Some(0)` retries under the same projection, and (3) an
30668        // empty [`MeshPolicy::default`] passes `validate_politicas` —
30669        // the outer accessor's reference-projection reaches every
30670        // per-axis branch without silently short-circuiting any.
30671        //
30672        // Peer of the sibling M3
30673        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
30674        // three-consumer coherence pin on the per-`:membros` node-list
30675        // axis and the sibling M3
30676        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
30677        // three-consumer coherence pin on the per-`:contratos`
30678        // edge-list axis — extends the multi-consumer coherence
30679        // discipline onto the outermost M3 mesh-slot type's per-
30680        // Aplicacao mesh-policy composite-reference axis, the first
30681        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
30682        // type.
30683
30684        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
30685        // reference projection: a `Some(Duration::ZERO)` timeout must
30686        // trip the zero-floor gate. The bracket-dispatch's first arm
30687        // reads `p.timeout()` on the reference returned by the outer
30688        // accessor.
30689        let mut spec = three_member_spec();
30690        spec.politicas.timeout = Some(Duration::ZERO);
30691        spec.politicas.retries = None;
30692        spec.politicas.circuit_breaker = None;
30693        spec.politicas.rate_limit = None;
30694        assert_eq!(
30695            spec.validate().unwrap_err(),
30696            AplicacaoError::PolicyTimeoutZero,
30697        );
30698        assert!(
30699            std::ptr::eq(spec.politicas(), &spec.politicas),
30700            "the `validate_politicas` per-axis bracket-dispatch's \
30701             traversal input must be the same backing composite the \
30702             accessor's reference projection borrows from",
30703        );
30704
30705        // (2) `PolicyRetriesZero` refusal under the outer accessor's
30706        // reference projection: a `Some(0)` retries must trip the
30707        // zero-floor gate. The bracket-dispatch's second arm reads
30708        // `p.retries()` on the reference returned by the outer accessor.
30709        let mut spec = three_member_spec();
30710        spec.politicas.timeout = None;
30711        spec.politicas.retries = Some(0);
30712        spec.politicas.circuit_breaker = None;
30713        spec.politicas.rate_limit = None;
30714        assert_eq!(
30715            spec.validate().unwrap_err(),
30716            AplicacaoError::PolicyRetriesZero,
30717        );
30718
30719        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
30720        // — every per-axis arm short-circuits on `None`, so the outer
30721        // accessor's reference projection reaches the fall-through
30722        // `Ok(())` without any per-axis refusal firing.
30723        let mut spec = three_member_spec();
30724        spec.politicas = MeshPolicy::default();
30725        assert!(
30726            spec.validate().is_ok(),
30727            "an empty `MeshPolicy` must pass `validate_politicas` — \
30728             every per-axis arm short-circuits on `None` under the \
30729             outer accessor's reference projection",
30730        );
30731        assert!(
30732            spec.politicas().is_empty(),
30733            "the outer accessor's reference projection must be the \
30734             empty composite per the `MeshPolicy::default()` fixture",
30735        );
30736    }
30737
30738    #[test]
30739    #[allow(clippy::too_many_lines)]
30740    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
30741        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
30742        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
30743        // must both key off the lifted axis-level accessors
30744        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
30745        // the peer `:circuit-breaker` / `:rate-limit` arms already
30746        // routing through [`MeshPolicy::circuit_breaker`] /
30747        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
30748        // per axis on the substrate primitive" shape at the fan-out
30749        // (four axes, four accessors, no raw-field-access site
30750        // anywhere on the bracket-dispatch). Pins the per-axis
30751        // coherence at the accept-set boundaries the bracket carves:
30752        //   1. accessor byte-equal to raw field on every representative
30753        //      accept-set value (`None`, sub-cap, at-cap, past-cap
30754        //      sentinel) — a future accessor drift that no longer
30755        //      shipped the raw slot verbatim would surface here,
30756        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
30757        //      routed through the accessor's projection, proving the
30758        //      first arm reads through the accessor rather than a
30759        //      silent-detour peer-axis field access,
30760        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
30761        //      through the accessor's projection, proving the second
30762        //      arm reads through the accessor,
30763        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
30764        //      passes validate under the accessor projection (paired
30765        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
30766        //      sibling axis), pinning the upper-boundary accept-arm
30767        //      also routes through the accessor.
30768        //
30769        // Peer of the sibling M3
30770        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
30771        // outer-composite-reference coherence pin (which asserts the
30772        // `let p = self.politicas()` seed); extends the discipline onto
30773        // the per-axis fan-out layer that consumes the seed's
30774        // reference. Same shape as
30775        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
30776        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
30777        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
30778        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
30779
30780        // (1) Accessor byte-equal to raw field on the `:timeout` axis
30781        // across the accept-set boundaries the bracket dispatch's
30782        // three-arm gate carves out
30783        // ([`crate::render::require_positive_canonical_bounded_duration`]
30784        // — zero-floor + canonical-form + upper-cap).
30785        for timeout in [
30786            None,
30787            Some(Duration::ZERO),
30788            Some(Duration::from_millis(1)),
30789            Some(POLICY_TIMEOUT_MAX),
30790        ] {
30791            let p = MeshPolicy {
30792                timeout,
30793                ..MeshPolicy::default()
30794            };
30795            assert_eq!(
30796                p.timeout(),
30797                p.timeout,
30798                "MeshPolicy::timeout accessor must byte-equal the raw \
30799                 .timeout field across every accept-set boundary the \
30800                 validate_politicas :timeout arm carves out — a drift \
30801                 here would silently split the validate bracket's arm \
30802                 from the peer caixa-mesh HTTPRoute timeout-overlay \
30803                 emitter's read",
30804            );
30805        }
30806
30807        // (2) Accessor byte-equal to raw field on the `:retries` axis
30808        // across the accept-set boundaries the bracket dispatch's
30809        // two-arm gate carves out
30810        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
30811        // + upper-cap).
30812        for retries in [
30813            None,
30814            Some(0u32),
30815            Some(1u32),
30816            Some(POLICY_RETRIES_MAX),
30817            Some(POLICY_RETRIES_MAX + 1),
30818            Some(u32::MAX),
30819        ] {
30820            let p = MeshPolicy {
30821                retries,
30822                ..MeshPolicy::default()
30823            };
30824            assert_eq!(
30825                p.retries(),
30826                p.retries,
30827                "MeshPolicy::retries accessor must byte-equal the raw \
30828                 .retries field across every accept-set boundary the \
30829                 validate_politicas :retries arm carves out — a drift \
30830                 here would silently split the validate bracket's arm \
30831                 from the peer caixa-mesh HTTPRoute retry-overlay \
30832                 emitter's read",
30833            );
30834        }
30835
30836        // (3) `PolicyTimeoutZero` fires on the accessor-projected
30837        // zero-floor boundary. A silent detour that no longer read
30838        // through `p.timeout()` (a peer-axis field read, an accidental
30839        // Option::and-then chain that collapsed the None arm to Some,
30840        // an accessor rebrand that clamped the return through the
30841        // upper cap) would fail to refuse here.
30842        let mut spec = three_member_spec();
30843        spec.politicas.timeout = Some(Duration::ZERO);
30844        spec.politicas.retries = None;
30845        spec.politicas.circuit_breaker = None;
30846        spec.politicas.rate_limit = None;
30847        assert_eq!(
30848            spec.politicas().timeout(),
30849            Some(Duration::ZERO),
30850            "the accessor projection must reflect the fixture's \
30851             `Some(Duration::ZERO)` :timeout verbatim",
30852        );
30853        assert_eq!(
30854            spec.validate().unwrap_err(),
30855            AplicacaoError::PolicyTimeoutZero,
30856            "the validate_politicas :timeout zero-floor arm must fire \
30857             through the lifted accessor's projection — a silent \
30858             detour to a peer-axis field would fail to refuse",
30859        );
30860
30861        // (4) `PolicyRetriesZero` fires on the accessor-projected
30862        // zero-floor boundary on the sibling `:retries` axis.
30863        let mut spec = three_member_spec();
30864        spec.politicas.timeout = None;
30865        spec.politicas.retries = Some(0);
30866        spec.politicas.circuit_breaker = None;
30867        spec.politicas.rate_limit = None;
30868        assert_eq!(
30869            spec.politicas().retries(),
30870            Some(0),
30871            "the accessor projection must reflect the fixture's \
30872             `Some(0)` :retries verbatim",
30873        );
30874        assert_eq!(
30875            spec.validate().unwrap_err(),
30876            AplicacaoError::PolicyRetriesZero,
30877            "the validate_politicas :retries zero-floor arm must fire \
30878             through the lifted accessor's projection — a silent \
30879             detour to a peer-axis field would fail to refuse",
30880        );
30881
30882        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
30883        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
30884        // must pass validate under the accessor projection — pins the
30885        // upper-boundary accept-arm also routes through the lifted
30886        // accessor (a drift that clamped or short-circuited at the
30887        // upper boundary would fail the whole-spec validate here).
30888        let mut spec = three_member_spec();
30889        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
30890        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
30891        spec.politicas.circuit_breaker = None;
30892        spec.politicas.rate_limit = None;
30893        assert_eq!(
30894            spec.politicas().timeout(),
30895            Some(POLICY_TIMEOUT_MAX),
30896            "the accessor projection must reflect the fixture's \
30897             at-cap :timeout verbatim",
30898        );
30899        assert_eq!(
30900            spec.politicas().retries(),
30901            Some(POLICY_RETRIES_MAX),
30902            "the accessor projection must reflect the fixture's \
30903             at-cap :retries verbatim",
30904        );
30905        assert!(
30906            spec.validate().is_ok(),
30907            "at-cap :timeout + :retries must pass validate under the \
30908             accessor projection — the upper-boundary accept-arm on \
30909             both axes routes through the lifted accessor",
30910        );
30911    }
30912
30913    #[test]
30914    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
30915        // The canonical per-`:placement` outer-composite-reference-shape
30916        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
30917        // typed `Placement` verbatim as a `&Placement` reference over the
30918        // same backing storage the raw `&self.placement` field access
30919        // borrows from, byte-equal across every representative fixture in
30920        // the accept-set — the default `Placement` (the substrate seed
30921        // shape whose [`PlacementStrategy::default`] evaluates to
30922        // `SingleNode` with an empty `:clusters` pool and both
30923        // optional-scalar axes `None`), and every canonical strategy /
30924        // cluster-pool / optional-scalar combination the
30925        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
30926        // three [`PlacementStrategy`] variants — `SingleNode`,
30927        // `Replicated`, `Sharded` — cross-projected with a non-empty
30928        // `:clusters` pool and, on the `Sharded` arm, a non-empty
30929        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
30930        // canonical `three_member_spec` `Replicated` fixture's
30931        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
30932        //
30933        // Pins against a future silent detour that returned a fresh-
30934        // cloned `Placement` copy (which would type-check via a `Clone`
30935        // impl but silently break every downstream caller that relied on
30936        // the reference sharing the composite's backing identity), a
30937        // reference to an operator-resolved overlay (the future per-
30938        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
30939        // acknowledges — its resolution must land at exactly this
30940        // accessor body, not silently divert the raw slot away from a
30941        // second consumer), or an axis-shuffled projection (a future
30942        // detour that swapped `clusters` and `affinity` through the
30943        // accessor would silently split the paired `validate_placement`
30944        // per-axis bracket-dispatch's traversal input from the peer
30945        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
30946        // programs.yaml distribution-annotation emitter's fan-out input
30947        // from the peer `feira app graph` per-Aplicacao print line's
30948        // input).
30949        //
30950        // Peer of the sibling M3
30951        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
30952        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
30953        // outer mesh-policy composite-reference axis, and of the sibling
30954        // slice-return `aplicacao_spec_membros_returns_membros_slice_
30955        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
30956        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
30957        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
30958        // the outer-accessor byte-equal-projection discipline onto the
30959        // outermost M3 mesh-slot type's per-Aplicacao distribution
30960        // composite-reference axis, the second `&Composite`-return
30961        // accessor on the outer [`AplicacaoSpec`] type.
30962        let fixtures: Vec<Placement> = vec![
30963            Placement::default(),
30964            Placement {
30965                estrategia: PlacementStrategy::SingleNode,
30966                clusters: vec!["rio".into()],
30967                affinity: None,
30968                shard_key: None,
30969            },
30970            Placement {
30971                estrategia: PlacementStrategy::Replicated,
30972                clusters: vec!["rio".into(), "mar".into()],
30973                affinity: None,
30974                shard_key: None,
30975            },
30976            Placement {
30977                estrategia: PlacementStrategy::Replicated,
30978                clusters: vec!["rio".into(), "mar".into()],
30979                affinity: Some("data-locality".into()),
30980                shard_key: None,
30981            },
30982            Placement {
30983                estrategia: PlacementStrategy::Sharded,
30984                clusters: vec!["rio".into(), "mar".into()],
30985                affinity: None,
30986                shard_key: Some("tenantId".into()),
30987            },
30988            Placement {
30989                estrategia: PlacementStrategy::Sharded,
30990                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
30991                affinity: Some("low-latency".into()),
30992                shard_key: Some("metadata.tenantId".into()),
30993            },
30994        ];
30995        for placement in fixtures {
30996            let s = AplicacaoSpec {
30997                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
30998                contratos: Vec::new(),
30999                politicas: MeshPolicy::default(),
31000                placement: placement.clone(),
31001                entrada: None,
31002            };
31003            assert_eq!(
31004                *s.placement(),
31005                placement,
31006                "AplicacaoSpec::placement must return :placement verbatim \
31007                 (got {:?}, expected {:?})",
31008                s.placement(),
31009                placement,
31010            );
31011            assert!(
31012                std::ptr::eq(s.placement(), &s.placement),
31013                "AplicacaoSpec::placement accessor and &self.placement \
31014                 field access must borrow the same backing storage — the \
31015                 accessor is the substrate-primitive typed dispatch every \
31016                 downstream distribution-composite consumer must route \
31017                 through, and a reference-identity split would silently \
31018                 break every consumer that relied on the borrow sharing \
31019                 the composite's storage",
31020            );
31021            assert_eq!(
31022                s.placement().estrategia(),
31023                s.placement.estrategia,
31024                "AplicacaoSpec::placement().estrategia() must byte-equal \
31025                 self.placement.estrategia — a strategy-drift would \
31026                 silently split the paired `validate_placement` \
31027                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
31028                 peer caixa-mesh programs.yaml `placement.estrategia` \
31029                 emitter's key from the peer `feira app graph` printer's \
31030                 strategy label",
31031            );
31032            assert_eq!(
31033                s.placement().clusters(),
31034                s.placement.clusters.as_slice(),
31035                "AplicacaoSpec::placement().clusters() must byte-equal \
31036                 self.placement.clusters — a cluster-pool drift would \
31037                 silently split the paired `validate_placement` \
31038                 pre-flight `.is_empty()` refusal probe's traversal from \
31039                 the peer caixa-mesh programs.yaml `placement.clusters` \
31040                 emitter's fan-out from the peer `feira app graph` \
31041                 printer's cluster list",
31042            );
31043        }
31044    }
31045
31046    #[test]
31047    fn validate_placement_reads_through_lifted_placement_accessor() {
31048        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
31049        // per-axis bracket-dispatch seed (`let p = self.placement();`,
31050        // followed by the per-axis fan-out `p.clusters()` /
31051        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
31052        // lifted axis-level accessor family) must key off the lifted
31053        // outer accessor, so any future rebrand on the typed slot's
31054        // outer-composite reader shape lands at exactly one place. Pins
31055        // the multi-axis coherence by exercising each per-axis refusal
31056        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
31057        // `:clusters` pool under the outer accessor's reference
31058        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
31059        // strategy with a `None` `:shard-key` under the same projection,
31060        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
31061        // with a `Some` `:shard-key` under the same projection, and
31062        // (4) the canonical `three_member_spec` `Replicated` fixture
31063        // passes `validate_placement` under the outer accessor's
31064        // reference projection — the accessor's reference-projection
31065        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
31066        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
31067        // without silently short-circuiting any.
31068        //
31069        // Peer of the sibling M3
31070        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
31071        // (534dc21) multi-axis coherence pin on the per-`:politicas`
31072        // outer mesh-policy composite-reference axis — extends the
31073        // multi-consumer coherence discipline onto the outermost M3
31074        // mesh-slot type's per-Aplicacao distribution composite-
31075        // reference axis, the second `&Composite`-return accessor on
31076        // the outer [`AplicacaoSpec`] type.
31077
31078        // (1) `PlacementWithoutClusters` refusal under the outer
31079        // accessor's reference projection: an empty `:clusters` pool
31080        // must trip the pre-flight refusal probe. The bracket-dispatch's
31081        // first arm reads `p.clusters()` on the reference returned by
31082        // the outer accessor.
31083        let mut spec = three_member_spec();
31084        spec.placement.clusters = Vec::new();
31085        assert_eq!(
31086            spec.validate().unwrap_err(),
31087            AplicacaoError::PlacementWithoutClusters {
31088                estrategia: PlacementStrategy::Replicated,
31089            },
31090        );
31091        assert!(
31092            std::ptr::eq(spec.placement(), &spec.placement),
31093            "the `validate_placement` per-axis bracket-dispatch's \
31094             traversal input must be the same backing composite the \
31095             accessor's reference projection borrows from",
31096        );
31097
31098        // (2) `ShardedWithoutKey` refusal under the outer accessor's
31099        // reference projection: a `Sharded` strategy with a `None`
31100        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
31101        // The bracket-dispatch's third arm reads `p.estrategia()` for
31102        // the match scrutinee then `p.shard_key()` for the cascade
31103        // scrutinee, both on the reference returned by the outer
31104        // accessor.
31105        let mut spec = three_member_spec();
31106        spec.placement.estrategia = PlacementStrategy::Sharded;
31107        spec.placement.shard_key = None;
31108        assert_eq!(
31109            spec.validate().unwrap_err(),
31110            AplicacaoError::ShardedWithoutKey,
31111        );
31112
31113        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
31114        // reference projection: a non-`Sharded` strategy with a `Some`
31115        // `:shard-key` must trip the declared-but-inert refusal. The
31116        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
31117        // + `p.estrategia()` for the diagnostic on the reference
31118        // returned by the outer accessor.
31119        let mut spec = three_member_spec();
31120        spec.placement.estrategia = PlacementStrategy::Replicated;
31121        spec.placement.shard_key = Some("tenantId".into());
31122        assert_eq!(
31123            spec.validate().unwrap_err(),
31124            AplicacaoError::ShardKeyOnNonSharded {
31125                estrategia: PlacementStrategy::Replicated,
31126                shard_key: "tenantId".into(),
31127            },
31128        );
31129
31130        // (4) Canonical `three_member_spec` `Replicated` fixture passes
31131        // `validate_placement` — every per-axis arm reaches the fall-
31132        // through `Ok(())` without any per-axis refusal firing under the
31133        // outer accessor's reference projection.
31134        let spec = three_member_spec();
31135        assert!(
31136            spec.validate().is_ok(),
31137            "the canonical Replicated placement fixture must pass \
31138             `validate_placement` — every per-axis arm short-circuits on \
31139             valid input under the outer accessor's reference projection",
31140        );
31141        assert_eq!(
31142            spec.placement().estrategia(),
31143            PlacementStrategy::Replicated,
31144            "the outer accessor's reference projection must be the \
31145             canonical Replicated fixture's strategy",
31146        );
31147        assert_eq!(
31148            spec.placement().clusters(),
31149            &["rio", "mar"],
31150            "the outer accessor's reference projection must be the \
31151             canonical Replicated fixture's cluster pool",
31152        );
31153    }
31154
31155    #[test]
31156    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
31157        // The canonical per-`:entrada` outer-composite-optional-
31158        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
31159        // the `:entrada` typed `Option<Entrada>` verbatim as an
31160        // `Option<&Entrada>` reference over the same backing storage
31161        // the raw `self.entrada.as_ref()` field access borrows from,
31162        // byte-equal across every representative fixture in the
31163        // accept-set — the author-omitted `None` shape (the
31164        // "internal-only mesh" partition every downstream external-
31165        // gateway emitter treats as "emit nothing"), the minimal
31166        // singleton `:entrada` composite (host + destination + empty
31167        // paths + default port), the paths-carrying composite (the
31168        // canonical `three_member_spec` fixture's ["/api" "/health"]
31169        // path-list shape every HTTPRoute per-rule fan-out emitter
31170        // reads), and the non-default port composite (the canonical
31171        // custom-port shape the port-fallback resolver reads).
31172        //
31173        // Pins against a future silent detour that returned a fresh-
31174        // cloned `Entrada` copy (which would type-check via a `Clone`
31175        // impl but silently break every downstream caller that
31176        // relied on the reference sharing the composite's backing
31177        // identity), a reference to an operator-resolved overlay
31178        // (the future per-cluster `:entrada-overrides` slot the
31179        // MESH-COMPOSITION §V federation roadmap acknowledges — its
31180        // resolution must land at exactly this accessor body, not
31181        // silently divert the raw slot away from a second consumer),
31182        // a `None` → `Some(Entrada::default)` cluster-default
31183        // projection (which would collapse the load-bearing
31184        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
31185        // the peer `gateway_routes` early-return + `feira app graph`
31186        // internal-only-mesh partition both read), or an axis-
31187        // shuffled projection (a future detour that swapped
31188        // `host` and `para` through the accessor would silently
31189        // split the paired `validate` per-`:entrada` shape-and-
31190        // membership gate's traversal input from the peer
31191        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
31192        // fan-out input from the peer `feira app graph` external-
31193        // gateway summary line).
31194        //
31195        // Peer of the sibling M3
31196        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
31197        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
31198        // `:politicas` outer mesh-policy composite-reference axis
31199        // and of the sibling M3
31200        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
31201        // (9abb8f0) `&Placement` byte-equal pin on the per-
31202        // `:placement` outer distribution-composite composite-
31203        // reference axis — extends the outer-accessor byte-equal-
31204        // projection discipline onto the last unlifted outermost M3
31205        // mesh-slot type's per-Aplicacao external-gateway composite-
31206        // reference axis, the third and final `&Composite`-return
31207        // accessor on the outer [`AplicacaoSpec`] type.
31208        let fixtures: Vec<Option<Entrada>> = vec![
31209            None,
31210            Some(Entrada {
31211                host: "checkout.quero.cloud".into(),
31212                para: "cart".into(),
31213                paths: Vec::new(),
31214                port: DEFAULT_SERVICO_PORT,
31215            }),
31216            Some(Entrada {
31217                host: "checkout.quero.cloud".into(),
31218                para: "cart".into(),
31219                paths: vec!["/api".into(), "/health".into()],
31220                port: DEFAULT_SERVICO_PORT,
31221            }),
31222            Some(Entrada {
31223                host: "checkout.quero.cloud".into(),
31224                para: "cart".into(),
31225                paths: vec!["/api".into()],
31226                port: 9443,
31227            }),
31228        ];
31229        for entrada in fixtures {
31230            let s = AplicacaoSpec {
31231                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
31232                contratos: Vec::new(),
31233                politicas: MeshPolicy::default(),
31234                placement: Placement::default(),
31235                entrada: entrada.clone(),
31236            };
31237            assert_eq!(
31238                s.entrada(),
31239                entrada.as_ref(),
31240                "AplicacaoSpec::entrada must return :entrada verbatim \
31241                 (got {:?}, expected {:?})",
31242                s.entrada(),
31243                entrada.as_ref(),
31244            );
31245            match (s.entrada(), s.entrada.as_ref()) {
31246                (Some(a), Some(b)) => assert!(
31247                    std::ptr::eq(a, b),
31248                    "AplicacaoSpec::entrada accessor and \
31249                     self.entrada.as_ref() field access must borrow \
31250                     the same backing storage — the accessor is the \
31251                     substrate-primitive typed dispatch every \
31252                     downstream external-gateway composite consumer \
31253                     must route through, and a reference-identity \
31254                     split would silently break every consumer that \
31255                     relied on the borrow sharing the composite's \
31256                     storage",
31257                ),
31258                (None, None) => {}
31259                _ => panic!(
31260                    "AplicacaoSpec::entrada presence bit must byte-\
31261                     equal self.entrada.is_some() — a presence-bit \
31262                     drift would silently split the paired `validate` \
31263                     per-`:entrada` shape-and-membership gate's \
31264                     traversal head from the peer \
31265                     caixa-mesh gateway_routes early-return partition \
31266                     from the peer `feira app graph` internal-only-\
31267                     mesh partition",
31268                ),
31269            }
31270            assert_eq!(
31271                s.entrada().is_some(),
31272                s.entrada.is_some(),
31273                "AplicacaoSpec::entrada().is_some() must byte-equal \
31274                 self.entrada.is_some() — a presence-bit drift would \
31275                 silently split every downstream `Option<&Entrada>` \
31276                 consumer's partition on the internal-only-mesh arm",
31277            );
31278        }
31279    }
31280
31281    #[test]
31282    fn validate_reads_through_lifted_entrada_accessor() {
31283        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
31284        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
31285        // self.entrada() { … }`, followed by the per-axis fan-out
31286        // `validate_entrada_para(&e.para)` /
31287        // `EntradaMemberMissing` membership lookup /
31288        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
31289        // per-`e.paths` `validate_entrada_path` traversal) must key
31290        // off the lifted outer accessor, so any future rebrand on
31291        // the typed slot's outer-composite reader shape lands at
31292        // exactly one place. Pins the multi-axis coherence by
31293        // exercising each per-axis refusal end-to-end: (1) the
31294        // author-omitted `None` shape short-circuits past every
31295        // per-`:entrada` refusal (the internal-only mesh partition
31296        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
31297        // fires on a well-shaped but phantom `:para` under the outer
31298        // accessor's reference projection, and (3) the canonical
31299        // `three_member_spec` `:entrada` fixture passes `validate`
31300        // under the outer accessor's reference projection.
31301        //
31302        // Peer of the sibling M3
31303        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
31304        // (534dc21) multi-axis coherence pin on the per-`:politicas`
31305        // outer mesh-policy composite-reference axis and the sibling
31306        // M3
31307        // [`validate_placement_reads_through_lifted_placement_accessor`]
31308        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
31309        // outer distribution-composite composite-reference axis —
31310        // extends the multi-consumer coherence discipline onto the
31311        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
31312        // external-gateway composite-reference axis, the third and
31313        // final `&Composite`-return accessor on the outer
31314        // [`AplicacaoSpec`] type.
31315
31316        // (1) `None` :entrada — the internal-only-mesh partition
31317        // short-circuits past every per-`:entrada` refusal. The outer
31318        // accessor's reference projection reaches the fall-through
31319        // `Ok(())` on the `None` arm without any per-axis refusal
31320        // firing.
31321        let mut spec = three_member_spec();
31322        spec.entrada = None;
31323        assert!(
31324            spec.validate().is_ok(),
31325            "an author-omitted `:entrada` must pass `validate` — the \
31326             internal-only-mesh partition short-circuits past every \
31327             per-`:entrada` refusal under the outer accessor's \
31328             reference projection",
31329        );
31330        assert!(
31331            spec.entrada().is_none(),
31332            "the outer accessor's reference projection must name the \
31333             internal-only-mesh partition per the `None` fixture",
31334        );
31335
31336        // (2) `EntradaMemberMissing` refusal under the outer accessor's
31337        // reference projection: a well-shaped but phantom `:para` must
31338        // trip the membership-lookup refusal. The gate's second arm
31339        // reads `e.para` on the reference returned by the outer
31340        // accessor.
31341        let mut spec = three_member_spec();
31342        if let Some(e) = spec.entrada.as_mut() {
31343            e.para = "phantom".into();
31344        }
31345        assert_eq!(
31346            spec.validate().unwrap_err(),
31347            AplicacaoError::EntradaMemberMissing {
31348                para: "phantom".into(),
31349            },
31350        );
31351        match (spec.entrada(), spec.entrada.as_ref()) {
31352            (Some(a), Some(b)) => assert!(
31353                std::ptr::eq(a, b),
31354                "the `validate` per-`:entrada` gate's traversal head \
31355                 must be the same backing composite the accessor's \
31356                 reference projection borrows from",
31357            ),
31358            _ => panic!("fixture must carry Some(:entrada)"),
31359        }
31360
31361        // (3) Canonical `three_member_spec` `:entrada` fixture passes
31362        // `validate` — every per-axis arm reaches the fall-through
31363        // `Ok(())` without any per-axis refusal firing under the
31364        // outer accessor's reference projection.
31365        let spec = three_member_spec();
31366        assert!(
31367            spec.validate().is_ok(),
31368            "the canonical `:entrada` fixture must pass `validate` — \
31369             every per-axis arm short-circuits on valid input under \
31370             the outer accessor's reference projection",
31371        );
31372        assert!(
31373            spec.entrada().is_some(),
31374            "the outer accessor's reference projection must be the \
31375             canonical `:entrada` fixture's composite",
31376        );
31377    }
31378
31379    #[test]
31380    fn membro_names_matches_inline_membros_projection() {
31381        // Substrate-primitive ≡ inline-projection pin on
31382        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
31383        // must be byte-for-byte the set the pre-lift inline
31384        // `self.membros().iter().map(Membro::nome).collect()` builder
31385        // produced, on every membership shape the three
31386        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
31387        // :para`, `:entrada :para`) resolve against. Pins the
31388        // projection so a future rebrand of the node-identity axis
31389        // lands at the primitive rather than diverging between the
31390        // per-`:contratos` membership arms still inline at `validate`
31391        // and the lifted `validate_entrada` gate.
31392        for membros in [
31393            vec![],
31394            vec![membro("cart", "^0.1")],
31395            vec![
31396                membro("catalog", "^0.1"),
31397                membro("cart", "^0.1"),
31398                membro("payment", "^0.2"),
31399            ],
31400        ] {
31401            let mut spec = three_member_spec();
31402            spec.membros = membros;
31403            let inline: std::collections::HashSet<&str> =
31404                spec.membros().iter().map(Membro::nome).collect();
31405            assert_eq!(
31406                spec.membro_names(),
31407                inline,
31408                "the lifted membership oracle must discriminate the \
31409                 same node set as the pre-lift inline projection",
31410            );
31411        }
31412    }
31413
31414    #[test]
31415    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
31416        // Per-slot-gate ≡ validate equivalence pin on the lifted
31417        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
31418        // must discriminate the same set as [`AplicacaoSpec::validate`]
31419        // on every `:entrada`-covered input, so a future consumer that
31420        // re-validates the one slot (the M4 admission webhook
31421        // re-checking `:entrada` after a gateway-host patch) accepts
31422        // exactly what `feira build` accepts and surfaces the same
31423        // diagnostic on the same input. Covers each of the five gated
31424        // axes plus the two clean-pass shapes (`None` — the
31425        // internal-only-mesh partition — and the canonical fixture).
31426        //
31427        // Peer of the sibling per-slot equivalence pins
31428        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
31429        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
31430        // `:politicas` slot's compound entry gate, extended here onto
31431        // the `:entrada` slot's newly-named per-slot gate.
31432        /// One `:entrada` equivalence case: a label, the per-axis
31433        /// mutation applied to the canonical fixture's composite, and
31434        /// the diagnostic both the per-slot gate and `validate` must
31435        /// surface on it (`None` = clean pass).
31436        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
31437
31438        let cases: &[EntradaCase] = &[
31439            (
31440                ":para shape — empty",
31441                |e| e.para = String::new(),
31442                Some(AplicacaoError::EntradaParaEmpty),
31443            ),
31444            (
31445                ":para membership — well-shaped phantom",
31446                |e| e.para = "phantom".into(),
31447                Some(AplicacaoError::EntradaMemberMissing {
31448                    para: "phantom".into(),
31449                }),
31450            ),
31451            (
31452                ":host emptiness",
31453                |e| e.host = String::new(),
31454                Some(AplicacaoError::EmptyEntradaHost),
31455            ),
31456            (
31457                ":port structural floor",
31458                |e| e.port = 0,
31459                Some(AplicacaoError::EntradaPortZero),
31460            ),
31461            (
31462                ":paths per-entry emptiness",
31463                |e| e.paths = vec![String::new()],
31464                Some(AplicacaoError::EntradaPathEmpty),
31465            ),
31466            (
31467                ":paths leading-slash grammar",
31468                |e| e.paths = vec!["api/cart".into()],
31469                Some(AplicacaoError::EntradaPathNotAbsolute {
31470                    path: "api/cart".into(),
31471                }),
31472            ),
31473            (
31474                ":paths set-not-multiset",
31475                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
31476                Some(AplicacaoError::EntradaPathDuplicate {
31477                    path: "/api/cart".into(),
31478                }),
31479            ),
31480            ("clean pass — canonical fixture", |_| {}, None),
31481        ];
31482        for (label, mutate, expected) in cases {
31483            let mut spec = three_member_spec();
31484            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
31485            assert_eq!(
31486                spec.validate_entrada().err(),
31487                *expected,
31488                "per-slot gate disagreed with the expected diagnostic on {label}",
31489            );
31490            assert_eq!(
31491                spec.validate().err(),
31492                *expected,
31493                "`validate` disagreed with the per-slot gate on {label}",
31494            );
31495        }
31496
31497        // The `None` arm is the internal-only-mesh partition: a clean
31498        // pass through both the per-slot gate and `validate`, not a
31499        // refusal.
31500        let mut spec = three_member_spec();
31501        spec.entrada = None;
31502        assert_eq!(spec.validate_entrada().err(), None);
31503        assert_eq!(spec.validate().err(), None);
31504    }
31505
31506    #[test]
31507    fn validate_entrada_resolves_membership_through_own_oracle() {
31508        // Self-containment pin on the lifted per-slot gate:
31509        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
31510        // against the oracle *it* builds through
31511        // [`AplicacaoSpec::membro_names`], not one threaded down from
31512        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
31513        // longer contains the `:entrada :para` target must trip
31514        // `EntradaMemberMissing` when the per-slot gate is called
31515        // directly — the shape a future single-slot re-validator
31516        // (the M4 admission webhook) reaches the axis through, without
31517        // re-walking `:membros` / `:contratos` / the sync-cycle
31518        // detector first. Same self-contained posture
31519        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
31520        // the M4 per-edge policy resolver.
31521        let mut spec = three_member_spec();
31522        spec.membros.retain(|m| m.nome() != "cart");
31523        assert_eq!(
31524            spec.validate_entrada().unwrap_err(),
31525            AplicacaoError::EntradaMemberMissing {
31526                para: "cart".into(),
31527            },
31528            "the per-slot gate must resolve `:para` against the oracle \
31529             it builds itself, with no membership set threaded in",
31530        );
31531        assert!(
31532            !spec.membro_names().contains("cart"),
31533            "fixture must have dropped the `:entrada :para` target \
31534             from the graph's node set",
31535        );
31536    }
31537
31538    #[test]
31539    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
31540        // Per-slot-gate ≡ validate equivalence pin on the lifted
31541        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
31542        // gate must discriminate the same set as
31543        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
31544        // input, so a future consumer that re-validates the one slot
31545        // (the M4 admission webhook re-checking `:contratos` after a
31546        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
31547        // `:politicas` override MESH-COMPOSITION §III.2 #3
31548        // acknowledges — which resolves an effective per-edge
31549        // [`MeshPolicy`] and must re-check the edge's identity closure
31550        // before it can key a per-edge override off the endpoint
31551        // tuple) accepts exactly what `feira build` accepts and
31552        // surfaces the same diagnostic on the same input. Covers each
31553        // of the six gated axes (`:de`/`:para` per-arm shape,
31554        // per-arm graph-membership, structural self-loop, `:wit`
31555        // emptiness) plus the clean-pass canonical fixture; the
31556        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
31557        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
31558        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
31559        // `target:` carriers depend on library implementation
31560        // details are pinned separately below with a `matches!`
31561        // predicate on the arm identity plus the mirror equivalence
31562        // between the two entry points.
31563        //
31564        // Peer of the sibling per-slot equivalence pins
31565        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
31566        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
31567        // `:politicas` slot's compound entry gate, and
31568        // `validate_entrada_matches_gate_on_every_per_axis_shape`
31569        // (20cd523) on the `:entrada` slot's per-slot gate — extended
31570        // here onto the `:contratos` slot's newly-named per-slot gate,
31571        // closing the last unlifted per-slot gate on the M3 mesh-slot
31572        // family.
31573        /// One `:contratos` equivalence case: a label, the per-axis
31574        /// mutation applied to the canonical fixture's spec, and the
31575        /// diagnostic both the per-slot gate and `validate` must
31576        /// surface on it (`None` = clean pass).
31577        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
31578
31579        let cases: &[ContratoCase] = &[
31580            (
31581                ":de shape — empty",
31582                |s| s.contratos[0].de = String::new(),
31583                Some(AplicacaoError::ContratoCaixaEmpty {
31584                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
31585                }),
31586            ),
31587            (
31588                ":para shape — empty",
31589                |s| s.contratos[0].para = String::new(),
31590                Some(AplicacaoError::ContratoCaixaEmpty {
31591                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
31592                }),
31593            ),
31594            (
31595                ":de membership — well-shaped phantom",
31596                |s| s.contratos[0].de = "phantom".into(),
31597                Some(AplicacaoError::ContratoMemberMissing {
31598                    caixa: "phantom".into(),
31599                }),
31600            ),
31601            (
31602                ":para membership — well-shaped phantom",
31603                |s| s.contratos[0].para = "phantom".into(),
31604                Some(AplicacaoError::ContratoMemberMissing {
31605                    caixa: "phantom".into(),
31606                }),
31607            ),
31608            (
31609                "structural self-loop",
31610                |s| s.contratos[0].para = "cart".into(),
31611                Some(AplicacaoError::ContratoSelfLoop {
31612                    caixa: "cart".into(),
31613                    wit: "wasi:http/proxy".into(),
31614                }),
31615            ),
31616            (
31617                ":wit emptiness",
31618                |s| s.contratos[0].wit = String::new(),
31619                Some(AplicacaoError::EmptyWit {
31620                    de: "cart".into(),
31621                    para: "catalog".into(),
31622                }),
31623            ),
31624            ("clean pass — canonical fixture", |_| {}, None),
31625        ];
31626        for (label, mutate, expected) in cases {
31627            let mut spec = three_member_spec();
31628            mutate(&mut spec);
31629            assert_eq!(
31630                spec.validate_contratos().err(),
31631                *expected,
31632                "per-slot gate disagreed with the expected diagnostic on {label}",
31633            );
31634            assert_eq!(
31635                spec.validate().err(),
31636                *expected,
31637                "`validate` disagreed with the per-slot gate on {label}",
31638            );
31639        }
31640    }
31641
31642    #[test]
31643    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
31644        // Companion pin to
31645        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
31646        // the per-slot gate ≡ `validate` equivalence on the three
31647        // `:contratos` refusal arms whose diagnostic carries a
31648        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
31649        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
31650        // `is_dns_1123_label` / `WitContract::target` shape helpers,
31651        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
31652        // library-formatted `target:` scalar). Value equality between
31653        // the per-slot gate and `validate` outputs pins the full
31654        // `Option<AplicacaoError>` (including reason-strings), and the
31655        // per-arm `matches!` predicate pins the arm-discriminator
31656        // identity on the specific `Contrato*` variant. Split from
31657        // the primary equivalence pin so each pin body stays under
31658        // [`clippy::too_many_lines`], the same shape the peer
31659        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
31660        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
31661        // carries on the `:politicas` slot's compound entry gate.
31662        type ContratoReasonCase = (
31663            &'static str,
31664            fn(&mut AplicacaoSpec),
31665            fn(&AplicacaoError) -> bool,
31666        );
31667        let cases: &[ContratoReasonCase] = &[
31668            (
31669                ":de shape — DNS-1123 invalid",
31670                |s| s.contratos[0].de = "Cart".into(),
31671                |err| {
31672                    matches!(
31673                        err,
31674                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
31675                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
31676                    )
31677                },
31678            ),
31679            (
31680                ":wit target-shape mismatch — payload on capability arm",
31681                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
31682                |err| {
31683                    matches!(
31684                        err,
31685                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
31686                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
31687                    )
31688                },
31689            ),
31690            (
31691                "whole-edge dedup — six-axis identity collision",
31692                |s| {
31693                    let dup = s.contratos[0].clone();
31694                    s.contratos.push(dup);
31695                },
31696                |err| {
31697                    matches!(
31698                        err,
31699                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
31700                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
31701                    )
31702                },
31703            ),
31704        ];
31705        for (label, mutate, arm_matches) in cases {
31706            let mut spec = three_member_spec();
31707            mutate(&mut spec);
31708            let per_slot = spec.validate_contratos().err();
31709            let gate = spec.validate().err();
31710            assert_eq!(
31711                per_slot, gate,
31712                "per-slot gate and `validate` must return byte-equal \
31713                 `Option<AplicacaoError>` on {label} (including \
31714                 library-owned reason strings)",
31715            );
31716            let err = per_slot
31717                .as_ref()
31718                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
31719            assert!(
31720                arm_matches(err),
31721                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
31722            );
31723        }
31724    }
31725
31726    #[test]
31727    fn validate_contratos_resolves_membership_through_own_oracle() {
31728        // Self-containment pin on the lifted per-slot gate:
31729        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
31730        // `:de` / `:para` against the oracle *it* builds through
31731        // [`AplicacaoSpec::membro_names`], not one threaded down from
31732        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
31733        // longer contains a `:contratos` edge's endpoint must trip
31734        // `ContratoMemberMissing` when the per-slot gate is called
31735        // directly — the shape a future single-slot re-validator
31736        // (the M4 admission webhook re-checking `:contratos` after a
31737        // per-`(:de, :para)` edge patch, the M4 per-edge policy
31738        // resolver on the `:politicas` override axis) reaches the
31739        // axis through, without re-walking `:membros` / `:entrada` /
31740        // `:placement` / `:politicas` first. Same self-contained
31741        // posture the peer per-slot gates
31742        // [`AplicacaoSpec::detect_sync_cycles`] and
31743        // [`AplicacaoSpec::validate_entrada`] already carry for the
31744        // same M4 consumers.
31745        let mut spec = three_member_spec();
31746        spec.membros.retain(|m| m.nome() != "catalog");
31747        assert_eq!(
31748            spec.validate_contratos().unwrap_err(),
31749            AplicacaoError::ContratoMemberMissing {
31750                caixa: "catalog".into(),
31751            },
31752            "the per-slot gate must resolve `:de` / `:para` against \
31753             the oracle it builds itself, with no membership set \
31754             threaded in",
31755        );
31756        assert!(
31757            !spec.membro_names().contains("catalog"),
31758            "fixture must have dropped the `:contratos` edge's \
31759             `:para` target from the graph's node set",
31760        );
31761    }
31762
31763    #[test]
31764    fn validate_contratos_folds_cycle_axis_matches_gate() {
31765        // Fold-into-per-slot-gate equivalence pin on the
31766        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
31767        // surfaces byte-equal through both
31768        // [`AplicacaoSpec::validate_contratos`] and
31769        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
31770        // a synchronous-edge cycle in `:contratos`. Pins the fold that
31771        // moved the cross-edge cycle axis onto the per-slot gate — a
31772        // future silent regression that de-folded the axis back to the
31773        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
31774        // a peer per-slot gate lift that skipped the cross-axis half of
31775        // the [`MeshPolicy::validate`]-analogous discipline) would
31776        // surface here as `Some(ContratoCycle)` from `validate` and
31777        // `None` from `validate_contratos`.
31778        //
31779        // Cycle fixture is the same shape as the peer
31780        // [`rejects_three_node_synchronous_cycle`] test carries: a
31781        // clean 3-cycle over the HTTP subgraph (catalog → cart →
31782        // payment → catalog), so the per-entry cascade (shape +
31783        // membership + self-loop + `:wit` emptiness + WIT-target +
31784        // whole-edge dedup) passes cleanly and the sole surviving
31785        // refusal shape is the cross-edge cycle axis. The `cycle`
31786        // vector is normalized to a sorted body set for the equality
31787        // compare (the traversal path's starting node depends on
31788        // BTreeMap iteration order, which is deterministic but is not
31789        // the load-bearing property this pin covers).
31790        //
31791        // Peer of the sibling per-slot ≡ `validate` equivalence pins
31792        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
31793        // (per-entry axes) and
31794        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
31795        // (parser-owned reason arms) already carry on the six
31796        // per-entry axes — this extends the discipline onto the
31797        // cross-edge cycle axis newly folded into the per-slot gate,
31798        // matching the peer per-slot compound gate
31799        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
31800        // both per-axis and cross-axis surfaces on `:politicas`.
31801        let mut spec = three_member_spec();
31802        spec.contratos = vec![
31803            contract_http("catalog", "cart", "/x"),
31804            contract_http("cart", "payment", "/y"),
31805            contract_http("payment", "catalog", "/z"),
31806        ];
31807        let per_slot_err = spec.validate_contratos().unwrap_err();
31808        let gate_err = spec.validate().unwrap_err();
31809        assert_eq!(
31810            per_slot_err, gate_err,
31811            "the per-slot gate and `validate` must return byte-equal \
31812             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
31813             — the fold pins the cross-edge axis onto the per-slot \
31814             gate the same way the peer `validate_politicas` fold \
31815             pinned the `:politicas` cross-axis surface",
31816        );
31817        match per_slot_err {
31818            AplicacaoError::ContratoCycle { ref cycle } => {
31819                assert_eq!(
31820                    cycle.first(),
31821                    cycle.last(),
31822                    "cycle traversal must close on the back-edge \
31823                     target — the diagnostic shape the peer \
31824                     `rejects_three_node_synchronous_cycle` pins",
31825                );
31826                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
31827                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
31828                assert!(body.contains("cart"));
31829                assert!(body.contains("catalog"));
31830                assert!(body.contains("payment"));
31831            }
31832            other => panic!("expected ContratoCycle, got {other:?}"),
31833        }
31834    }
31835
31836    #[test]
31837    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
31838        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
31839        // carrying *both* a per-entry defect (a self-loop, the
31840        // structural-self-edge arm on the per-entry cascade — chosen
31841        // because it never masks or is masked by the cycle diagnostic
31842        // on the peer arms) *and* a would-be synchronous-edge cycle in
31843        // the remaining edges must surface the per-entry diagnostic
31844        // first through both [`AplicacaoSpec::validate_contratos`] and
31845        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
31846        // per-entry-before-cross-edge dispatch ordering, byte-equal to
31847        // the pre-fold `validate`-side sequence
31848        // (`validate_contratos()? → detect_sync_cycles()?`) the
31849        // dispatch encoded verbatim. A silent regression that reversed
31850        // the ordering inside the fold would surface here as a cycle
31851        // diagnostic on a fixture carrying an earlier per-entry defect
31852        // — masking the narrower "this edge is degenerate" arm behind
31853        // the coarser "this graph deadlocks" arm.
31854        //
31855        // Peer of the diagnostic-ordering property the pre-fold
31856        // dispatch encoded at the [`AplicacaoSpec::validate`]
31857        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
31858        // now enforced inside the per-slot gate's own body, so a future
31859        // consumer that reaches only the per-slot gate (the M4
31860        // admission webhook re-checking `:contratos` after a per-edge
31861        // patch) inherits the ordering property by construction.
31862        let mut spec = three_member_spec();
31863        // The three-member fixture already has cart → catalog and
31864        // cart → payment; adding catalog → cart closes a 2-cycle on
31865        // the HTTP subgraph.
31866        spec.contratos
31867            .push(contract_http("catalog", "cart", "/refresh"));
31868        // Add a self-loop on `payment` — the per-entry structural-
31869        // self-edge arm — which must surface first.
31870        spec.contratos
31871            .push(contract_http("payment", "payment", "/loop"));
31872        let per_slot_err = spec.validate_contratos().unwrap_err();
31873        let gate_err = spec.validate().unwrap_err();
31874        assert_eq!(
31875            per_slot_err, gate_err,
31876            "per-slot gate and `validate` must agree on the ordering \
31877             fixture's surfaced diagnostic — a divergence here means \
31878             the fold reshaped one dispatch's ordering without the \
31879             other",
31880        );
31881        assert!(
31882            matches!(
31883                per_slot_err,
31884                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
31885                    if caixa == "payment"
31886            ),
31887            "the per-entry structural-self-edge arm must fire before \
31888             the cross-edge cycle arm — pinning the fold's per-entry-\
31889             before-cross-edge dispatch ordering byte-equal to the \
31890             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
31891             sequence; got {per_slot_err:?}",
31892        );
31893    }
31894
31895    #[test]
31896    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
31897        // Self-containment pin on the folded cross-edge cycle axis:
31898        // [`AplicacaoSpec::validate_contratos`] surfaces
31899        // [`AplicacaoError::ContratoCycle`] directly against `&self`
31900        // without depending on the peer per-slot gates
31901        // ([`AplicacaoSpec::validate_membros`],
31902        // [`AplicacaoSpec::validate_entrada`],
31903        // [`AplicacaoSpec::validate_placement`],
31904        // [`AplicacaoSpec::validate_politicas`]) running first — the
31905        // shape a future single-slot re-validator (the M4 admission
31906        // webhook re-checking `:contratos` after a per-`(:de, :para)`
31907        // edge patch, the per-edge policy resolver MESH-COMPOSITION
31908        // §III.2 #3 acknowledges) reaches *both* structural axes on
31909        // the slot through one call. A spec with a per-`:politicas`
31910        // refusal shape (zero `:timeout`, the first per-axis arm the
31911        // peer [`MeshPolicy::validate`] gate covers) AND a
31912        // synchronous-edge cycle in `:contratos` must:
31913        //
31914        //   - surface [`AplicacaoError::ContratoCycle`] through the
31915        //     per-slot gate `validate_contratos` directly (proves the
31916        //     cycle axis reaches the per-slot altitude without the
31917        //     peer `:politicas` gate running first);
31918        //   - surface [`AplicacaoError::ContratoCycle`] through
31919        //     `validate` (which reaches `validate_contratos` before
31920        //     `validate_politicas` per the fixed dispatch order), so
31921        //     the fold's cross-slot ordering (`:membros` →
31922        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
31923        //     is byte-equal to the pre-fold dispatch's ordering.
31924        //
31925        // Same self-contained-on-`&self` posture the peer per-slot
31926        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
31927        // [`AplicacaoSpec::validate_contratos`] per-entry axis
31928        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
31929        // (f03a154) already carry — extended here onto the newly-
31930        // folded cross-edge cycle axis. Peer of the sibling per-slot
31931        // self-containment pins
31932        // `validate_entrada_resolves_membership_through_own_oracle`
31933        // and `validate_contratos_resolves_membership_through_own_oracle`
31934        // on the per-entry membership axis — extends the discipline
31935        // onto the cross-edge cycle axis of the same per-slot gate.
31936        let mut spec = three_member_spec();
31937        // Poison `:politicas` — zero-`:timeout` trips the first per-
31938        // axis arm the [`MeshPolicy::validate`] gate covers, so any
31939        // dispatch that reached `:politicas` would surface a
31940        // `:politicas` diagnostic instead of `ContratoCycle`.
31941        spec.politicas.timeout = Some(Duration::from_secs(0));
31942        // Close a synchronous-edge cycle on the HTTP subgraph.
31943        spec.contratos
31944            .push(contract_http("catalog", "cart", "/refresh"));
31945        let per_slot_err = spec.validate_contratos().unwrap_err();
31946        assert!(
31947            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
31948            "the per-slot gate must surface `ContratoCycle` directly \
31949             against `&self` — a peer per-slot gate's regression \
31950             would surface a non-`ContratoCycle` diagnostic here; \
31951             got {per_slot_err:?}",
31952        );
31953        let gate_err = spec.validate().unwrap_err();
31954        assert!(
31955            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
31956            "`validate`'s five-slot dispatch must reach the fold's \
31957             cross-edge cycle axis on `:contratos` before the peer \
31958             `:politicas` gate — a dispatch-order regression would \
31959             surface a `:politicas` diagnostic here; got {gate_err:?}",
31960        );
31961        // Sanity: the poisoned `:politicas` alone would trip
31962        // [`MeshPolicy::validate`] under the peer per-slot gate, so
31963        // the cycle-first surfacing above is a real ordering property,
31964        // not a case where the `:politicas` axis silently accepts the
31965        // fixture.
31966        let mut politicas_only = three_member_spec();
31967        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
31968        assert!(
31969            politicas_only.validate_politicas().is_err(),
31970            "the poisoned `:politicas` fixture must trip the peer \
31971             per-slot gate on its own — otherwise the self-contained \
31972             cycle-first surfacing above would not be an ordering \
31973             property",
31974        );
31975    }
31976
31977    #[test]
31978    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
31979        // Fail-before-pass-after equivalence pin on the lifted
31980        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
31981        // both arms (`:de` phantom and `:para` phantom) must fire the
31982        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
31983        // `caixa` carrier byte-equal to the offending accessor's
31984        // projection, and `:de` must fire before `:para` when both
31985        // arms would trip on the same call — preserving the canonical
31986        // edge-direction order the peer per-arm shape gate
31987        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
31988        // diagnostic, and every peer per-arm ordering in
31989        // [`AplicacaoSpec::validate_contratos`] already carry.
31990        //
31991        // Two-endpoint oracle covers exactly enough graph nodes to
31992        // exercise each arm in isolation: the `:de` arm fires when
31993        // the source is off-oracle and the destination is on-oracle,
31994        // the `:para` arm fires when the source is on-oracle and the
31995        // destination is off-oracle, and the `:de`-before-`:para`
31996        // ordering falls out from a probe where *both* endpoints are
31997        // off-oracle — the diagnostic's `caixa` field must byte-equal
31998        // the source, not the destination, pinning the primitive's
31999        // arm ordering as `:de` first.
32000        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
32001        names.insert("cart");
32002        names.insert("catalog");
32003
32004        // `:de` phantom, `:para` on-oracle
32005        let de_phantom = contract_http("phantom-de", "catalog", "/x");
32006        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
32007        assert_eq!(
32008            err,
32009            AplicacaoError::ContratoMemberMissing {
32010                caixa: de_phantom.source().to_string(),
32011            },
32012            "the `:de` phantom arm must fire ContratoMemberMissing \
32013             with `caixa` byte-equal to `WitContract::source` — a \
32014             bypass here (a raw `.de.clone()` regression, a divergent \
32015             accessor on a per-CR alias table) would silently split \
32016             the primitive's diagnostic from the substrate-primitive \
32017             scalar accessor every downstream consumer routes through",
32018        );
32019
32020        // `:de` on-oracle, `:para` phantom
32021        let para_phantom = contract_http("cart", "phantom-para", "/x");
32022        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
32023        assert_eq!(
32024            err,
32025            AplicacaoError::ContratoMemberMissing {
32026                caixa: para_phantom.destination().to_string(),
32027            },
32028            "the `:para` phantom arm must fire ContratoMemberMissing \
32029             with `caixa` byte-equal to `WitContract::destination` — \
32030             symmetric callee-side pin to the `:de` arm above",
32031        );
32032
32033        // Both endpoints off-oracle: the `:de` arm must fire first,
32034        // pinning the primitive's canonical edge-direction order.
32035        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
32036        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
32037        assert_eq!(
32038            err,
32039            AplicacaoError::ContratoMemberMissing {
32040                caixa: both_phantom.source().to_string(),
32041            },
32042            "when both endpoints are off-oracle, the `:de` arm must \
32043             fire before the `:para` arm — preserving byte-equal \
32044             ordering with the pre-lift inline cascade in \
32045             `validate_contratos` and with every peer per-arm \
32046             ordering the sibling per-edge substrate primitives \
32047             already carry",
32048        );
32049
32050        // Both endpoints on-oracle: clean pass.
32051        let clean = contract_http("cart", "catalog", "/x");
32052        clean.require_endpoints_in(&names).unwrap();
32053    }
32054
32055    #[test]
32056    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
32057        // Convergence pin: the whole-spec end-to-end route through
32058        // [`AplicacaoSpec::validate_contratos`] must reach the
32059        // per-edge substrate primitive
32060        // [`WitContract::require_endpoints_in`] on every membership
32061        // arm — the diagnostic fired at the per-slot altitude must
32062        // byte-equal the diagnostic the primitive fires when called
32063        // directly on the same edge and the same oracle. Pins the
32064        // primitive as the sole load-bearing gate on the membership
32065        // axis, so any future silent detour that re-inlined the twin
32066        // `if !names.contains(...)` cascade back into the per-slot
32067        // gate (a rebase-artifact regression, an M4 admission-webhook
32068        // consumer that bypassed the primitive) would surface here as
32069        // a byte-equal miss between the two dispatches.
32070        //
32071        // Same equivalence-pin discipline the peer
32072        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
32073        // pin already carries on the per-slot gate ≡ `validate` axis,
32074        // extended here onto the per-slot gate ≡ per-edge primitive
32075        // axis at one altitude deeper.
32076        for phantom_edge in [
32077            contract_http("phantom-de", "catalog", "/x"),
32078            contract_http("cart", "phantom-para", "/x"),
32079        ] {
32080            let mut spec = three_member_spec();
32081            spec.contratos.push(phantom_edge.clone());
32082            let per_slot_err = spec.validate_contratos().unwrap_err();
32083            let primitive_err = phantom_edge
32084                .require_endpoints_in(&spec.membro_names())
32085                .unwrap_err();
32086            assert_eq!(
32087                per_slot_err, primitive_err,
32088                "the per-slot gate must reach the per-edge substrate \
32089                 primitive on every membership arm — a bypass here \
32090                 would silently split the two dispatches on the \
32091                 same edge + same oracle input",
32092            );
32093            // And the diagnostic's `caixa` carrier must byte-equal
32094            // the offending accessor's projection at both altitudes,
32095            // pinning the accessor routing across the whole-spec
32096            // path.
32097            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
32098                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
32099            };
32100            let expected = if spec.membro_names().contains(phantom_edge.source()) {
32101                phantom_edge.destination()
32102            } else {
32103                phantom_edge.source()
32104            };
32105            assert_eq!(
32106                caixa, expected,
32107                "the whole-spec ContratoMemberMissing.caixa carrier \
32108                 must byte-equal the offending edge's accessor \
32109                 projection — a bypass here would silently split \
32110                 the wrap envelope's `caixa` field from the \
32111                 substrate-primitive scalar accessor every \
32112                 downstream consumer routes through",
32113            );
32114        }
32115    }
32116
32117    #[test]
32118    fn port_for_destination_reads_through_lifted_entrada_accessor() {
32119        // Peer coherence pin: the
32120        // [`AplicacaoSpec::port_for_destination`] per-destination
32121        // L4-port fallback resolver's composite-projection seed
32122        // (`self.entrada().filter(…).map_or(…)`) must key off the
32123        // lifted outer accessor. Pins the coherence by exercising
32124        // the resolver end-to-end: (1) the `None` `:entrada` shape
32125        // falls through to `DEFAULT_SERVICO_PORT` under the outer
32126        // accessor's reference projection, (2) a non-matching
32127        // destination falls through to `DEFAULT_SERVICO_PORT` under
32128        // the outer accessor's reference projection, and (3) the
32129        // matching destination resolves to the `:entrada :port`
32130        // value under the outer accessor's reference projection.
32131        //
32132        // Peer of the sibling
32133        // [`validate_reads_through_lifted_entrada_accessor`] multi-
32134        // consumer coherence pin on the same per-`:entrada` outer-
32135        // composite axis — extends the multi-consumer coherence
32136        // discipline onto the second per-`:entrada` production
32137        // consumer, the L4-port fallback resolver.
32138
32139        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
32140        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
32141        // arm under the outer accessor's reference projection.
32142        let mut spec = three_member_spec();
32143        spec.entrada = None;
32144        assert_eq!(
32145            spec.port_for_destination("cart"),
32146            DEFAULT_SERVICO_PORT,
32147            "the port-fallback resolver must fall through to \
32148             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
32149             under the outer accessor's reference projection",
32150        );
32151
32152        // (2) Non-matching destination — the resolver's `filter(…)`
32153        // arm rejects a mismatched destination and falls through
32154        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
32155        // reference projection.
32156        let mut spec = three_member_spec();
32157        if let Some(e) = spec.entrada.as_mut() {
32158            e.para = "cart".into();
32159            e.port = 9443;
32160        }
32161        assert_eq!(
32162            spec.port_for_destination("catalog"),
32163            DEFAULT_SERVICO_PORT,
32164            "the port-fallback resolver must fall through to \
32165             DEFAULT_SERVICO_PORT on a non-matching destination \
32166             under the outer accessor's reference projection",
32167        );
32168
32169        // (3) Matching destination — the resolver's `map_or(…)` arm
32170        // returns the `:entrada :port` value under the outer
32171        // accessor's reference projection.
32172        let mut spec = three_member_spec();
32173        if let Some(e) = spec.entrada.as_mut() {
32174            e.para = "cart".into();
32175            e.port = 9443;
32176        }
32177        assert_eq!(
32178            spec.port_for_destination("cart"),
32179            9443,
32180            "the port-fallback resolver must return the \
32181             `:entrada :port` value on a matching destination \
32182             under the outer accessor's reference projection",
32183        );
32184    }
32185
32186    #[test]
32187    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
32188        // The canonical per-`:politicas` `:mtls-required` mTLS-
32189        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
32190        // must return the `:politicas :mtls-required` typed bool
32191        // verbatim as an `Option<bool>`, byte-equal to the raw field
32192        // access across every value in the three-way accept-set —
32193        // `None` (cluster default applies), `Some(true)` (mTLS
32194        // handshake enforced — the sandboxing-by-default arm the
32195        // MeshPolicy's docstring names), `Some(false)` (handshake
32196        // skipped — the explicit debug-edge opt-out).
32197        //
32198        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
32199        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
32200        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
32201        // shape — first `Option<Copy-T>`-return accessor on the M3
32202        // mesh-slot family. Pins against a future silent detour that
32203        // re-derived the toggle from a peer axis (an accidental
32204        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
32205        // whenever a breaker is set), a `None` → `Some(false)` cluster-
32206        // default projection (the canonical `Option<bool>` → `bool`
32207        // collapse footgun the surrounding `is_empty()` predicate
32208        // guards on the peer emptiness axis), or a `Some(true)` /
32209        // `Some(false)` variant swap that landed on one consumer
32210        // without the other.
32211        for required in [None, Some(true), Some(false)] {
32212            let p = MeshPolicy {
32213                mtls_required: required,
32214                ..MeshPolicy::default()
32215            };
32216            assert_eq!(
32217                p.mtls_required(),
32218                required,
32219                "MeshPolicy::mtls_required must return :politicas \
32220                 :mtls-required verbatim (got {:?}, expected {required:?})",
32221                p.mtls_required(),
32222            );
32223            assert_eq!(
32224                p.mtls_required(),
32225                p.mtls_required,
32226                "MeshPolicy::mtls_required must byte-equal the raw \
32227                 .mtls_required field access across every value in the \
32228                 three-way accept-set",
32229            );
32230        }
32231    }
32232
32233    #[test]
32234    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
32235        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
32236        // arm must key off [`MeshPolicy::mtls_required`], not the raw
32237        // `.mtls_required` field access. Structurally: toggling ONLY
32238        // the `mtls_required` slot on an otherwise-default MeshPolicy
32239        // must flip `is_empty()` from `true` (all-`None`) to `false`
32240        // (one axis carries a value); the flip must be observed for
32241        // both `Some(true)` and `Some(false)` since the emptiness
32242        // semantic reads "any axis carries a value" — not "any axis
32243        // carries a truthy value" — the same non-collapsing shape the
32244        // sibling M2 [`crate::LimitsSpec::is_empty`] /
32245        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
32246        // peer `Option<T>`-typed slot surfaces.
32247        //
32248        // Pins against a future silent detour that re-derived the
32249        // emptiness predicate off a peer axis (an accidental
32250        // `.rate_limit.is_none()`-only chain that dropped the
32251        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
32252        // collapse to a truthy-only check (which would silently
32253        // classify `Some(false)` as empty), or an accessor-side
32254        // detour that no longer names the substrate-primitive typed
32255        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
32256        // == false` fallback in the accessor that would silently
32257        // classify both `None` and `Some(false)` as the same value).
32258        //
32259        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
32260        // (7cd2a28) accessor-composition pin on the sibling optional-
32261        // scalar axis — same "the emptiness / shape-gate predicate
32262        // must route through the substrate-primitive typed dispatch"
32263        // discipline extended onto the peer per-`:politicas` emptiness
32264        // predicate.
32265        let empty = MeshPolicy::default();
32266        assert!(
32267            empty.is_empty(),
32268            "MeshPolicy::default() must be is_empty() — every axis \
32269             defaults to None",
32270        );
32271        for required in [Some(true), Some(false)] {
32272            let p = MeshPolicy {
32273                mtls_required: required,
32274                ..MeshPolicy::default()
32275            };
32276            assert!(
32277                !p.is_empty(),
32278                "MeshPolicy::is_empty must return false when \
32279                 :mtls-required is {required:?} — the emptiness \
32280                 predicate reads \"any axis carries a value\", not \
32281                 \"any axis carries a truthy value\"",
32282            );
32283            assert_eq!(
32284                p.mtls_required().is_none(),
32285                p.is_empty(),
32286                "when :mtls-required is the only set axis, \
32287                 is_empty() must equal mtls_required().is_none() — \
32288                 the accessor and the emptiness predicate must \
32289                 route through the same substrate-primitive typed \
32290                 dispatch on the :mtls-required arm",
32291            );
32292        }
32293    }
32294
32295    #[test]
32296    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
32297        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
32298        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
32299        // accessor must return by value, not by reference. Peer of the
32300        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
32301        // borrow-invariant pin on the sibling `Option<String>` slot,
32302        // but extended onto the peer `Option<bool>` copy-invariant
32303        // shape — the accessor's returned `Option<bool>` must outlive
32304        // `&self` (multiple calls must return equal values from a
32305        // dropped-`&self` copy, since the returned Option carries no
32306        // borrow), and calling the accessor twice on the same
32307        // MeshPolicy must yield the same `Option<bool>` verbatim
32308        // (idempotent, no side effects on `&self`).
32309        //
32310        // Pins against a future silent detour that returned
32311        // `Option<&bool>` (which would type-check but silently break
32312        // every downstream caller — [`single_field_overlay`]'s first
32313        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
32314        // detached copy at the call site), an accidental
32315        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
32316        // would also type-check but return `Option<&bool>`), or a
32317        // one-arm-only accessor that reads `Some(*b)` in the Some arm
32318        // but reads a fresh Default::default() in the None arm.
32319        for required in [None, Some(true), Some(false)] {
32320            let p = MeshPolicy {
32321                mtls_required: required,
32322                ..MeshPolicy::default()
32323            };
32324            let first = p.mtls_required();
32325            let second = p.mtls_required();
32326            assert_eq!(
32327                first, second,
32328                "MeshPolicy::mtls_required must be idempotent — two \
32329                 successive calls on the same &self must return the \
32330                 same Option<bool>",
32331            );
32332            assert_eq!(
32333                first, required,
32334                "MeshPolicy::mtls_required must return :politicas \
32335                 :mtls-required verbatim by copy — got {first:?}, \
32336                 expected {required:?}",
32337            );
32338        }
32339    }
32340
32341    #[test]
32342    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
32343        // The canonical per-`:politicas` `:retries` transient-failure-
32344        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
32345        // the `:politicas :retries` typed `u32` verbatim as an
32346        // `Option<u32>`, byte-equal to the raw field access across every
32347        // representative value in the accept-set — `None` (cluster
32348        // default applies — typically "no retries beyond a single
32349        // dispatch attempt" the caixa-mesh `retry_overlay` builder
32350        // documents), `Some(1)` (the lower boundary of the
32351        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
32352        // `AplicacaoSpec::validate_politicas` gate carves out on the
32353        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
32354        // (the upper boundary the same gate carves out on the sibling
32355        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
32356        // past-the-guard sentinel that pins the accessor doesn't perform
32357        // a silent bounds-collapse at the return path).
32358        //
32359        // Sibling of the peer per-`:politicas`
32360        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
32361        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
32362        // peer per-`:politicas` `Option<u32>` shape — second
32363        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
32364        // Pins against a future silent detour that re-derived the retry
32365        // cap from a peer axis (an accidental `.circuit_breaker
32366        // .as_ref().map(|b| b.max_failures)` collapse that read the
32367        // breaker's max-failure count as a retry budget), a
32368        // `None → Some(0)` cluster-default projection (which would
32369        // silently re-introduce the `PolicyRetriesZero` refusal case at
32370        // the emit boundary), or a bounds-collapsing accessor that
32371        // clamped the return through `POLICY_RETRIES_MAX` (the
32372        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
32373        // must ship the raw slot verbatim so a validate-time gate
32374        // regression surfaces at the emit boundary rather than being
32375        // silently absorbed).
32376        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
32377            let p = MeshPolicy {
32378                retries,
32379                ..MeshPolicy::default()
32380            };
32381            assert_eq!(
32382                p.retries(),
32383                retries,
32384                "MeshPolicy::retries must return :politicas :retries \
32385                 verbatim (got {:?}, expected {retries:?})",
32386                p.retries(),
32387            );
32388            assert_eq!(
32389                p.retries(),
32390                p.retries,
32391                "MeshPolicy::retries must byte-equal the raw .retries \
32392                 field access across every value in the accept-set",
32393            );
32394        }
32395    }
32396
32397    #[test]
32398    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
32399        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
32400        // must key off [`MeshPolicy::retries`], not the raw `.retries`
32401        // field access. Structurally: toggling ONLY the `retries` slot
32402        // on an otherwise-default MeshPolicy must flip `is_empty()`
32403        // from `true` (all-`None`) to `false` (one axis carries a
32404        // value); the flip must be observed for every value in the
32405        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
32406        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
32407        // the emptiness semantic reads "any axis carries a value" —
32408        // not "any axis carries a value the validate gate accepts" —
32409        // the same non-collapsing shape the peer M2
32410        // [`crate::LimitsSpec::is_empty`] /
32411        // [`crate::BehaviorSpec::is_empty`] predicates carry.
32412        //
32413        // Pins against a future silent detour that re-derived the
32414        // emptiness predicate off a peer axis (an accidental
32415        // `.rate_limit.is_none()`-only chain that dropped the
32416        // `retries` arm entirely), a `retries == Some(_)` collapse
32417        // that key-off a validate-gate-clamped bounds check (which
32418        // would silently classify a past-the-guard `Some(u32::MAX)`
32419        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
32420        // check), or an accessor-side detour that no longer names the
32421        // substrate-primitive typed dispatch.
32422        //
32423        // Sibling of the peer per-`:politicas`
32424        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
32425        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
32426        // same "the emptiness predicate must route through the
32427        // substrate-primitive typed dispatch" discipline extended onto
32428        // the peer per-`:politicas` `Option<u32>` axis.
32429        let empty = MeshPolicy::default();
32430        assert!(
32431            empty.is_empty(),
32432            "MeshPolicy::default() must be is_empty() — every axis \
32433             defaults to None",
32434        );
32435        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
32436            let p = MeshPolicy {
32437                retries,
32438                ..MeshPolicy::default()
32439            };
32440            assert!(
32441                !p.is_empty(),
32442                "MeshPolicy::is_empty must return false when \
32443                 :retries is {retries:?} — the emptiness \
32444                 predicate reads \"any axis carries a value\", not \
32445                 \"any axis carries a value the validate gate \
32446                 accepts\"",
32447            );
32448            assert_eq!(
32449                p.retries().is_none(),
32450                p.is_empty(),
32451                "when :retries is the only set axis, is_empty() \
32452                 must equal retries().is_none() — the accessor and \
32453                 the emptiness predicate must route through the same \
32454                 substrate-primitive typed dispatch on the :retries \
32455                 arm",
32456            );
32457        }
32458    }
32459
32460    #[test]
32461    fn mesh_policy_retries_projects_option_u32_by_copy() {
32462        // The by-copy pin: [`MeshPolicy::retries`] returns
32463        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
32464        // accessor must return by value, not by reference. Sibling of
32465        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
32466        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
32467        // extended onto the sibling `Option<u32>` copy-invariant
32468        // shape — the accessor's returned `Option<u32>` must outlive
32469        // `&self` (multiple calls must return equal values from a
32470        // dropped-`&self` copy, since the returned Option carries no
32471        // borrow), and calling the accessor twice on the same
32472        // MeshPolicy must yield the same `Option<u32>` verbatim
32473        // (idempotent, no side effects on `&self`).
32474        //
32475        // Pins against a future silent detour that returned
32476        // `Option<&u32>` (which would type-check but silently break
32477        // every downstream caller — [`crate::render::single_field_overlay`]'s
32478        // first parameter is `Option<T: Clone>`, and `&u32` would
32479        // fold to a detached copy at the call site), an accidental
32480        // `Option::as_ref()` projection (`self.retries.as_ref()` would
32481        // also type-check but return `Option<&u32>`), or a one-arm-
32482        // only accessor that reads `Some(*n)` in the Some arm but
32483        // reads a fresh `Default::default()` (`0_u32`) in the None
32484        // arm.
32485        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
32486            let p = MeshPolicy {
32487                retries,
32488                ..MeshPolicy::default()
32489            };
32490            let first = p.retries();
32491            let second = p.retries();
32492            assert_eq!(
32493                first, second,
32494                "MeshPolicy::retries must be idempotent — two \
32495                 successive calls on the same &self must return the \
32496                 same Option<u32>",
32497            );
32498            assert_eq!(
32499                first, retries,
32500                "MeshPolicy::retries must return :politicas :retries \
32501                 verbatim by copy — got {first:?}, expected {retries:?}",
32502            );
32503        }
32504    }
32505
32506    #[test]
32507    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
32508        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
32509        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
32510        // return the `:politicas :timeout` typed [`Duration`] verbatim
32511        // as an `Option<Duration>`, byte-equal to the raw field access
32512        // across every representative value in the accept-set — `None`
32513        // (cluster default applies — typically the gateway class's
32514        // implementation-side per-request wall-clock cap the caixa-mesh
32515        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
32516        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
32517        // set the surrounding `AplicacaoSpec::validate_politicas` gate
32518        // carves out on the sibling `PolicyTimeoutZero` /
32519        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
32520        // (the upper boundary the same gate carves out on the sibling
32521        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
32522        // (a past-the-guard sentinel that pins the accessor doesn't
32523        // perform a silent bounds-collapse into `None` on the zero-
32524        // Duration arm — validate rejects zero but the accessor must
32525        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
32526        // past-the-guard sentinel that pins the accessor doesn't
32527        // perform a silent bounds-collapse at the return path).
32528        //
32529        // Sibling of the peer per-`:politicas`
32530        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
32531        // `Option<u32>` optional-scalar axis and the peer per-
32532        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
32533        // pin on the sibling `Option<bool>` optional-scalar axis,
32534        // extended onto the peer per-`:politicas` `Option<Duration>`
32535        // shape — third `Option<Copy-T>`-return accessor on the M3
32536        // mesh-slot family. Pins against a future silent detour that
32537        // re-derived the per-call cap from a peer axis (an accidental
32538        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
32539        // read the breaker's rolling-window duration as a per-call
32540        // deadline), a `None → Some(Duration::MAX)` cluster-default
32541        // projection (which would silently re-introduce the
32542        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
32543        // blocking" arm at the emit boundary), or a bounds-collapsing
32544        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
32545        // (the `AplicacaoSpec::validate` gate owns the bounds; the
32546        // accessor must ship the raw slot verbatim so a validate-time
32547        // gate regression surfaces at the emit boundary rather than
32548        // being silently absorbed).
32549        for timeout in [
32550            None,
32551            Some(Duration::from_millis(1)),
32552            Some(POLICY_TIMEOUT_MAX),
32553            Some(Duration::ZERO),
32554            Some(Duration::MAX),
32555        ] {
32556            let p = MeshPolicy {
32557                timeout,
32558                ..MeshPolicy::default()
32559            };
32560            assert_eq!(
32561                p.timeout(),
32562                timeout,
32563                "MeshPolicy::timeout must return :politicas :timeout \
32564                 verbatim (got {:?}, expected {timeout:?})",
32565                p.timeout(),
32566            );
32567            assert_eq!(
32568                p.timeout(),
32569                p.timeout,
32570                "MeshPolicy::timeout must byte-equal the raw .timeout \
32571                 field access across every value in the accept-set",
32572            );
32573        }
32574    }
32575
32576    #[test]
32577    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
32578        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
32579        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
32580        // field access. Structurally: toggling ONLY the `timeout` slot
32581        // on an otherwise-default MeshPolicy must flip `is_empty()`
32582        // from `true` (all-`None`) to `false` (one axis carries a
32583        // value); the flip must be observed for every value in the
32584        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
32585        // gate accepts (`Some(Duration::from_millis(1))`,
32586        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
32587        // reads "any axis carries a value" — not "any axis carries a
32588        // value the validate gate accepts" — the same non-collapsing
32589        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
32590        // [`crate::BehaviorSpec::is_empty`] predicates carry.
32591        //
32592        // Pins against a future silent detour that re-derived the
32593        // emptiness predicate off a peer axis (an accidental
32594        // `.rate_limit.is_none()`-only chain that dropped the
32595        // `timeout` arm entirely), a `timeout == Some(_)` collapse
32596        // that key-off a validate-gate-clamped bounds check (which
32597        // would silently classify a past-the-guard `Some(Duration::MAX)`
32598        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
32599        // check), or an accessor-side detour that no longer names the
32600        // substrate-primitive typed dispatch.
32601        //
32602        // Sibling of the peer per-`:politicas`
32603        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
32604        // the sibling `Option<u32>` optional-scalar axis and the peer
32605        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
32606        // accessor-composition pin on the sibling `Option<bool>`
32607        // optional-scalar axis — same "the emptiness predicate must
32608        // route through the substrate-primitive typed dispatch"
32609        // discipline extended onto the peer per-`:politicas`
32610        // `Option<Duration>` axis.
32611        let empty = MeshPolicy::default();
32612        assert!(
32613            empty.is_empty(),
32614            "MeshPolicy::default() must be is_empty() — every axis \
32615             defaults to None",
32616        );
32617        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
32618            let p = MeshPolicy {
32619                timeout,
32620                ..MeshPolicy::default()
32621            };
32622            assert!(
32623                !p.is_empty(),
32624                "MeshPolicy::is_empty must return false when \
32625                 :timeout is {timeout:?} — the emptiness \
32626                 predicate reads \"any axis carries a value\", not \
32627                 \"any axis carries a value the validate gate \
32628                 accepts\"",
32629            );
32630            assert_eq!(
32631                p.timeout().is_none(),
32632                p.is_empty(),
32633                "when :timeout is the only set axis, is_empty() \
32634                 must equal timeout().is_none() — the accessor and \
32635                 the emptiness predicate must route through the same \
32636                 substrate-primitive typed dispatch on the :timeout \
32637                 arm",
32638            );
32639        }
32640    }
32641
32642    #[test]
32643    fn mesh_policy_timeout_projects_option_duration_by_copy() {
32644        // The by-copy pin: [`MeshPolicy::timeout`] returns
32645        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
32646        // and the accessor must return by value, not by reference.
32647        // Sibling of the peer per-`:politicas`
32648        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
32649        // sibling `Option<u32>` optional-scalar axis and the peer
32650        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
32651        // by-copy pin on the sibling `Option<bool>` optional-scalar
32652        // axis, extended onto the peer per-`:politicas`
32653        // `Option<Duration>` copy-invariant shape — the accessor's
32654        // returned `Option<Duration>` must outlive `&self` (multiple
32655        // calls must return equal values from a dropped-`&self`
32656        // copy, since the returned Option carries no borrow), and
32657        // calling the accessor twice on the same MeshPolicy must
32658        // yield the same `Option<Duration>` verbatim (idempotent, no
32659        // side effects on `&self`).
32660        //
32661        // Pins against a future silent detour that returned
32662        // `Option<&Duration>` (which would type-check but silently
32663        // break every downstream caller — [`crate::render::single_field_overlay`]'s
32664        // first parameter is `Option<T: Clone>`, and `&Duration`
32665        // would fold to a detached copy at the call site), an
32666        // accidental `Option::as_ref()` projection
32667        // (`self.timeout.as_ref()` would also type-check but return
32668        // `Option<&Duration>`), or a one-arm-only accessor that
32669        // reads `Some(*d)` in the Some arm but reads a fresh
32670        // `Default::default()` (`Duration::ZERO`) in the None arm
32671        // (which would silently re-classify every unset `:timeout`
32672        // as the `PolicyTimeoutZero`-refused zero-Duration value at
32673        // the accessor boundary).
32674        for timeout in [
32675            None,
32676            Some(Duration::from_millis(1)),
32677            Some(POLICY_TIMEOUT_MAX),
32678            Some(Duration::ZERO),
32679            Some(Duration::MAX),
32680        ] {
32681            let p = MeshPolicy {
32682                timeout,
32683                ..MeshPolicy::default()
32684            };
32685            let first = p.timeout();
32686            let second = p.timeout();
32687            assert_eq!(
32688                first, second,
32689                "MeshPolicy::timeout must be idempotent — two \
32690                 successive calls on the same &self must return the \
32691                 same Option<Duration>",
32692            );
32693            assert_eq!(
32694                first, timeout,
32695                "MeshPolicy::timeout must return :politicas :timeout \
32696                 verbatim by copy — got {first:?}, expected {timeout:?}",
32697            );
32698        }
32699    }
32700
32701    #[test]
32702    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
32703        // The canonical per-`:politicas` `:rate-limit` Envoy-
32704        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
32705        // [`MeshPolicy::rate_limit`] must return the `:politicas
32706        // :rate-limit` typed [`RateLimit`] verbatim as an
32707        // `Option<RateLimit>`, byte-equal to the raw field access
32708        // across every representative value in the accept-set — `None`
32709        // (cluster default applies — no per-Aplicacao rate declaration,
32710        // the gateway-class per-listener default arm the future caixa-
32711        // mesh `local_rate_limit_overlay` emitter documents),
32712        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
32713        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
32714        // accept-set the surrounding
32715        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
32716        // sibling `PolicyRateLimitZero` refusal, paired with the
32717        // canonical-window "1 second" arm of the three-unit
32718        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
32719        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
32720        // (the upper boundary the same gate carves out on the sibling
32721        // `PolicyRateLimitExceedsCap` refusal, paired with the
32722        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
32723        // (a past-the-guard sentinel that pins the accessor doesn't
32724        // perform a silent bounds-collapse into `None` on the
32725        // zero-rate/zero-window arm — validate rejects zero but the
32726        // accessor must ship the raw slot verbatim so a validate-time
32727        // gate regression surfaces at the emit boundary rather than
32728        // being silently absorbed), and
32729        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
32730        // (a past-the-guard sentinel that pins the accessor doesn't
32731        // perform a silent bounds-collapse at the return path).
32732        //
32733        // First `Option<Copy-composite-T>`-return accessor pin on the
32734        // M3 mesh-slot family (peer of the sibling per-`:politicas`
32735        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
32736        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
32737        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
32738        // Copy accessor pins, extended onto the peer per-`:politicas`
32739        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
32740        // and the accessor returns by value). Pins against a future
32741        // silent detour that re-derived the rate declaration from a
32742        // peer axis (an accidental
32743        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
32744        // collapse that read the breaker's trip threshold + rolling
32745        // window as a rate declaration), a `None → Some(default())`
32746        // cluster-default projection (which would silently re-
32747        // introduce a "cluster default is 0/s" arm the emit boundary
32748        // would take as "declared but inert" — the canonical
32749        // declared-but-inert footgun the sibling
32750        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
32751        // amplification-shape axis), a bounds-collapsing accessor
32752        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
32753        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
32754        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
32755        // accessor must ship the raw slot verbatim), or a
32756        // by-reference detour (`Option<&RateLimit>`) that broke every
32757        // downstream consumer keying off `Option<RateLimit>` by-copy.
32758        for rl in [
32759            None,
32760            Some(RateLimit {
32761                rate: 1,
32762                window: Duration::from_secs(1),
32763            }),
32764            Some(RateLimit {
32765                rate: POLICY_RATE_LIMIT_MAX,
32766                window: Duration::from_secs(3600),
32767            }),
32768            Some(RateLimit {
32769                rate: 0,
32770                window: Duration::ZERO,
32771            }),
32772            Some(RateLimit {
32773                rate: u32::MAX,
32774                window: Duration::MAX,
32775            }),
32776        ] {
32777            let p = MeshPolicy {
32778                rate_limit: rl,
32779                ..MeshPolicy::default()
32780            };
32781            assert_eq!(
32782                p.rate_limit(),
32783                rl,
32784                "MeshPolicy::rate_limit must return :politicas :rate-limit \
32785                 verbatim (got {:?}, expected {rl:?})",
32786                p.rate_limit(),
32787            );
32788            assert_eq!(
32789                p.rate_limit(),
32790                p.rate_limit,
32791                "MeshPolicy::rate_limit must byte-equal the raw \
32792                 .rate_limit field access across every value in the \
32793                 accept-set",
32794            );
32795        }
32796    }
32797
32798    #[test]
32799    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
32800        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
32801        // must key off [`MeshPolicy::rate_limit`], not the raw
32802        // `.rate_limit` field access. Structurally: toggling ONLY the
32803        // `rate_limit` slot on an otherwise-default MeshPolicy must
32804        // flip `is_empty()` from `true` (all-`None`) to `false` (one
32805        // axis carries a value); the flip must be observed for every
32806        // representative value in the accept-set the surrounding
32807        // [`AplicacaoSpec::validate_politicas`] gate accepts
32808        // (`Some(RateLimit { rate: 1, window: 1s })`,
32809        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
32810        // since the emptiness semantic reads "any axis carries a
32811        // value" — not "any axis carries a value the validate gate
32812        // accepts" — the same non-collapsing shape the peer M2
32813        // [`crate::LimitsSpec::is_empty`] /
32814        // [`crate::BehaviorSpec::is_empty`] predicates carry.
32815        //
32816        // Pins against a future silent detour that re-derived the
32817        // emptiness predicate off a peer axis (an accidental
32818        // `.timeout.is_none()`-only chain that dropped the
32819        // `rate_limit` arm entirely — the last unlifted inline field
32820        // access on `is_empty` before this lift), a `rate_limit ==
32821        // Some(_)` collapse that key-off a validate-gate-clamped
32822        // bounds check (which would silently classify a past-the-
32823        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
32824        // because it fails the value-shape gate), or an accessor-
32825        // side detour that no longer names the substrate-primitive
32826        // typed dispatch.
32827        //
32828        // Fourth "the emptiness predicate must route through the
32829        // substrate-primitive typed dispatch" composition pin on the
32830        // M3 mesh-slot family — closes the last unlifted composition
32831        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
32832        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
32833        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
32834        // 7073d0f is_empty-composition pins on the sibling primitive-
32835        // Copy axes, extended onto the peer per-`:politicas`
32836        // composite-Copy `Option<RateLimit>` axis).
32837        let empty = MeshPolicy::default();
32838        assert!(
32839            empty.is_empty(),
32840            "MeshPolicy::default() must be is_empty() — every axis \
32841             defaults to None",
32842        );
32843        for rl in [
32844            RateLimit {
32845                rate: 1,
32846                window: Duration::from_secs(1),
32847            },
32848            RateLimit {
32849                rate: POLICY_RATE_LIMIT_MAX,
32850                window: Duration::from_secs(3600),
32851            },
32852        ] {
32853            let p = MeshPolicy {
32854                rate_limit: Some(rl),
32855                ..MeshPolicy::default()
32856            };
32857            assert!(
32858                !p.is_empty(),
32859                "MeshPolicy::is_empty must return false when \
32860                 :rate-limit is {rl:?} — the emptiness predicate \
32861                 reads \"any axis carries a value\", not \"any axis \
32862                 carries a value the validate gate accepts\"",
32863            );
32864            assert_eq!(
32865                p.rate_limit().is_none(),
32866                p.is_empty(),
32867                "when :rate-limit is the only set axis, is_empty() \
32868                 must equal rate_limit().is_none() — the accessor \
32869                 and the emptiness predicate must route through the \
32870                 same substrate-primitive typed dispatch on the \
32871                 :rate-limit arm",
32872            );
32873        }
32874    }
32875
32876    #[test]
32877    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
32878        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32879        // `:rate-limit` value-shape gate must key off
32880        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
32881        // field bind. Structurally: a `MeshPolicy` whose only set
32882        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
32883        // the `PolicyRateLimitZero` refusal exactly, and the same
32884        // MeshPolicy with the rate at the canonical lower boundary
32885        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
32886        // The pair jointly pins the accessor + validate-gate
32887        // composition: any future silent detour that had the accessor
32888        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
32889        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
32890        // silently absorb the `PolicyRateLimitZero` refusal at the
32891        // accessor boundary — the composition pin catches that at
32892        // caixa-core build time.
32893        //
32894        // Sibling of the peer [`validate_politicas`]
32895        // `:mtls-required` / `:retries` / `:timeout` composition pins
32896        // on the sibling primitive-Copy optional-scalar axes — same
32897        // "the validate / shape-gate predicate must route through the
32898        // substrate-primitive typed dispatch" discipline extended
32899        // onto the peer per-`:politicas` composite-Copy
32900        // `Option<RateLimit>` axis. Second composition-with-accessor
32901        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
32902        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
32903        let mut spec = three_member_spec();
32904        spec.politicas = MeshPolicy {
32905            rate_limit: Some(RateLimit {
32906                rate: 0,
32907                window: Duration::from_secs(1),
32908            }),
32909            ..MeshPolicy::default()
32910        };
32911        assert!(
32912            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32913            "validate_politicas must reject rate == 0 with \
32914             PolicyRateLimitZero — the accessor and the validate gate \
32915             must route through the same substrate-primitive typed \
32916             dispatch on the :rate-limit zero-floor arm",
32917        );
32918        spec.politicas = MeshPolicy {
32919            rate_limit: Some(RateLimit {
32920                rate: 1,
32921                window: Duration::from_secs(1),
32922            }),
32923            ..MeshPolicy::default()
32924        };
32925        assert!(
32926            spec.validate().is_ok(),
32927            "validate_politicas must accept rate == 1 (the canonical \
32928             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
32929             set) with a canonical 1s window",
32930        );
32931    }
32932
32933    #[test]
32934    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
32935        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
32936        // `outlier_detection`-mesh consecutive-failure-ejection scalar
32937        // pin: [`MeshPolicy::circuit_breaker`] must return the
32938        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
32939        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
32940        // raw field access across every representative value in the
32941        // accept-set — `None` (cluster default applies — no
32942        // per-Aplicacao breaker declaration, the gateway-class per-
32943        // listener default arm the future caixa-mesh
32944        // `outlier_detection_overlay` emitter documents),
32945        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
32946        // (the lower boundary of the accept-set the surrounding
32947        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
32948        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
32949        // refusals),
32950        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
32951        // (the upper boundary the same gate carves out on the sibling
32952        // `PolicyBreakerMaxFailuresExceedsCap` /
32953        // `PolicyBreakerWindowExceedsCap` refusals),
32954        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
32955        // (a past-the-guard sentinel that pins the accessor doesn't
32956        // perform a silent bounds-collapse into `None` on the
32957        // zero-failures/zero-window arm — validate rejects zero but
32958        // the accessor must ship the raw slot verbatim so a validate-
32959        // time gate regression surfaces at the emit boundary rather
32960        // than being silently absorbed), and
32961        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
32962        // (a past-the-guard sentinel that pins the accessor doesn't
32963        // perform a silent bounds-collapse at the return path).
32964        //
32965        // Second `Option<Copy-composite-T>`-return accessor pin on the
32966        // M3 mesh-slot family (peer of the sibling per-`:politicas`
32967        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
32968        // composite-Copy accessor pin, and of the sibling per-
32969        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
32970        // [`MeshPolicy::retries`] bdfb399 /
32971        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
32972        // accessor pins). Pins against a future silent detour that
32973        // re-derived the breaker declaration from a peer axis (an
32974        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
32975        // collapse that read the rate-limit's bucket capacity + refill
32976        // period as a breaker declaration), a `None → Some(default())`
32977        // cluster-default projection (which would silently re-
32978        // introduce the `PolicyBreakerZeroFailures` /
32979        // `PolicyBreakerZeroWindow` refusal cases at the emit
32980        // boundary), a bounds-collapsing accessor that clamped
32981        // `cb.max_failures` through
32982        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
32983        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
32984        // [`AplicacaoSpec::validate`] gate owns the bounds; the
32985        // accessor must ship the raw slot verbatim), or a
32986        // by-reference detour (`Option<&CircuitBreaker>`) that broke
32987        // every downstream consumer keying off `Option<CircuitBreaker>`
32988        // by-copy.
32989        for cb in [
32990            None,
32991            Some(CircuitBreaker {
32992                max_failures: 1,
32993                window: Duration::from_millis(1),
32994            }),
32995            Some(CircuitBreaker {
32996                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
32997                window: POLICY_BREAKER_WINDOW_MAX,
32998            }),
32999            Some(CircuitBreaker {
33000                max_failures: 0,
33001                window: Duration::ZERO,
33002            }),
33003            Some(CircuitBreaker {
33004                max_failures: u32::MAX,
33005                window: Duration::MAX,
33006            }),
33007        ] {
33008            let p = MeshPolicy {
33009                circuit_breaker: cb,
33010                ..MeshPolicy::default()
33011            };
33012            assert_eq!(
33013                p.circuit_breaker(),
33014                cb,
33015                "MeshPolicy::circuit_breaker must return :politicas \
33016                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
33017                p.circuit_breaker(),
33018            );
33019            assert_eq!(
33020                p.circuit_breaker(),
33021                p.circuit_breaker,
33022                "MeshPolicy::circuit_breaker must byte-equal the raw \
33023                 .circuit_breaker field access across every value in \
33024                 the accept-set",
33025            );
33026        }
33027    }
33028
33029    #[test]
33030    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
33031        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
33032        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
33033        // `.circuit_breaker` field access. Structurally: toggling ONLY
33034        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
33035        // must flip `is_empty()` from `true` (all-`None`) to `false`
33036        // (one axis carries a value); the flip must be observed for
33037        // every representative value in the accept-set the surrounding
33038        // [`AplicacaoSpec::validate_politicas`] gate accepts
33039        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
33040        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
33041        // since the emptiness semantic reads "any axis carries a
33042        // value" — not "any axis carries a value the validate gate
33043        // accepts" — the same non-collapsing shape the peer M2
33044        // [`crate::LimitsSpec::is_empty`] /
33045        // [`crate::BehaviorSpec::is_empty`] predicates carry.
33046        //
33047        // Pins against a future silent detour that re-derived the
33048        // emptiness predicate off a peer axis (an accidental
33049        // `.rate_limit.is_none()`-only chain that dropped the
33050        // `circuit_breaker` arm entirely — the last unlifted inline
33051        // field access on `is_empty` before this lift), a
33052        // `circuit_breaker == Some(_)` collapse that key-off a
33053        // validate-gate-clamped bounds check (which would silently
33054        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
33055        // 0, window: 0s })` as empty because it fails the value-shape
33056        // gate), or an accessor-side detour that no longer names the
33057        // substrate-primitive typed dispatch.
33058        //
33059        // Fifth "the emptiness predicate must route through the
33060        // substrate-primitive typed dispatch" composition pin on the
33061        // M3 mesh-slot family — closes the last unlifted composition
33062        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
33063        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
33064        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
33065        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
33066        // composition pins on the sibling primitive-Copy + composite-
33067        // Copy axes, extended onto the peer per-`:politicas`
33068        // composite-Copy `Option<CircuitBreaker>` axis).
33069        let empty = MeshPolicy::default();
33070        assert!(
33071            empty.is_empty(),
33072            "MeshPolicy::default() must be is_empty() — every axis \
33073             defaults to None",
33074        );
33075        for cb in [
33076            CircuitBreaker {
33077                max_failures: 1,
33078                window: Duration::from_millis(1),
33079            },
33080            CircuitBreaker {
33081                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
33082                window: POLICY_BREAKER_WINDOW_MAX,
33083            },
33084        ] {
33085            let p = MeshPolicy {
33086                circuit_breaker: Some(cb),
33087                ..MeshPolicy::default()
33088            };
33089            assert!(
33090                !p.is_empty(),
33091                "MeshPolicy::is_empty must return false when \
33092                 :circuit-breaker is {cb:?} — the emptiness predicate \
33093                 reads \"any axis carries a value\", not \"any axis \
33094                 carries a value the validate gate accepts\"",
33095            );
33096            assert_eq!(
33097                p.circuit_breaker().is_none(),
33098                p.is_empty(),
33099                "when :circuit-breaker is the only set axis, \
33100                 is_empty() must equal circuit_breaker().is_none() — \
33101                 the accessor and the emptiness predicate must route \
33102                 through the same substrate-primitive typed dispatch \
33103                 on the :circuit-breaker arm",
33104            );
33105        }
33106    }
33107
33108    #[test]
33109    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
33110        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33111        // `:circuit-breaker` value-shape gate must key off
33112        // [`MeshPolicy::circuit_breaker`], not the raw
33113        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
33114        // whose only set axis is a `Some(CircuitBreaker { max_failures:
33115        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
33116        // refusal exactly, and the same MeshPolicy with the breaker at
33117        // the canonical lower boundary
33118        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
33119        // pass validate. The pair jointly pins the accessor +
33120        // validate-gate composition: any future silent detour that had
33121        // the accessor omit the `Some(CircuitBreaker { max_failures:
33122        // 0, .. })` arm (a
33123        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
33124        // collapse) would silently absorb the
33125        // `PolicyBreakerZeroFailures` refusal at the accessor
33126        // boundary — the composition pin catches that at caixa-core
33127        // build time.
33128        //
33129        // Sibling of the peer [`validate_politicas`]
33130        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
33131        // composition pins on the sibling primitive-Copy + composite-
33132        // Copy optional-scalar axes — same "the validate / shape-gate
33133        // predicate must route through the substrate-primitive typed
33134        // dispatch" discipline extended onto the peer per-`:politicas`
33135        // composite-Copy `Option<CircuitBreaker>` axis. Second
33136        // composition-with-accessor pin on the M3 mesh-slot
33137        // `Option<CircuitBreaker>` arm alongside the
33138        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
33139        let mut spec = three_member_spec();
33140        spec.politicas = MeshPolicy {
33141            circuit_breaker: Some(CircuitBreaker {
33142                max_failures: 0,
33143                window: Duration::from_millis(1),
33144            }),
33145            ..MeshPolicy::default()
33146        };
33147        assert!(
33148            matches!(
33149                spec.validate(),
33150                Err(AplicacaoError::PolicyBreakerZeroFailures)
33151            ),
33152            "validate_politicas must reject max_failures == 0 with \
33153             PolicyBreakerZeroFailures — the accessor and the validate \
33154             gate must route through the same substrate-primitive \
33155             typed dispatch on the :circuit-breaker zero-floor arm",
33156        );
33157        spec.politicas = MeshPolicy {
33158            circuit_breaker: Some(CircuitBreaker {
33159                max_failures: 1,
33160                window: Duration::from_millis(1),
33161            }),
33162            ..MeshPolicy::default()
33163        };
33164        assert!(
33165            spec.validate().is_ok(),
33166            "validate_politicas must accept a CircuitBreaker at the \
33167             canonical lower boundary (max_failures = 1, window = \
33168             1ms) — the accessor and the validate gate must route \
33169             through the same substrate-primitive typed dispatch on \
33170             the :circuit-breaker arm",
33171        );
33172    }
33173
33174    #[test]
33175    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
33176        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
33177        // Envoy-outlier-detection trip-threshold scalar pin:
33178        // [`CircuitBreaker::max_failures`] must return the
33179        // `:politicas :circuit-breaker :max-failures` typed `u32`
33180        // verbatim, byte-equal to the raw field access across every
33181        // representative value in the accept-set — `1` (the lower
33182        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
33183        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
33184        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
33185        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
33186        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
33187        // refusal), `0` (a past-the-guard sentinel that pins the accessor
33188        // doesn't perform a silent bounds-collapse into `1` on the zero
33189        // arm — validate rejects zero but the accessor must ship the
33190        // raw slot verbatim so a validate-time gate regression surfaces
33191        // at the emit boundary rather than being silently absorbed),
33192        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
33193        // doesn't perform a silent bounds-collapse through
33194        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
33195        //
33196        // First sub-struct required-scalar accessor pin on the M3
33197        // mesh-slot family — sibling in shape to the peer per-`:membros`
33198        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
33199        // (a40b0e3) required-`String`-carry accessor pins and the peer
33200        // per-`:contratos` [`WitContract::source`] /
33201        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
33202        // accessor pins, extended onto the peer per-`CircuitBreaker`
33203        // required-`u32` scalar-value axis. Pins against a future silent
33204        // detour that re-derived the trip threshold from a peer axis (an
33205        // accidental `self.window.as_secs() as u32` collapse that read
33206        // the breaker's rolling-window duration as a failure count), a
33207        // `0 → 1` cluster-default projection (which would silently absorb
33208        // the `PolicyBreakerZeroFailures` refusal case at the accessor
33209        // boundary), or a bounds-collapsing accessor that clamped the
33210        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
33211        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
33212        // must ship the raw slot verbatim).
33213        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
33214            let cb = CircuitBreaker {
33215                max_failures,
33216                window: Duration::from_secs(60),
33217            };
33218            assert_eq!(
33219                cb.max_failures(),
33220                max_failures,
33221                "CircuitBreaker::max_failures must return :politicas \
33222                 :circuit-breaker :max-failures verbatim (got {}, \
33223                 expected {max_failures})",
33224                cb.max_failures(),
33225            );
33226            assert_eq!(
33227                cb.max_failures(),
33228                cb.max_failures,
33229                "CircuitBreaker::max_failures must byte-equal the raw \
33230                 .max_failures field access across every value in the \
33231                 u32 accept-set",
33232            );
33233        }
33234    }
33235
33236    #[test]
33237    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
33238        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33239        // `:circuit-breaker :max-failures` zero-floor arm must key off
33240        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
33241        // field access. Structurally: a `CircuitBreaker { max_failures:
33242        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
33243        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
33244        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
33245        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
33246        // pass validate. The pair jointly pins the accessor +
33247        // validate-gate composition: any future silent detour that had
33248        // the accessor return a fresh `1` on the zero arm (a
33249        // `.max_failures().max(1)` collapse) would silently absorb the
33250        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
33251        // and the validate gate would accept a struct-literal
33252        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
33253        // catches that at caixa-core build time.
33254        //
33255        // Peer of the sibling per-`:politicas`
33256        // [`MeshPolicy::mtls_required`] (c0110f1) /
33257        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
33258        // (7073d0f) accessor-composition pins on the sibling optional-
33259        // scalar axes — same "the validate / shape-gate predicate must
33260        // route through the substrate-primitive typed dispatch"
33261        // discipline extended onto the peer per-`CircuitBreaker`
33262        // required-scalar composition axis.
33263        let mut spec = three_member_spec();
33264        spec.politicas = MeshPolicy {
33265            circuit_breaker: Some(CircuitBreaker {
33266                max_failures: 0,
33267                window: Duration::from_secs(60),
33268            }),
33269            ..MeshPolicy::default()
33270        };
33271        assert!(
33272            matches!(
33273                spec.validate(),
33274                Err(AplicacaoError::PolicyBreakerZeroFailures)
33275            ),
33276            "validate_politicas must reject max_failures == 0 with \
33277             PolicyBreakerZeroFailures — the accessor and the validate \
33278             gate must route through the same substrate-primitive typed \
33279             dispatch on the :max-failures zero-floor arm",
33280        );
33281        spec.politicas = MeshPolicy {
33282            circuit_breaker: Some(CircuitBreaker {
33283                max_failures: 1,
33284                window: Duration::from_secs(60),
33285            }),
33286            ..MeshPolicy::default()
33287        };
33288        assert!(
33289            spec.validate().is_ok(),
33290            "validate_politicas must accept max_failures == 1 (the \
33291             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
33292             accept-set)",
33293        );
33294    }
33295
33296    #[test]
33297    fn circuit_breaker_max_failures_projects_u32_by_copy() {
33298        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
33299        // `u32` by copy — `u32` is `Copy` and the accessor must return
33300        // by value, not by reference. Peer of the sibling
33301        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
33302        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
33303        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
33304        // optional-scalar axes, extended onto the peer
33305        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
33306        // the accessor's returned `u32` must outlive `&self` (multiple
33307        // calls must return equal values from a dropped-`&self` copy,
33308        // since the returned scalar carries no borrow), and calling
33309        // the accessor twice on the same CircuitBreaker must yield the
33310        // same `u32` verbatim (idempotent, no side effects on `&self`).
33311        //
33312        // Pins against a future silent detour that returned `&u32`
33313        // (which would type-check but silently break every downstream
33314        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
33315        // first parameter is `u32`, and `&u32` would fold to a detached
33316        // copy at the call site with a `*` deref the sibling accessors
33317        // don't need), an accidental `.max_failures.wrapping_add(0)`
33318        // detour that returned a fresh copy through an arithmetic
33319        // no-op (breaking a future `const fn` regression), or a
33320        // one-arm-only accessor that returned a saturating value on
33321        // some sentinel input (breaking the pass-through invariant the
33322        // sibling required-scalar accessors carry).
33323        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
33324            let cb = CircuitBreaker {
33325                max_failures,
33326                window: Duration::from_secs(60),
33327            };
33328            let first = cb.max_failures();
33329            let second = cb.max_failures();
33330            assert_eq!(
33331                first, second,
33332                "CircuitBreaker::max_failures must be idempotent — two \
33333                 successive calls on the same &self must return the \
33334                 same u32",
33335            );
33336            assert_eq!(
33337                first, max_failures,
33338                "CircuitBreaker::max_failures must return :politicas \
33339                 :circuit-breaker :max-failures verbatim by copy — \
33340                 got {first}, expected {max_failures}",
33341            );
33342        }
33343    }
33344
33345    #[test]
33346    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
33347        // The canonical per-`:politicas :circuit-breaker` `:window`
33348        // Envoy-outlier-detection rolling-observation-interval scalar
33349        // pin: [`CircuitBreaker::window`] must return the
33350        // `:politicas :circuit-breaker :window` typed `Duration`
33351        // verbatim, byte-equal to the raw field access across every
33352        // representative value in the accept-set — `Duration::from_millis(1)`
33353        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
33354        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
33355        // gate carves out on the sibling `PolicyBreakerZeroWindow`
33356        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
33357        // same gate carves out on the sibling
33358        // `PolicyBreakerWindowExceedsCap` refusal),
33359        // `Duration::ZERO` (a past-the-guard sentinel that pins the
33360        // accessor doesn't perform a silent bounds-collapse into
33361        // `Duration::from_millis(1)` on the zero arm — validate rejects
33362        // zero but the accessor must ship the raw slot verbatim so a
33363        // validate-time gate regression surfaces at the emit boundary
33364        // rather than being silently absorbed),
33365        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
33366        // far above the 1h cap — that pins the accessor doesn't perform
33367        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
33368        // at the return path).
33369        //
33370        // Second sub-struct required-scalar accessor pin on the M3
33371        // mesh-slot family — sibling in shape to the just-landed
33372        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
33373        // (3a74062) required-`u32` accessor pin on the peer
33374        // per-`CircuitBreaker` required-axis, extended onto the
33375        // per-sub-struct required-`Duration` axis. Pins against a
33376        // future silent detour that re-derived the observation window
33377        // from a peer axis (an accidental
33378        // `Duration::from_secs(self.max_failures as u64)` collapse that
33379        // read the breaker's trip count as an observation-interval
33380        // duration), a `Duration::ZERO → Duration::from_millis(1)`
33381        // cluster-default projection (which would silently absorb the
33382        // `PolicyBreakerZeroWindow` refusal case at the accessor
33383        // boundary), or a bounds-collapsing accessor that clamped the
33384        // return through `POLICY_BREAKER_WINDOW_MAX` (the
33385        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
33386        // must ship the raw slot verbatim).
33387        for window in [
33388            Duration::from_millis(1),
33389            POLICY_BREAKER_WINDOW_MAX,
33390            Duration::ZERO,
33391            Duration::from_secs(86_400),
33392        ] {
33393            let cb = CircuitBreaker {
33394                max_failures: 5,
33395                window,
33396            };
33397            assert_eq!(
33398                cb.window(),
33399                window,
33400                "CircuitBreaker::window must return :politicas \
33401                 :circuit-breaker :window verbatim (got {:?}, \
33402                 expected {window:?})",
33403                cb.window(),
33404            );
33405            assert_eq!(
33406                cb.window(),
33407                cb.window,
33408                "CircuitBreaker::window must byte-equal the raw \
33409                 .window field access across every value in the \
33410                 Duration accept-set",
33411            );
33412        }
33413    }
33414
33415    #[test]
33416    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
33417        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33418        // `:circuit-breaker :window` zero-floor arm must key off
33419        // [`CircuitBreaker::window`], not the raw `.window` field
33420        // access. Structurally: a `CircuitBreaker { window:
33421        // Duration::ZERO, .. }` embedded in a
33422        // `:politicas :circuit-breaker` slot must surface the
33423        // `PolicyBreakerZeroWindow` refusal exactly, and a
33424        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
33425        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
33426        // accept-set) must pass validate. The pair jointly pins the
33427        // accessor + validate-gate composition: any future silent
33428        // detour that had the accessor return a fresh
33429        // `Duration::from_millis(1)` on the zero arm (a
33430        // `.window().max(Duration::from_millis(1))` collapse) would
33431        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
33432        // accessor boundary and the validate gate would accept a
33433        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
33434        // — the composition pin catches that at caixa-core build time.
33435        //
33436        // Peer of the sibling per-`CircuitBreaker`
33437        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
33438        // pin on the peer required-scalar `:max-failures` axis — same
33439        // "the validate / shape-gate predicate must route through the
33440        // substrate-primitive typed dispatch" discipline extended onto
33441        // the peer per-`CircuitBreaker` required-`Duration` composition
33442        // axis.
33443        let mut spec = three_member_spec();
33444        spec.politicas = MeshPolicy {
33445            circuit_breaker: Some(CircuitBreaker {
33446                max_failures: 5,
33447                window: Duration::ZERO,
33448            }),
33449            ..MeshPolicy::default()
33450        };
33451        assert!(
33452            matches!(
33453                spec.validate(),
33454                Err(AplicacaoError::PolicyBreakerZeroWindow)
33455            ),
33456            "validate_politicas must reject window == Duration::ZERO \
33457             with PolicyBreakerZeroWindow — the accessor and the \
33458             validate gate must route through the same substrate-\
33459             primitive typed dispatch on the :window zero-floor arm",
33460        );
33461        spec.politicas = MeshPolicy {
33462            circuit_breaker: Some(CircuitBreaker {
33463                max_failures: 5,
33464                window: Duration::from_millis(1),
33465            }),
33466            ..MeshPolicy::default()
33467        };
33468        assert!(
33469            spec.validate().is_ok(),
33470            "validate_politicas must accept window == \
33471             Duration::from_millis(1) (the lower boundary of the \
33472             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
33473        );
33474    }
33475
33476    #[test]
33477    fn circuit_breaker_window_projects_duration_by_copy() {
33478        // The by-copy pin: [`CircuitBreaker::window`] returns
33479        // `Duration` by copy — `Duration` is `Copy` and the accessor
33480        // must return by value, not by reference. Peer of the sibling
33481        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
33482        // (3a74062) by-copy pin on the peer required-scalar
33483        // `:max-failures` axis, extended onto the peer
33484        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
33485        // — the accessor's returned `Duration` must outlive `&self`
33486        // (multiple calls must return equal values from a
33487        // dropped-`&self` copy, since the returned scalar carries no
33488        // borrow), and calling the accessor twice on the same
33489        // CircuitBreaker must yield the same `Duration` verbatim
33490        // (idempotent, no side effects on `&self`).
33491        //
33492        // Pins against a future silent detour that returned
33493        // `&Duration` (which would type-check but silently break every
33494        // downstream `Duration`-by-value consumer —
33495        // [`crate::render::require_positive_canonical_bounded_duration`]'s
33496        // first parameter is `Duration`, and `&Duration` would fold to
33497        // a detached copy at the call site with a `*` deref the sibling
33498        // accessors don't need), an accidental `.window + Duration::ZERO`
33499        // detour that returned a fresh copy through an arithmetic
33500        // no-op (breaking a future `const fn` regression), or a
33501        // one-arm-only accessor that returned a saturating value on
33502        // some sentinel input (breaking the pass-through invariant the
33503        // sibling required-scalar accessors carry).
33504        for window in [
33505            Duration::from_millis(1),
33506            POLICY_BREAKER_WINDOW_MAX,
33507            Duration::ZERO,
33508            Duration::from_secs(86_400),
33509        ] {
33510            let cb = CircuitBreaker {
33511                max_failures: 5,
33512                window,
33513            };
33514            let first = cb.window();
33515            let second = cb.window();
33516            assert_eq!(
33517                first, second,
33518                "CircuitBreaker::window must be idempotent — two \
33519                 successive calls on the same &self must return the \
33520                 same Duration",
33521            );
33522            assert_eq!(
33523                first, window,
33524                "CircuitBreaker::window must return :politicas \
33525                 :circuit-breaker :window verbatim by copy — \
33526                 got {first:?}, expected {window:?}",
33527            );
33528        }
33529    }
33530
33531    #[test]
33532    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
33533        // Apex-identity pair-invariant pin composing both substrate-
33534        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
33535        // and [`WitContract::destination`] — at the emit-side call shape
33536        // every per-`(:de, :para)` CNP L4 port reader now takes. The
33537        // invariant, evaluated per-edge:
33538        //
33539        //   spec.port_for_destination(c.destination()) == expected_port
33540        //
33541        // where `expected_port` is `entrada.port` when
33542        // `c.destination() == entrada.destination()` and
33543        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
33544        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
33545        // pin on the per-`:entrada` axis — that pin encodes the apex
33546        // ingress L4 identity via `entrada.destination()`; this pin
33547        // encodes the per-edge L4 identity via `c.destination()`, and
33548        // both compose on the same substrate-primitive resolver so a
33549        // future refactor that silently split either accessor's apex
33550        // behavior surfaces at caixa-core build time.
33551        let mut spec = three_member_spec();
33552        if let Some(e) = spec.entrada.as_mut() {
33553            e.para = "cart".into();
33554            e.port = 8443;
33555        }
33556        let apex_contract = WitContract {
33557            de: "checkout".into(),
33558            para: "cart".into(),
33559            wit: "wasi:http/proxy".into(),
33560            endpoint: Some("/hello".into()),
33561            subject: None,
33562            slot: None,
33563        };
33564        assert_eq!(
33565            spec.port_for_destination(apex_contract.destination()),
33566            8443,
33567            "`spec.port_for_destination(c.destination())` must equal \
33568             `entrada.port` when the contract callee names the ingress \
33569             apex — the CNP per-edge L4 port and the HTTPRoute apex \
33570             backendRef port share this substrate-primitive resolver.",
33571        );
33572        let non_apex_contract = WitContract {
33573            de: "cart".into(),
33574            para: "payment".into(),
33575            wit: "wasi:http/proxy".into(),
33576            endpoint: Some("/charge".into()),
33577            subject: None,
33578            slot: None,
33579        };
33580        assert_eq!(
33581            spec.port_for_destination(non_apex_contract.destination()),
33582            DEFAULT_SERVICO_PORT,
33583            "`spec.port_for_destination(c.destination())` must fall back \
33584             to the substrate-canonical port floor when the contract \
33585             callee is not the ingress apex — the resolver's non-apex \
33586             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
33587        );
33588    }
33589
33590    #[test]
33591    fn membro_key_consts_are_lower_camel_case_shape() {
33592        // Shape-pin: every `MEMBRO_KEY_*` const must be a
33593        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33594        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33595        // leading capital, no whitespace / dots) — the canonical shape
33596        // the `#[serde(rename_all = "camelCase")]` derive produces on
33597        // [`Membro`]. A future flip to a non-camelCase attribute at
33598        // the derive surfaces both here (this test fails on the
33599        // stale-constant shape) and at
33600        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
33601        // fails on the mismatch between const and derive). Peer with
33602        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
33603        // on the sibling `SupervisorSpec` top-level axis.
33604        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
33605            assert!(
33606                !key.is_empty(),
33607                "MEMBRO_KEY_* must be non-empty (got {key:?})"
33608            );
33609            let first = key.chars().next().unwrap();
33610            assert!(
33611                first.is_ascii_lowercase(),
33612                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
33613                 (got {key:?}, leads with {first:?})",
33614            );
33615            assert!(
33616                key.chars().all(|c| c.is_ascii_alphanumeric()),
33617                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
33618                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33619            );
33620        }
33621    }
33622
33623    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
33624
33625    #[test]
33626    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
33627        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
33628        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
33629        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
33630        // keys the `#[serde(rename_all = "camelCase")]` attribute on
33631        // [`WitContract`] emits for the required-triad. The three
33632        // sibling payload-arm keys already pin under
33633        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
33634        // `STORE_FIELD_NAME` — pin all six alongside so a future
33635        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
33636        // verbatim-field-name flip at the derive attribute (any of which
33637        // would silently break every downstream JSON consumer that
33638        // reaches for one of the six via `Value::get(...)`) surfaces
33639        // here as a build-time test failure at `aplicacao.rs`, not as an
33640        // apply-time `.get(<stale-canonical-const>)` returning `None`
33641        // far from the derive-attr drift's commit. Peer with the sibling
33642        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
33643        // pin on the M3 `:membros` per-entry axis — same discipline the
33644        // `Membro` per-entry lift established, extended here to the
33645        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
33646        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
33647        // axis on the Aplicacao surface without a lifted serde-key peer.
33648        let c = WitContract {
33649            de: "cart".into(),
33650            para: "catalog".into(),
33651            wit: "wasi:http/proxy".into(),
33652            endpoint: Some("/lookup".into()),
33653            subject: None,
33654            slot: None,
33655        };
33656        let json = serde_json::to_string(&c).unwrap();
33657        for key in [
33658            crate::CONTRATO_KEY_DE,
33659            crate::CONTRATO_KEY_PARA,
33660            crate::CONTRATO_KEY_WIT,
33661            WitTarget::HTTP_FIELD_NAME,
33662        ] {
33663            let quoted = format!("\"{key}\"");
33664            assert!(
33665                json.contains(&quoted),
33666                "serialized WitContract must carry the lifted \
33667                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
33668                 {quoted} verbatim in the JSON emission (got: {json})",
33669            );
33670        }
33671
33672        // Pin the two remaining payload-arm keys by round-tripping a
33673        // `WitContract` under each payload-shape (pub-sub, store) — the
33674        // required-triad appears on every emission but the payload arms
33675        // only surface when their `Option<String>` field is `Some`.
33676        let pubsub = WitContract {
33677            de: "cart".into(),
33678            para: "events".into(),
33679            wit: "nats:pub-sub".into(),
33680            endpoint: None,
33681            subject: Some("orders.placed".into()),
33682            slot: None,
33683        };
33684        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
33685        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
33686        assert!(
33687            pubsub_json.contains(&pubsub_quoted),
33688            "serialized pub-sub WitContract must carry the lifted \
33689             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
33690             verbatim in the JSON emission (got: {pubsub_json})",
33691        );
33692        let store = WitContract {
33693            de: "cart".into(),
33694            para: "sessions".into(),
33695            wit: "wasi:keyvalue/store".into(),
33696            endpoint: None,
33697            subject: None,
33698            slot: Some("cart/$id".into()),
33699        };
33700        let store_json = serde_json::to_string(&store).unwrap();
33701        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
33702        assert!(
33703            store_json.contains(&store_quoted),
33704            "serialized store WitContract must carry the lifted \
33705             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
33706             verbatim in the JSON emission (got: {store_json})",
33707        );
33708    }
33709
33710    #[test]
33711    fn contrato_key_consts_are_pairwise_distinct() {
33712        // Cross-axis drift-detection pin: a future collapse of the six
33713        // canonical [`WitContract`] per-entry byte-strings onto the same
33714        // value (e.g. an accidental copy-paste flip of
33715        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
33716        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
33717        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
33718        // every downstream probe on one axis onto the sibling axis's
33719        // overlay entry and pass every propagation-probe test that
33720        // expected only the stale axis's value. Peer of the sibling
33721        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
33722        // widened here to the six-way axis the `WitContract`
33723        // required-triad + `WitTarget` payload-triad jointly cover.
33724        let all = [
33725            crate::CONTRATO_KEY_DE,
33726            crate::CONTRATO_KEY_PARA,
33727            crate::CONTRATO_KEY_WIT,
33728            WitTarget::HTTP_FIELD_NAME,
33729            WitTarget::PUBSUB_FIELD_NAME,
33730            WitTarget::STORE_FIELD_NAME,
33731        ];
33732        for (i, a) in all.iter().enumerate() {
33733            for b in all.iter().skip(i + 1) {
33734                assert_ne!(
33735                    a, b,
33736                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
33737                     must be pairwise-distinct canonical byte-sequences \
33738                     — got `{a}` == `{b}`",
33739                );
33740            }
33741        }
33742    }
33743
33744    #[test]
33745    fn contrato_key_consts_are_lower_camel_case_shape() {
33746        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
33747        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
33748        // byte-sequence (no `snake_case` underscores, no `kebab-case`
33749        // hyphens, no leading colon, no `PascalCase` leading capital, no
33750        // whitespace / dots) — the canonical shape the
33751        // `#[serde(rename_all = "camelCase")]` derive produces on
33752        // [`WitContract`]. A future flip to a non-camelCase attribute at
33753        // the derive surfaces both here (this test fails on the
33754        // stale-constant shape) and at
33755        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
33756        // (that test fails on the mismatch between const and derive).
33757        // Peer with `membro_key_consts_are_lower_camel_case_shape`
33758        // (ce80ca0) on the sibling `Membro` per-entry axis.
33759        for key in [
33760            crate::CONTRATO_KEY_DE,
33761            crate::CONTRATO_KEY_PARA,
33762            crate::CONTRATO_KEY_WIT,
33763            WitTarget::HTTP_FIELD_NAME,
33764            WitTarget::PUBSUB_FIELD_NAME,
33765            WitTarget::STORE_FIELD_NAME,
33766        ] {
33767            assert!(
33768                !key.is_empty(),
33769                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
33770                 non-empty (got {key:?})"
33771            );
33772            let first = key.chars().next().unwrap();
33773            assert!(
33774                first.is_ascii_lowercase(),
33775                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
33776                 with an ASCII-lowercase byte (got {key:?}, leads with \
33777                 {first:?})",
33778            );
33779            assert!(
33780                key.chars().all(|c| c.is_ascii_alphanumeric()),
33781                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
33782                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
33783                 whitespace (got {key:?})",
33784            );
33785        }
33786    }
33787
33788    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
33789
33790    #[test]
33791    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
33792        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
33793        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
33794        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
33795        // name the exact camelCase JSON keys the
33796        // `#[serde(rename_all = "camelCase")]` attribute on
33797        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
33798        // pin that each canonical byte-sequence appears verbatim in the
33799        // JSON — a future accidental `rename_all = "snake_case"` /
33800        // `"kebab-case"` / verbatim-field-name flip at the derive
33801        // attribute (any of which would silently break every downstream
33802        // JSON consumer that reaches for one of the four consts via
33803        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
33804        // emitter's per-Aplicacao hostname/paths/port projection, the
33805        // future `app-operator` reconciler's per-Aplicacao ingress
33806        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
33807        // materializer's admission-time cross-check) surfaces here as
33808        // a build-time test failure at `aplicacao.rs`, not as an
33809        // apply-time `.get(<stale-canonical-const>)` returning `None`
33810        // far from the derive-attr drift's commit. Peer with the
33811        // sibling
33812        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
33813        // (ca463a4) and
33814        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
33815        // pins on the M3 collection-slot atom axes — same discipline
33816        // both collection-slot lifts established, extended here to the
33817        // singleton `:entrada` mesh-slot atom axis, the last M3
33818        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
33819        // axis on the Aplicacao surface without a lifted serde-key
33820        // peer.
33821        let e = Entrada {
33822            host: "checkout.quero.cloud".into(),
33823            para: "cart".into(),
33824            paths: vec!["/cart".into()],
33825            port: 8080,
33826        };
33827        let json = serde_json::to_string(&e).unwrap();
33828        for key in [
33829            crate::ENTRADA_KEY_HOST,
33830            crate::ENTRADA_KEY_PARA,
33831            crate::ENTRADA_KEY_PATHS,
33832            crate::ENTRADA_KEY_PORT,
33833        ] {
33834            let quoted = format!("\"{key}\"");
33835            assert!(
33836                json.contains(&quoted),
33837                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
33838                 byte-sequence {quoted} verbatim in the JSON emission \
33839                 (got: {json})",
33840            );
33841        }
33842    }
33843
33844    #[test]
33845    fn entrada_key_consts_are_pairwise_distinct() {
33846        // Cross-axis drift-detection pin: a future collapse of the four
33847        // canonical [`Entrada`] singleton byte-strings onto the same
33848        // value (e.g. an accidental copy-paste flip of
33849        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
33850        // silently reroute every downstream probe on one axis onto the
33851        // sibling axis's overlay entry and pass every propagation-probe
33852        // test that expected only the stale axis's value — the
33853        // Gateway/HTTPRoute emitter would read the hostname string
33854        // where the destination-Servico name was expected (or vice
33855        // versa), the admission-webhook cross-check would compare the
33856        // wrong pair of values, and the resulting Gateway resource
33857        // would either be admitted with garbage or rejected at the
33858        // controller far from the rebrand commit's source. Peer of the
33859        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
33860        // tetrad (40cc4e5), the two-way distinct pin on the
33861        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
33862        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
33863        // triad (ca463a4).
33864        let all = [
33865            crate::ENTRADA_KEY_HOST,
33866            crate::ENTRADA_KEY_PARA,
33867            crate::ENTRADA_KEY_PATHS,
33868            crate::ENTRADA_KEY_PORT,
33869        ];
33870        for (i, a) in all.iter().enumerate() {
33871            for b in all.iter().skip(i + 1) {
33872                assert_ne!(
33873                    a, b,
33874                    "ENTRADA_KEY_* consts must be pairwise-distinct \
33875                     canonical byte-sequences — got `{a}` == `{b}`",
33876                );
33877            }
33878        }
33879    }
33880
33881    #[test]
33882    fn entrada_key_consts_are_lower_camel_case_shape() {
33883        // Shape-pin: every `ENTRADA_KEY_*` const must be a
33884        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33885        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33886        // leading capital, no whitespace / dots) — the canonical shape
33887        // the `#[serde(rename_all = "camelCase")]` derive produces on
33888        // [`Entrada`]. A future flip to a non-camelCase attribute at
33889        // the derive surfaces both here (this test fails on the
33890        // stale-constant shape) and at
33891        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
33892        // test fails on the mismatch between const and derive). Peer
33893        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
33894        // and `contrato_key_consts_are_lower_camel_case_shape`
33895        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
33896        // entry axes.
33897        for key in [
33898            crate::ENTRADA_KEY_HOST,
33899            crate::ENTRADA_KEY_PARA,
33900            crate::ENTRADA_KEY_PATHS,
33901            crate::ENTRADA_KEY_PORT,
33902        ] {
33903            assert!(
33904                !key.is_empty(),
33905                "ENTRADA_KEY_* must be non-empty (got {key:?})"
33906            );
33907            let first = key.chars().next().unwrap();
33908            assert!(
33909                first.is_ascii_lowercase(),
33910                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
33911                 (got {key:?}, leads with {first:?})",
33912            );
33913            assert!(
33914                key.chars().all(|c| c.is_ascii_alphanumeric()),
33915                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
33916                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33917            );
33918        }
33919    }
33920
33921    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
33922
33923    #[test]
33924    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
33925        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
33926        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
33927        // [`crate::POLITICAS_KEY_RETRIES`] /
33928        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
33929        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
33930        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
33931        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
33932        // on [`MeshPolicy`] emits. Three of the five axes
33933        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
33934        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
33935        // camelCase transforms — the derive-attribute is load-bearing
33936        // on those, unlike the sibling `Entrada` / `Membro` /
33937        // `WitContract` structs whose fields are all lowercase-single-
33938        // word and where the derive is a no-op on every axis.
33939        // Serialize a fully-populated [`MeshPolicy`] (every axis
33940        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
33941        // on none of the five slots) and pin that each canonical
33942        // byte-sequence appears verbatim in the JSON — a future
33943        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
33944        // verbatim-field-name flip at the derive attribute (any of
33945        // which would silently break every downstream JSON consumer
33946        // that reaches for one of the five consts via
33947        // `Value::get(...)` — the future M4 per-edge `:politicas`
33948        // overlay projection onto Cilium `L7Rules` and Gateway API
33949        // `HTTPRoute` backend timeouts, the future
33950        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
33951        // admission-time mesh-policy cross-check, the future
33952        // `feira lint` per-`:politicas` bound-check gate) surfaces here
33953        // as a build-time test failure at `aplicacao.rs`, not as an
33954        // apply-time `.get(<stale-canonical-const>)` returning `None`
33955        // far from the derive-attr drift's commit. Peer with the
33956        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
33957        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
33958        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
33959        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
33960        // atom axes — same discipline every M3 sibling lift
33961        // established, extended here to the singleton `:politicas`
33962        // mesh-slot atom axis, closing the last M3 typed-struct
33963        // top-level `#[serde(rename_all = "camelCase")]` axis on the
33964        // Aplicacao surface without a lifted serde-key peer.
33965        let p = MeshPolicy {
33966            timeout: Some(Duration::from_secs(30)),
33967            retries: Some(3),
33968            circuit_breaker: Some(CircuitBreaker {
33969                max_failures: 5,
33970                window: Duration::from_secs(60),
33971            }),
33972            mtls_required: Some(true),
33973            rate_limit: Some(RateLimit {
33974                rate: 100,
33975                window: Duration::from_secs(1),
33976            }),
33977        };
33978        let json = serde_json::to_string(&p).unwrap();
33979        for key in [
33980            crate::POLITICAS_KEY_TIMEOUT,
33981            crate::POLITICAS_KEY_RETRIES,
33982            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
33983            crate::POLITICAS_KEY_MTLS_REQUIRED,
33984            crate::POLITICAS_KEY_RATE_LIMIT,
33985        ] {
33986            let quoted = format!("\"{key}\"");
33987            assert!(
33988                json.contains(&quoted),
33989                "serialized MeshPolicy must carry the lifted \
33990                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
33991                 JSON emission (got: {json})",
33992            );
33993        }
33994    }
33995
33996    #[test]
33997    fn politicas_key_consts_are_pairwise_distinct() {
33998        // Cross-axis drift-detection pin: a future collapse of the five
33999        // canonical [`MeshPolicy`] singleton byte-strings onto the same
34000        // value (e.g. an accidental copy-paste flip of
34001        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
34002        // would silently reroute every downstream probe on one axis
34003        // onto the sibling axis's overlay entry and pass every
34004        // propagation-probe test that expected only the stale axis's
34005        // value — the M4 per-edge `:politicas` overlay projection would
34006        // read the retry-count string where the timeout duration was
34007        // expected (or vice versa), the CR materializer's admission
34008        // cross-check would compare the wrong pair of values, and the
34009        // resulting mesh reconciler would either bind the wrong axis
34010        // or reject the resource at reconcile far from the rebrand
34011        // commit's source. Peer of the sibling four-way distinct pin
34012        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
34013        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
34014        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
34015        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
34016        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
34017        let all = [
34018            crate::POLITICAS_KEY_TIMEOUT,
34019            crate::POLITICAS_KEY_RETRIES,
34020            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
34021            crate::POLITICAS_KEY_MTLS_REQUIRED,
34022            crate::POLITICAS_KEY_RATE_LIMIT,
34023        ];
34024        for (i, a) in all.iter().enumerate() {
34025            for b in all.iter().skip(i + 1) {
34026                assert_ne!(
34027                    a, b,
34028                    "POLITICAS_KEY_* consts must be pairwise-distinct \
34029                     canonical byte-sequences — got `{a}` == `{b}`",
34030                );
34031            }
34032        }
34033    }
34034
34035    #[test]
34036    fn politicas_key_consts_are_lower_camel_case_shape() {
34037        // Shape-pin: every `POLITICAS_KEY_*` const must be a
34038        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
34039        // `kebab-case` hyphens, no leading colon, no `PascalCase`
34040        // leading capital, no whitespace / dots) — the canonical shape
34041        // the `#[serde(rename_all = "camelCase")]` derive produces on
34042        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
34043        // at the derive surfaces both here (this test fails on the
34044        // stale-constant shape) and at
34045        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
34046        // (that test fails on the mismatch between const and derive).
34047        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
34048        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
34049        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
34050        // (ca463a4) on the sibling M3 typed-struct axes.
34051        for key in [
34052            crate::POLITICAS_KEY_TIMEOUT,
34053            crate::POLITICAS_KEY_RETRIES,
34054            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
34055            crate::POLITICAS_KEY_MTLS_REQUIRED,
34056            crate::POLITICAS_KEY_RATE_LIMIT,
34057        ] {
34058            assert!(
34059                !key.is_empty(),
34060                "POLITICAS_KEY_* must be non-empty (got {key:?})"
34061            );
34062            let first = key.chars().next().unwrap();
34063            assert!(
34064                first.is_ascii_lowercase(),
34065                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
34066                 byte (got {key:?}, leads with {first:?})",
34067            );
34068            assert!(
34069                key.chars().all(|c| c.is_ascii_alphanumeric()),
34070                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
34071                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
34072            );
34073        }
34074    }
34075
34076    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
34077
34078    #[test]
34079    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
34080        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
34081        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
34082        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
34083        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
34084        // [`CircuitBreaker`] emits inside the
34085        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
34086        // two axes (`max_failures` → `maxFailures`) is a non-trivial
34087        // camelCase transform — the derive-attribute is load-bearing on
34088        // that axis, unlike the sibling `window` field where the derive
34089        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
34090        // pin that each canonical byte-sequence appears verbatim in the
34091        // JSON — a future accidental `rename_all = "snake_case"` /
34092        // `"kebab-case"` / verbatim-field-name flip at the derive
34093        // attribute (any of which would silently break every downstream
34094        // JSON consumer that reaches for one of the two consts via
34095        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
34096        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
34097        // per-edge `:politicas` overlay projection onto the mesh's
34098        // per-backend consecutive-failure-counter tripping threshold, the
34099        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
34100        // admission-time breaker cross-check, the future `feira lint`
34101        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
34102        // here as a build-time test failure at `aplicacao.rs`, not as an
34103        // apply-time `.get(<stale-canonical-const>)` returning `None`
34104        // far from the derive-attr drift's commit. Peer with the sibling
34105        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
34106        // (b55cca7) parent-axis pin — that test pins the outer
34107        // sub-block key the derive on [`MeshPolicy`] emits, this test
34108        // pins the inner keys the derive on the payload type emits, so
34109        // the two together lock the whole [`MeshPolicy`] breaker-tuning
34110        // shape end-to-end at build time.
34111        let cb = CircuitBreaker {
34112            max_failures: 5,
34113            window: Duration::from_secs(60),
34114        };
34115        let json = serde_json::to_string(&cb).unwrap();
34116        for key in [
34117            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
34118            crate::CIRCUIT_BREAKER_KEY_WINDOW,
34119        ] {
34120            let quoted = format!("\"{key}\"");
34121            assert!(
34122                json.contains(&quoted),
34123                "serialized CircuitBreaker must carry the lifted \
34124                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
34125                 in the JSON emission (got: {json})",
34126            );
34127        }
34128    }
34129
34130    #[test]
34131    fn circuit_breaker_key_consts_are_pairwise_distinct() {
34132        // Cross-axis drift-detection pin: a future collapse of the two
34133        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
34134        // same value (e.g. an accidental copy-paste flip of
34135        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
34136        // `"maxFailures"`) would silently reroute every downstream
34137        // probe on one axis onto the sibling axis's overlay entry and
34138        // pass every propagation-probe test that expected only the
34139        // stale axis's value — the M4 per-edge `:politicas` overlay
34140        // projection would read the failure-count where the window
34141        // duration was expected (or vice versa), the CR materializer's
34142        // admission cross-check would compare the wrong pair of values,
34143        // and the resulting mesh reconciler would either bind the wrong
34144        // axis or reject the resource at reconcile far from the rebrand
34145        // commit's source. Peer of the sibling five-way distinct pin on
34146        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
34147        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
34148        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
34149        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
34150        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
34151        let all = [
34152            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
34153            crate::CIRCUIT_BREAKER_KEY_WINDOW,
34154        ];
34155        for (i, a) in all.iter().enumerate() {
34156            for b in all.iter().skip(i + 1) {
34157                assert_ne!(
34158                    a, b,
34159                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
34160                     canonical byte-sequences — got `{a}` == `{b}`",
34161                );
34162            }
34163        }
34164    }
34165
34166    #[test]
34167    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
34168        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
34169        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
34170        // `kebab-case` hyphens, no leading colon, no `PascalCase`
34171        // leading capital, no whitespace / dots) — the canonical shape
34172        // the `#[serde(rename_all = "camelCase")]` derive produces on
34173        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
34174        // at the derive surfaces both here (this test fails on the
34175        // stale-constant shape) and at
34176        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
34177        // (that test fails on the mismatch between const and derive).
34178        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
34179        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
34180        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
34181        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
34182        // (ca463a4) on the sibling M3 typed-struct axes.
34183        for key in [
34184            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
34185            crate::CIRCUIT_BREAKER_KEY_WINDOW,
34186        ] {
34187            assert!(
34188                !key.is_empty(),
34189                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
34190            );
34191            let first = key.chars().next().unwrap();
34192            assert!(
34193                first.is_ascii_lowercase(),
34194                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
34195                 byte (got {key:?}, leads with {first:?})",
34196            );
34197            assert!(
34198                key.chars().all(|c| c.is_ascii_alphanumeric()),
34199                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
34200                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
34201            );
34202        }
34203    }
34204
34205    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
34206
34207    #[test]
34208    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
34209        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
34210        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
34211        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
34212        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
34213        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
34214        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
34215        // [`Placement`] emits. One of the four axes (`shard_key` →
34216        // `shardKey`) is a non-trivial camelCase transform — the
34217        // derive-attribute is load-bearing on that axis, unlike the
34218        // sibling `estrategia` / `clusters` / `affinity` axes whose
34219        // source-side field names carry no `_` and where the derive is a
34220        // no-op. Serialize a fully-populated [`Placement`] (both
34221        // `Option`-carrying axes `Some(_)` so
34222        // `skip_serializing_if = "Option::is_none"` fires on neither of
34223        // the two optional slots) and pin that each canonical
34224        // byte-sequence appears verbatim in the JSON — a future
34225        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
34226        // verbatim-field-name flip at the derive attribute (any of which
34227        // would silently break every downstream consumer that reaches
34228        // for one of the four consts via
34229        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
34230        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
34231        // aggregator's per-cluster fanout filter keying off
34232        // `placement.clusters`, the M3 shard-pool dispatch materializer
34233        // keying off `placement.shardKey`, the M3 Adaptive compression
34234        // pass weighting off `placement.affinity`, every downstream
34235        // dispatcher branching on `placement.estrategia`, the future
34236        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
34237        // admission-time placement cross-check, the future `feira lint`
34238        // per-`:placement` bound-check gate) surfaces here as a
34239        // build-time test failure at `aplicacao.rs`, not as an
34240        // apply-time `.get(<stale-canonical-const>)` returning `None`
34241        // far from the derive-attr drift's commit. Peer with the sibling
34242        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
34243        // (b55cca7),
34244        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
34245        // (468e959),
34246        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
34247        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
34248        // (ca463a4), and
34249        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
34250        // pins on the M3 collection-slot / singleton-slot atom axes —
34251        // closes the last M3 typed-struct top-level
34252        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
34253        // surface without a drift-detection pin.
34254        let p = Placement {
34255            estrategia: PlacementStrategy::Sharded,
34256            clusters: vec!["rio".into(), "mar".into()],
34257            affinity: Some("data-locality".into()),
34258            shard_key: Some("$tenantId".into()),
34259        };
34260        let json = serde_json::to_string(&p).unwrap();
34261        for key in [
34262            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
34263            crate::M3_PLACEMENT_KEY_CLUSTERS,
34264            crate::M3_PLACEMENT_KEY_AFFINITY,
34265            crate::M3_PLACEMENT_KEY_SHARD_KEY,
34266        ] {
34267            let quoted = format!("\"{key}\"");
34268            assert!(
34269                json.contains(&quoted),
34270                "serialized Placement must carry the lifted \
34271                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
34272                 the JSON emission (got: {json})",
34273            );
34274        }
34275    }
34276
34277    #[test]
34278    fn m3_placement_key_consts_are_pairwise_distinct() {
34279        // Cross-axis drift-detection pin: a future collapse of the four
34280        // canonical [`Placement`] sub-block byte-strings onto the same
34281        // value (e.g. an accidental copy-paste flip of
34282        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
34283        // `"affinity"`) would silently reroute every downstream probe on
34284        // one axis onto the sibling axis's overlay entry and pass every
34285        // propagation-probe test that expected only the stale axis's
34286        // value — the M3 shard-pool dispatch materializer would read the
34287        // affinity placement-hint where the shard-selection template was
34288        // expected (or vice versa), the M3 Adaptive compression pass's
34289        // cross-check would compare the wrong pair of values, and the
34290        // resulting placement engine would either bind the wrong axis or
34291        // reject the resource at reconcile far from the rebrand commit's
34292        // source. Peer of the sibling two-way distinct pin on the
34293        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
34294        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
34295        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
34296        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
34297        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
34298        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
34299        let all = [
34300            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
34301            crate::M3_PLACEMENT_KEY_CLUSTERS,
34302            crate::M3_PLACEMENT_KEY_AFFINITY,
34303            crate::M3_PLACEMENT_KEY_SHARD_KEY,
34304        ];
34305        for (i, a) in all.iter().enumerate() {
34306            for b in all.iter().skip(i + 1) {
34307                assert_ne!(
34308                    a, b,
34309                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
34310                     canonical byte-sequences — got `{a}` == `{b}`",
34311                );
34312            }
34313        }
34314    }
34315
34316    #[test]
34317    fn m3_placement_key_consts_are_lower_camel_case_shape() {
34318        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
34319        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
34320        // `kebab-case` hyphens, no leading colon, no `PascalCase`
34321        // leading capital, no whitespace / dots) — the canonical shape
34322        // the `#[serde(rename_all = "camelCase")]` derive produces on
34323        // [`Placement`]. A future flip to a non-camelCase attribute at
34324        // the derive surfaces both here (this test fails on the stale-
34325        // constant shape) and at
34326        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
34327        // (that test fails on the mismatch between const and derive).
34328        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
34329        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
34330        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
34331        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
34332        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
34333        // (ca463a4) on the sibling M3 typed-struct axes.
34334        for key in [
34335            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
34336            crate::M3_PLACEMENT_KEY_CLUSTERS,
34337            crate::M3_PLACEMENT_KEY_AFFINITY,
34338            crate::M3_PLACEMENT_KEY_SHARD_KEY,
34339        ] {
34340            assert!(
34341                !key.is_empty(),
34342                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
34343            );
34344            let first = key.chars().next().unwrap();
34345            assert!(
34346                first.is_ascii_lowercase(),
34347                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
34348                 byte (got {key:?}, leads with {first:?})",
34349            );
34350            assert!(
34351                key.chars().all(|c| c.is_ascii_alphanumeric()),
34352                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
34353                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
34354            );
34355        }
34356    }
34357
34358    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
34359    //    destination-facing L4 port resolver every per-Aplicacao renderer
34360    //    reaching for a per-destination Servico TCP port axis routes
34361    //    through. The four pin tests below fix the four-way accept-set
34362    //    the resolver must always honor: (:entrada-para-matches,
34363    //    :entrada-para-mismatches, :entrada-none-so-fallback,
34364    //    :entrada-port-non-default-honored) — drift on any arm surfaces
34365    //    at caixa-core build time rather than at cluster-apply time.
34366
34367    #[test]
34368    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
34369        // The typed `:entrada` block's `:para "cart"` matches the
34370        // queried destination, so the resolver returns the author-
34371        // declared `:port` scalar verbatim — the canonical "the
34372        // destination Servico IS the ingress apex, honor the typed
34373        // listener port" arm of the port-resolution dispatch.
34374        let mut spec = three_member_spec();
34375        if let Some(e) = spec.entrada.as_mut() {
34376            e.para = "cart".into();
34377            e.port = 9090;
34378        }
34379        assert_eq!(
34380            spec.port_for_destination("cart"),
34381            9090,
34382            "port_for_destination(entrada.para) must return entrada.port \
34383             verbatim, not the DEFAULT_SERVICO_PORT fallback"
34384        );
34385    }
34386
34387    #[test]
34388    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
34389        // The typed `:entrada` block names `:para "cart"`, but the
34390        // queried destination is `"payment"` — a Servico that
34391        // participates in the mesh graph but is not the ingress apex.
34392        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
34393        // canonical port floor, closing the "non-apex destination reads
34394        // the substrate default" arm. Same fixture the peer
34395        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
34396        // pin at caixa-mesh exercises through the CNP emit-side path;
34397        // this pin exercises the shared underlying resolver directly.
34398        let spec = three_member_spec();
34399        assert_eq!(
34400            spec.port_for_destination("payment"),
34401            DEFAULT_SERVICO_PORT,
34402            "port_for_destination(non-apex-destination) must route \
34403             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
34404        );
34405    }
34406
34407    #[test]
34408    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
34409        // Internal-only Aplicacao — no `:entrada` block declared. Every
34410        // per-destination port query falls back to the lifted
34411        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
34412        // the Aplicacao surface admits `:entrada None` (internal mesh
34413        // with no external gateway); every downstream renderer's per-
34414        // destination port axis must still resolve to a well-defined
34415        // scalar even without an ingress apex.
34416        let mut spec = three_member_spec();
34417        spec.entrada = None;
34418        assert_eq!(
34419            spec.port_for_destination("cart"),
34420            DEFAULT_SERVICO_PORT,
34421            "port_for_destination on an internal-only Aplicacao must \
34422             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
34423             every destination"
34424        );
34425        assert_eq!(
34426            spec.port_for_destination("payment"),
34427            DEFAULT_SERVICO_PORT,
34428            "port_for_destination on an internal-only Aplicacao must \
34429             fall back uniformly across every destination — the fallback \
34430             is not entrada-shape-conditional"
34431        );
34432    }
34433
34434    #[test]
34435    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
34436        // Structural pin against a hypothetical future refactor that
34437        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
34438        // the resolver (a "normalize to the default when the author's
34439        // port matches the substrate default" collapse) — that would
34440        // break renderer sites that carry meaning on the emitted port
34441        // value beyond bare equality (a future per-cluster listener-
34442        // audit that keys off the author-declared port, not the
34443        // resolved-with-fallback port). Pin that a non-default
34444        // entrada.port is returned verbatim so drift here surfaces at
34445        // caixa-core build time.
34446        let mut spec = three_member_spec();
34447        if let Some(e) = spec.entrada.as_mut() {
34448            e.para = "cart".into();
34449            e.port = 8443;
34450        }
34451        assert_ne!(
34452            8443, DEFAULT_SERVICO_PORT,
34453            "test fixture must probe a port distinct from \
34454             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
34455        );
34456        assert_eq!(
34457            spec.port_for_destination("cart"),
34458            8443,
34459            "port_for_destination(entrada.para) must return entrada.port \
34460             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
34461        );
34462    }
34463
34464    #[test]
34465    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
34466        // Apex-identity pair-invariant pin composing both substrate-
34467        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
34468        // and [`Entrada::destination`] — at the emit-side call shape
34469        // every per-Aplicacao renderer's ingress-apex L4 port reader
34470        // now takes. The invariant:
34471        //
34472        //   spec.port_for_destination(entrada.destination()) == entrada.port
34473        //
34474        // holds by construction under today's single-destination
34475        // `:entrada` slot (`destination()` returns `entrada.para`, and
34476        // the resolver's apex arm matches `para == destination` and
34477        // returns `entrada.port`), and every downstream consumer that
34478        // composes the two accessors at the ingress apex — the
34479        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
34480        // `backendRefs[0].port` emit-site path, the peer future M4 CR
34481        // materializer's admission-webhook that promotes the scalar to
34482        // a per-CR override overlay, every future per-Aplicacao snapshot
34483        // renderer's apex-facing L4 port reader — reaches through the
34484        // same composition. Pin the identity across four permutations
34485        // (`:para` × `:port` including a non-default port to exercise
34486        // the honor-verbatim arm and a non-cart `:para` to exercise
34487        // destination-agnostic identity) so a future refactor that
34488        // silently split either accessor's apex behavior surfaces at
34489        // caixa-core build time — a subtle `destination()` renaming
34490        // that returned `entrada.host.as_str()` instead of
34491        // `entrada.para.as_str()` would blow this pin loudly, closing
34492        // the last quiet failure mode the two lifts admit in composition.
34493        //
34494        // Peer discipline with the sibling caixa-mesh cross-crate pin
34495        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
34496        // on the two-renderer pair-invariant axis; this pin encodes the
34497        // same two-consumer coherence rule at the substrate-primitive
34498        // level so the invariant survives even if every renderer is
34499        // deleted.
34500        for (para, port) in [
34501            ("cart", DEFAULT_SERVICO_PORT),
34502            ("cart", 8443u16),
34503            ("payment", 9090u16),
34504            ("catalog", 443u16),
34505        ] {
34506            let mut spec = three_member_spec();
34507            if let Some(e) = spec.entrada.as_mut() {
34508                e.para = para.into();
34509                e.port = port;
34510            }
34511            let expected_port = spec
34512                .entrada()
34513                .expect("three_member_spec carries a typed `:entrada` block")
34514                .port();
34515            let composed_port = {
34516                let entrada = spec.entrada().expect("entrada present");
34517                spec.port_for_destination(entrada.destination())
34518            };
34519            assert_eq!(
34520                composed_port, expected_port,
34521                "`spec.port_for_destination(entrada.destination())` must \
34522                 equal `entrada.port` under today's single-destination \
34523                 `:entrada` slot — this is the apex-identity contract \
34524                 every downstream ingress-apex L4 port reader relies on. \
34525                 Input :entrada :para: {para:?}, :entrada :port: {port}"
34526            );
34527        }
34528    }
34529
34530    #[test]
34531    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
34532        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
34533        // per-`:entrada` apex-arm membership probe must key off
34534        // [`Entrada::destination`], not the raw `.para` field access.
34535        // Structurally: setting ONLY the `:entrada :para` field to a
34536        // fresh non-cart destination on an otherwise-well-formed
34537        // Aplicacao must (1) leave `e.destination()` byte-equal to
34538        // `e.para.as_str()` (the accessor is byte-projective by
34539        // definition), and (2) cause the resolver's apex arm to fire
34540        // and return `entrada.port` at exactly that new destination
34541        // while every other destination string falls through to
34542        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
34543        // membership check. Pins against a future silent detour that
34544        // (a) re-derived the apex-arm membership probe off
34545        // `e.para == destination` in `port_for_destination` instead of
34546        // `e.destination() == destination`, silently disagreeing with
34547        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
34548        // consumers (`entrada.destination()` at
34549        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
34550        // caixa-mesh/src/lib.rs:2739) that already reach through the
34551        // accessor, (b) accessor-side introduced a per-tenant alias
34552        // arm the caller was unaware of, silently rewriting an
34553        // author-declared `:para "cart"` value to a canary-aliased
34554        // form — the raw-field-access resolver would fall through to
34555        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
34556        // while the peer emit-site consumers landed on the aliased
34557        // destination, splitting the ingress-apex L4 port at
34558        // cluster-apply time.
34559        //
34560        // Peer of the sibling
34561        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
34562        // (d0de220) composition pin on the per-`:membros` refusal-arm
34563        // axis — same "the shape-gate predicate must route through the
34564        // substrate-primitive typed dispatch" discipline extended onto
34565        // the per-`:entrada` apex-arm membership-probe axis. Closes
34566        // the last unlifted `.para` production-code read site on
34567        // `Entrada` in `caixa-core` — after this converge every
34568        // `caixa-core` `.para` field access outside the accessor's own
34569        // body and outside the `WitContract` per-`:contratos` sibling
34570        // axis is either a test-side field-setter or a doc-comment
34571        // reference.
34572        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
34573            let mut spec = three_member_spec();
34574            if let Some(e) = spec.entrada.as_mut() {
34575                e.para = para.into();
34576                e.port = port;
34577            }
34578            let e = spec
34579                .entrada
34580                .as_ref()
34581                .expect("three_member_spec carries a typed `:entrada` block");
34582            assert_eq!(
34583                e.destination(),
34584                e.para.as_str(),
34585                "Entrada::destination must byte-equal the .para field \
34586                 access — an accessor-side detour that no longer \
34587                 projects the raw field would silently split this \
34588                 drift-detection test from the port_for_destination \
34589                 apex-arm membership probe",
34590            );
34591            assert_eq!(
34592                spec.port_for_destination(para),
34593                port,
34594                "port_for_destination must key off the accessor-projected \
34595                 destination and return `entrada.port` on the apex arm — \
34596                 input :entrada :para: {para:?}, :entrada :port: {port}",
34597            );
34598            assert_eq!(
34599                spec.port_for_destination("ghost-destination-never-a-member"),
34600                DEFAULT_SERVICO_PORT,
34601                "port_for_destination must fall through to \
34602                 DEFAULT_SERVICO_PORT on a non-matching destination \
34603                 under the accessor-projected membership check — input \
34604                 :entrada :para: {para:?}, :entrada :port: {port}",
34605            );
34606        }
34607    }
34608
34609    #[test]
34610    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
34611        // The canonical per-`:politicas :rate-limit` `:rate`
34612        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
34613        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
34614        // typed `u32` verbatim, byte-equal to the raw field access
34615        // across every representative value in the accept-set — `1` (the
34616        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
34617        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
34618        // carves out on the sibling `PolicyRateLimitZero` refusal),
34619        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
34620        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
34621        // `0` (a past-the-guard sentinel that pins the accessor doesn't
34622        // perform a silent bounds-collapse into `1` on the zero arm —
34623        // validate rejects zero but the accessor must ship the raw slot
34624        // verbatim so a validate-time gate regression surfaces at the
34625        // emit boundary rather than being silently absorbed), `u32::MAX`
34626        // (a past-the-guard sentinel that pins the accessor doesn't
34627        // perform a silent bounds-collapse through
34628        // `POLICY_RATE_LIMIT_MAX` at the return path).
34629        //
34630        // First sub-struct required-scalar accessor pin on the
34631        // `RateLimit` axis — sibling in shape to the peer
34632        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
34633        // required-`u32` accessor pin on the peer per-sub-struct
34634        // required-axis. Pins against a future silent detour that
34635        // re-derived the token capacity from a peer axis (an accidental
34636        // `self.window.as_secs() as u32` collapse that read the
34637        // rate-limit window duration as a token count), a `0 → 1`
34638        // cluster-default projection (which would silently absorb the
34639        // `PolicyRateLimitZero` refusal case at the accessor boundary),
34640        // or a bounds-collapsing accessor that clamped the return
34641        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
34642        // gate owns the bounds; the accessor must ship the raw slot
34643        // verbatim).
34644        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
34645            let rl = RateLimit {
34646                rate,
34647                window: Duration::from_secs(1),
34648            };
34649            assert_eq!(
34650                rl.rate(),
34651                rate,
34652                "RateLimit::rate must return :politicas :rate-limit :rate \
34653                 verbatim (got {}, expected {rate})",
34654                rl.rate(),
34655            );
34656            assert_eq!(
34657                rl.rate(),
34658                rl.rate,
34659                "RateLimit::rate must byte-equal the raw .rate field \
34660                 access across every value in the u32 accept-set",
34661            );
34662        }
34663    }
34664
34665    #[test]
34666    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
34667        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34668        // `:rate-limit :rate` zero-floor arm must key off
34669        // [`RateLimit::rate`], not the raw `.rate` field access.
34670        // Structurally: a `RateLimit { rate: 0, window:
34671        // Duration::from_secs(1) }` embedded in a `:politicas
34672        // :rate-limit` slot must surface the `PolicyRateLimitZero`
34673        // refusal exactly, and a `RateLimit { rate: 1, window:
34674        // Duration::from_secs(1) }` (the lower boundary of the
34675        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
34676        // The pair jointly pins the accessor + validate-gate composition:
34677        // any future silent detour that had the accessor return a fresh
34678        // `1` on the zero arm (a `.rate().max(1)` collapse) would
34679        // silently absorb the `PolicyRateLimitZero` refusal at the
34680        // accessor boundary and the validate gate would accept a
34681        // struct-literal `RateLimit { rate: 0, .. }` — the composition
34682        // pin catches that at caixa-core build time.
34683        //
34684        // Peer of the sibling per-`CircuitBreaker`
34685        // [`CircuitBreaker::max_failures`] (3a74062) /
34686        // [`CircuitBreaker::window`] (373957f) accessor-composition
34687        // pins on the peer required-scalar axes — same "the validate /
34688        // shape-gate predicate must route through the substrate-primitive
34689        // typed dispatch" discipline extended onto the peer
34690        // per-`RateLimit` required-`u32` composition axis.
34691        let mut spec = three_member_spec();
34692        spec.politicas = MeshPolicy {
34693            rate_limit: Some(RateLimit {
34694                rate: 0,
34695                window: Duration::from_secs(1),
34696            }),
34697            ..MeshPolicy::default()
34698        };
34699        assert!(
34700            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
34701            "validate_politicas must reject rate == 0 with \
34702             PolicyRateLimitZero — the accessor and the validate gate \
34703             must route through the same substrate-primitive typed \
34704             dispatch on the :rate zero-floor arm",
34705        );
34706        spec.politicas = MeshPolicy {
34707            rate_limit: Some(RateLimit {
34708                rate: 1,
34709                window: Duration::from_secs(1),
34710            }),
34711            ..MeshPolicy::default()
34712        };
34713        assert!(
34714            spec.validate().is_ok(),
34715            "validate_politicas must accept rate == 1 (the lower \
34716             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
34717        );
34718    }
34719
34720    #[test]
34721    fn rate_limit_rate_projects_u32_by_copy() {
34722        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
34723        // `u32` is `Copy` and the accessor must return by value, not by
34724        // reference. Peer of the sibling per-`CircuitBreaker`
34725        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
34726        // peer required-scalar `:max-failures` axis, extended onto the
34727        // peer per-`RateLimit` required-`u32` copy-invariant shape —
34728        // the accessor's returned `u32` must outlive `&self` (multiple
34729        // calls must return equal values from a dropped-`&self` copy,
34730        // since the returned scalar carries no borrow), and calling the
34731        // accessor twice on the same RateLimit must yield the same
34732        // `u32` verbatim (idempotent, no side effects on `&self`).
34733        //
34734        // Pins against a future silent detour that returned `&u32`
34735        // (which would type-check but silently break every downstream
34736        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
34737        // first parameter is `u32`, and `&u32` would fold to a detached
34738        // copy at the call site with a `*` deref the sibling accessors
34739        // don't need), an accidental `.rate.wrapping_add(0)` detour that
34740        // returned a fresh copy through an arithmetic no-op (breaking a
34741        // future `const fn` regression), or a one-arm-only accessor
34742        // that returned a saturating value on some sentinel input
34743        // (breaking the pass-through invariant the sibling required-
34744        // scalar accessors carry).
34745        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
34746            let rl = RateLimit {
34747                rate,
34748                window: Duration::from_secs(1),
34749            };
34750            let first = rl.rate();
34751            let second = rl.rate();
34752            assert_eq!(
34753                first, second,
34754                "RateLimit::rate must be idempotent — two successive \
34755                 calls on the same &self must return the same u32",
34756            );
34757            assert_eq!(
34758                first, rate,
34759                "RateLimit::rate must return :politicas :rate-limit :rate \
34760                 verbatim by copy — got {first}, expected {rate}",
34761            );
34762        }
34763    }
34764
34765    #[test]
34766    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
34767        // The canonical per-`:politicas :rate-limit` `:window`
34768        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
34769        // pin: [`RateLimit::window`] must return the
34770        // `:politicas :rate-limit :window` typed `Duration` verbatim,
34771        // byte-equal to the raw field access across every
34772        // representative value in the accept-set — `Duration::from_secs(1)`
34773        // (the `"s"` canonical window, the lower row of
34774        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
34775        // [`AplicacaoSpec::validate_politicas`] gate accepts via
34776        // [`is_canonical_rate_limit_window`]),
34777        // `Duration::from_secs(60)` (the `"m"` canonical window, the
34778        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
34779        // window, the upper row), `Duration::ZERO` (a past-the-guard
34780        // sentinel that pins the accessor doesn't perform a silent
34781        // bounds-collapse into `Duration::from_secs(1)` on the zero
34782        // arm — validate rejects an off-set window through
34783        // `PolicyRateLimitWindowNotCanonical` but the accessor must
34784        // ship the raw slot verbatim so a validate-time gate
34785        // regression surfaces at the emit boundary rather than being
34786        // silently absorbed), `Duration::from_millis(500)` (a
34787        // sub-canonical past-the-guard sentinel that pins the accessor
34788        // doesn't silently normalize a non-canonical fractional
34789        // magnitude onto the nearest canonical row).
34790        //
34791        // Second sub-struct required-scalar accessor pin on the
34792        // `RateLimit` axis — sibling in shape to the just-landed
34793        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
34794        // accessor pin on the peer per-sub-struct required-axis,
34795        // extended onto the per-`RateLimit` required-`Duration` axis.
34796        // Pins against a future silent detour that re-derived the
34797        // refill period from a peer axis (an accidental
34798        // `Duration::from_secs(self.rate as u64)` collapse that read
34799        // the rate-limit token capacity as a refill-interval
34800        // duration), a `Duration::ZERO → Duration::from_secs(1)`
34801        // canonical-default projection (which would silently absorb
34802        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
34803        // accessor boundary), or a canonical-set-collapsing accessor
34804        // that clamped the return through [`rate_limit_window_unit`]
34805        // (the `AplicacaoSpec::validate` gate owns the canonical-set
34806        // membership; the accessor must ship the raw slot verbatim).
34807        for window in [
34808            Duration::from_secs(1),
34809            Duration::from_secs(60),
34810            Duration::from_secs(3600),
34811            Duration::ZERO,
34812            Duration::from_millis(500),
34813        ] {
34814            let rl = RateLimit { rate: 100, window };
34815            assert_eq!(
34816                rl.window(),
34817                window,
34818                "RateLimit::window must return :politicas :rate-limit :window \
34819                 verbatim (got {:?}, expected {window:?})",
34820                rl.window(),
34821            );
34822            assert_eq!(
34823                rl.window(),
34824                rl.window,
34825                "RateLimit::window must byte-equal the raw .window field \
34826                 access across every value in the Duration accept-set",
34827            );
34828        }
34829    }
34830
34831    #[test]
34832    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
34833        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34834        // `:rate-limit :window` canonical-set arm must key off
34835        // [`RateLimit::window`], not the raw `.window` field access.
34836        // Structurally: a `RateLimit { window: Duration::from_millis(500),
34837        // .. }` embedded in a `:politicas :rate-limit` slot must
34838        // surface the `PolicyRateLimitWindowNotCanonical` refusal
34839        // exactly (with the sub-canonical `Duration::from_millis(500)`
34840        // magnitude carried through verbatim), and a `RateLimit
34841        // { window: Duration::from_secs(1), .. }` (the lower row of
34842        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
34843        // The pair jointly pins the accessor + validate-gate
34844        // composition: any future silent detour that had the accessor
34845        // normalize the off-set window to the nearest canonical row
34846        // (a `.window().max(Duration::from_secs(1))` collapse, or a
34847        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
34848        // collapse) would silently absorb the
34849        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
34850        // boundary — including a drift in the error's `window` payload
34851        // (the emit-side diagnostic reader keys off the offending
34852        // magnitude verbatim, so a normalization at the accessor
34853        // boundary would silently pin the wrong magnitude in the
34854        // refusal). The composition pin catches that at caixa-core
34855        // build time.
34856        //
34857        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
34858        // (7f81a60) accessor-composition pin on the peer required-
34859        // scalar `:rate` axis — same "the validate / shape-gate
34860        // predicate must route through the substrate-primitive typed
34861        // dispatch, and the error payload must project through the
34862        // same accessor" discipline extended onto the peer
34863        // per-`RateLimit` required-`Duration` composition axis.
34864        let mut spec = three_member_spec();
34865        spec.politicas = MeshPolicy {
34866            rate_limit: Some(RateLimit {
34867                rate: 100,
34868                window: Duration::from_millis(500),
34869            }),
34870            ..MeshPolicy::default()
34871        };
34872        match spec.validate() {
34873            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
34874                assert_eq!(
34875                    window,
34876                    Duration::from_millis(500),
34877                    "PolicyRateLimitWindowNotCanonical must carry the \
34878                     offending :window magnitude verbatim through the \
34879                     accessor — got {window:?}, expected 500ms",
34880                );
34881            }
34882            other => panic!(
34883                "validate_politicas must reject non-canonical :window \
34884                 with PolicyRateLimitWindowNotCanonical — the accessor \
34885                 and the validate gate must route through the same \
34886                 substrate-primitive typed dispatch on the :window \
34887                 canonical-set arm; got {other:?}",
34888            ),
34889        }
34890        spec.politicas = MeshPolicy {
34891            rate_limit: Some(RateLimit {
34892                rate: 100,
34893                window: Duration::from_secs(1),
34894            }),
34895            ..MeshPolicy::default()
34896        };
34897        assert!(
34898            spec.validate().is_ok(),
34899            "validate_politicas must accept window == Duration::from_secs(1) \
34900             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
34901        );
34902    }
34903
34904    #[test]
34905    fn rate_limit_window_projects_duration_by_copy() {
34906        // The by-copy pin: [`RateLimit::window`] returns `Duration`
34907        // by copy — `Duration` is `Copy` and the accessor must return
34908        // by value, not by reference. Peer of the sibling per-`RateLimit`
34909        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
34910        // required-scalar `:rate` axis, extended onto the peer
34911        // per-`RateLimit` required-`Duration` copy-invariant shape —
34912        // the accessor's returned `Duration` must outlive `&self`
34913        // (multiple calls must return equal values from a
34914        // dropped-`&self` copy, since the returned scalar carries no
34915        // borrow), and calling the accessor twice on the same
34916        // RateLimit must yield the same `Duration` verbatim
34917        // (idempotent, no side effects on `&self`).
34918        //
34919        // Pins against a future silent detour that returned
34920        // `&Duration` (which would type-check but silently break every
34921        // downstream `Duration`-by-value consumer —
34922        // [`is_canonical_rate_limit_window`]'s first parameter is
34923        // `Duration`, and `&Duration` would fold to a detached copy at
34924        // the call site with a `*` deref the sibling accessors don't
34925        // need), an accidental `.window + Duration::ZERO` detour that
34926        // returned a fresh copy through an arithmetic no-op (breaking
34927        // a future `const fn` regression), or a one-arm-only accessor
34928        // that returned a canonical fallback on some sentinel input
34929        // (breaking the pass-through invariant the sibling required-
34930        // scalar accessors carry).
34931        for window in [
34932            Duration::from_secs(1),
34933            Duration::from_secs(60),
34934            Duration::from_secs(3600),
34935            Duration::ZERO,
34936            Duration::from_millis(500),
34937        ] {
34938            let rl = RateLimit { rate: 100, window };
34939            let first = rl.window();
34940            let second = rl.window();
34941            assert_eq!(
34942                first, second,
34943                "RateLimit::window must be idempotent — two successive \
34944                 calls on the same &self must return the same Duration",
34945            );
34946            assert_eq!(
34947                first, window,
34948                "RateLimit::window must return :politicas :rate-limit :window \
34949                 verbatim by copy — got {first:?}, expected {window:?}",
34950            );
34951        }
34952    }
34953
34954    #[test]
34955    fn placement_estrategia_default_pins_m3_canonical_value() {
34956        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
34957        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
34958        // active-active-across-every-named-cluster arm, the closest
34959        // canonical M3 production reference the substrate carries and
34960        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
34961        // for every un-`:placement`-declared Aplicacao. Pinning the arm
34962        // here surfaces a future rebrand of the M3-canonical
34963        // distribution default (a widening to `Sharded` once the
34964        // substrate discovers hash-keyed distribution as the more
34965        // common production shape, a tightening to `SingleNode` for
34966        // stateful Erlang/OTP distributed-app-takeover semantics
34967        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
34968        // operator pins through a future `:placement-overrides` slot)
34969        // as a deliberate test edit, not a silent contract migration.
34970        // Peer of the sibling M2 per-supervisor value pins
34971        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
34972        // /
34973        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
34974        // extended onto the M3 mesh-primitive-defining `:placement
34975        // :estrategia` axis.
34976        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
34977    }
34978
34979    #[test]
34980    fn placement_strategy_default_routes_through_lifted_default() {
34981        // Composition pin: the [`Default for PlacementStrategy`] impl's
34982        // return arm must route through the substrate-canonical
34983        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
34984        // a raw `Self::Replicated` arm. Prior to the lift the impl
34985        // carried an inline `Self::Replicated` arm with no compile-time
34986        // link back to the shared M3-canonical `Replicated` arm the
34987        // paired [`Default for Placement`] impl's struct-literal
34988        // `estrategia` field, the serde-side `#[serde(default)]` on
34989        // [`Placement::estrategia`] that resolves an author-omitted
34990        // wire-form `:placement :estrategia` scalar through the impl,
34991        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
34992        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
34993        // routes through [`Placement::default`] which routes through the
34994        // strategy default) all key off — so a future rebrand of the
34995        // M3-canonical distribution default would have had to be threaded
34996        // through the `Default` impl and the three peer routes in
34997        // lockstep or the four consumers would silently split. Byte-
34998        // parity against the lifted constant closes the split. Peer of
34999        // the sibling
35000        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
35001        // /
35002        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
35003        // composition pins on the M2 per-supervisor axes.
35004        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
35005    }
35006
35007    #[test]
35008    fn placement_default_estrategia_routes_through_lifted_default() {
35009        // Composition pin: the [`Default for Placement`] impl's
35010        // struct-literal `estrategia` field must route through the
35011        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
35012        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
35013        // impl that the sibling
35014        // `placement_strategy_default_routes_through_lifted_default` pin
35015        // already routes onto the constant). Structurally: every
35016        // `Placement::default()` call must yield an `estrategia` field
35017        // byte-equal to the lifted constant so the two paired defaults —
35018        // the [`Default for PlacementStrategy`] impl arm and the
35019        // struct-literal default arm here — cannot silently split on any
35020        // future M3-canonical distribution-default rebrand. Peer of the
35021        // sibling M2
35022        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
35023        // byte-parity pin on the [`Default for SupervisorSpec`]
35024        // struct-literal `estrategia` field extended onto the M3
35025        // mesh-primitive-defining slot family.
35026        assert_eq!(
35027            Placement::default().estrategia,
35028            PLACEMENT_ESTRATEGIA_DEFAULT,
35029        );
35030    }
35031
35032    #[test]
35033    fn placement_serde_default_estrategia_routes_through_lifted_default() {
35034        // Composition pin: the serde-side `#[serde(default)]` on
35035        // [`Placement::estrategia`] — the wire-format author-omitted
35036        // `:placement :estrategia` arm — must resolve onto the substrate-
35037        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
35038        // (via the [`Default for PlacementStrategy`] impl the sibling
35039        // `placement_strategy_default_routes_through_lifted_default` pin
35040        // already routes onto the constant). Structurally: a `Placement`
35041        // deserialized from a payload that omits the `estrategia` key
35042        // must yield an `estrategia` field byte-equal to the lifted
35043        // constant, so the wire-format author-omitted arm and the
35044        // [`PlacementStrategy::default`] impl arm cannot silently split
35045        // on any future M3-canonical distribution-default rebrand. Peer
35046        // of the sibling M2
35047        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
35048        // byte-parity pin on the wire-format author-omitted `:children
35049        // :restart` scalar extended onto the M3 mesh-primitive-defining
35050        // slot family.
35051        let omitted: Placement = serde_json::from_str("{}")
35052            .expect("Placement must deserialize with the estrategia key omitted");
35053        assert_eq!(
35054            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
35055            "an author-omitted :placement :estrategia slot must degrade onto \
35056             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
35057             {:?}, expected {:?})",
35058            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
35059        );
35060    }
35061
35062    // ── contrato_target_ctors! fold pins ────────────────────────────────
35063    //
35064    // Fixture edge triple + payload-field-name label pair for every
35065    // `contrato_target_ctors!`-generated ctor pin below. Kept as
35066    // non-default `("cart", "catalog", "wasi:http/proxy")` +
35067    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
35068    // the fixture default doesn't silently pass. Peer of the sibling
35069    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
35070    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
35071    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
35072    // `missing_entry_ctor_matches_struct_literal_wrap` /
35073    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
35074    // four `LayoutError` constructor families each closed on their
35075    // sibling envelopes.
35076    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
35077        (
35078            "cart".to_string(),
35079            "catalog".to_string(),
35080            "wasi:http/proxy".to_string(),
35081            WitTarget::HTTP_FIELD_NAME,
35082        )
35083    }
35084
35085    #[test]
35086    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
35087        // Equivalence pin: the ctor produces byte-equal
35088        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
35089        // coded struct-literal on the same edge fixture, so the fold
35090        // cannot silently drift on any future field-addition /
35091        // reordering / string-conversion tweak on the variant. Peer of
35092        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
35093        // (17dd504) / the four `LayoutError` family equivalence pins.
35094        let (de, para, wit, expected) = contrato_target_ctor_fixture();
35095        let lifted = AplicacaoError::contrato_wrong_target(
35096            (de.clone(), para.clone(), wit.clone()),
35097            expected,
35098        );
35099        let struct_literal = AplicacaoError::ContratoWrongTarget {
35100            de,
35101            para,
35102            wit,
35103            expected,
35104        };
35105        assert_eq!(lifted, struct_literal);
35106    }
35107
35108    #[test]
35109    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
35110        // Equivalence pin peer of the sibling
35111        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
35112        // on the paired `ContratoMissingTarget` variant of the same
35113        // four-slot envelope shape the `contrato_target_ctors!` macro
35114        // closes.
35115        let (de, para, wit, expected) = contrato_target_ctor_fixture();
35116        let lifted = AplicacaoError::contrato_missing_target(
35117            (de.clone(), para.clone(), wit.clone()),
35118            expected,
35119        );
35120        let struct_literal = AplicacaoError::ContratoMissingTarget {
35121            de,
35122            para,
35123            wit,
35124            expected,
35125        };
35126        assert_eq!(lifted, struct_literal);
35127    }
35128
35129    #[test]
35130    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
35131        // Routing pin: the `(de, para, wit)` triple threads verbatim
35132        // onto same-named fields on both generated ctors, no wrapper-
35133        // side lowercase / trim / re-order. Sweeps a non-default triple
35134        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
35135        // wrapper-side transformation surfaces here rather than at a
35136        // downstream diagnostic-shape drift. Sibling of
35137        // `entrada_host_invalid_ctor_routes_host_through_to_string`
35138        // (17dd504) on the paired triple-carrying envelope.
35139        let edge = (
35140            "cart-svc".to_string(),
35141            "catalog-v2".to_string(),
35142            "nats:pub-sub".to_string(),
35143        );
35144        let wrong =
35145            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
35146        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
35147        let AplicacaoError::ContratoWrongTarget {
35148            de: wde,
35149            para: wpara,
35150            wit: wwit,
35151            ..
35152        } = wrong
35153        else {
35154            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
35155        };
35156        let AplicacaoError::ContratoMissingTarget {
35157            de: mde,
35158            para: mpara,
35159            wit: mwit,
35160            ..
35161        } = missing
35162        else {
35163            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
35164        };
35165        assert_eq!(wde, "cart-svc");
35166        assert_eq!(wpara, "catalog-v2");
35167        assert_eq!(wwit, "nats:pub-sub");
35168        assert_eq!(mde, "cart-svc");
35169        assert_eq!(mpara, "catalog-v2");
35170        assert_eq!(mwit, "nats:pub-sub");
35171    }
35172
35173    #[test]
35174    fn contrato_target_ctors_route_expected_through_verbatim() {
35175        // Routing pin: the `expected: &'static str` label threads
35176        // verbatim (identity, not copy-and-transform) onto the
35177        // `expected` field of both variants, so the four canonical
35178        // labels [`WitTarget::HTTP_FIELD_NAME`] /
35179        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
35180        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
35181        // pointer-equal (not merely value-equal) references — a wrapper-
35182        // side `.to_string()` / `Cow::Owned` promotion would break the
35183        // `&'static str` contract downstream consumers depend on.
35184        for label in [
35185            WitTarget::HTTP_FIELD_NAME,
35186            WitTarget::PUBSUB_FIELD_NAME,
35187            WitTarget::STORE_FIELD_NAME,
35188            WitTarget::CAPABILITY_EXPECTED,
35189        ] {
35190            let (de, para, wit, _) = contrato_target_ctor_fixture();
35191            let wrong = AplicacaoError::contrato_wrong_target(
35192                (de.clone(), para.clone(), wit.clone()),
35193                label,
35194            );
35195            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
35196            match wrong {
35197                AplicacaoError::ContratoWrongTarget { expected, .. } => {
35198                    assert!(
35199                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
35200                            && expected.len() == label.len(),
35201                        "contrato_wrong_target must thread the &'static str \
35202                         label pointer-equal onto the `expected` field \
35203                         (label = {label:?})",
35204                    );
35205                }
35206                other => panic!("expected ContratoWrongTarget, got {other:?}"),
35207            }
35208            match missing {
35209                AplicacaoError::ContratoMissingTarget { expected, .. } => {
35210                    assert!(
35211                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
35212                            && expected.len() == label.len(),
35213                        "contrato_missing_target must thread the &'static \
35214                         str label pointer-equal onto the `expected` field \
35215                         (label = {label:?})",
35216                    );
35217                }
35218                other => panic!("expected ContratoMissingTarget, got {other:?}"),
35219            }
35220        }
35221    }
35222
35223    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
35224    //
35225    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
35226    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
35227    // byte-equality mistake against the fixture default doesn't silently
35228    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
35229    // triple + expected-label envelope on
35230    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
35231    // struct_literal_wrap` (17dd504, host + reason envelope on
35232    // `entrada_host_invalid`) / the four `LayoutError` family
35233    // equivalence pins.
35234    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
35235        ("cart".to_string(), "catalog".to_string())
35236    }
35237
35238    #[test]
35239    fn empty_wit_ctor_matches_struct_literal_wrap() {
35240        // Equivalence pin: the ctor produces byte-equal
35241        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
35242        // struct-literal on the same edge pair, so the fold cannot
35243        // silently drift on any future field-addition / reordering /
35244        // string-conversion tweak on the variant. Peer of the sibling
35245        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
35246        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
35247        // (17dd504) / the four `LayoutError` family equivalence pins.
35248        let (de, para) = contrato_empty_pair_ctor_fixture();
35249        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
35250        let struct_literal = AplicacaoError::EmptyWit { de, para };
35251        assert_eq!(lifted, struct_literal);
35252    }
35253
35254    #[test]
35255    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
35256        // Equivalence pin peer of the sibling
35257        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
35258        // paired `ContratoEndpointEmpty` variant of the same two-slot
35259        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
35260        let (de, para) = contrato_empty_pair_ctor_fixture();
35261        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
35262        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
35263        assert_eq!(lifted, struct_literal);
35264    }
35265
35266    #[test]
35267    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
35268        // Equivalence pin peer of the sibling
35269        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
35270        // above on the paired `ContratoSubjectEmpty` variant of the
35271        // same two-slot envelope shape.
35272        let (de, para) = contrato_empty_pair_ctor_fixture();
35273        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
35274        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
35275        assert_eq!(lifted, struct_literal);
35276    }
35277
35278    #[test]
35279    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
35280        // Equivalence pin peer of the sibling
35281        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
35282        // above on the paired `ContratoSlotEmpty` variant of the same
35283        // two-slot envelope shape.
35284        let (de, para) = contrato_empty_pair_ctor_fixture();
35285        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
35286        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
35287        assert_eq!(lifted, struct_literal);
35288    }
35289
35290    #[test]
35291    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
35292        // Routing pin: the `(de, para)` pair threads verbatim onto
35293        // same-named fields on all four generated ctors, no wrapper-
35294        // side lowercase / trim / re-order. Sweeps a non-default pair
35295        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
35296        // transformation surfaces here rather than at a downstream
35297        // diagnostic-shape drift. Sibling of
35298        // `contrato_target_ctors_route_edge_triple_through_verbatim`
35299        // (14b81d5) on the paired triple-carrying envelope and of
35300        // `entrada_host_invalid_ctor_routes_host_through_to_string`
35301        // (17dd504) on the sibling `{ host, reason }` envelope.
35302        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
35303        let variants: [(AplicacaoError, &'static str); 4] = [
35304            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
35305            (
35306                AplicacaoError::contrato_endpoint_empty(edge.clone()),
35307                "ContratoEndpointEmpty",
35308            ),
35309            (
35310                AplicacaoError::contrato_subject_empty(edge.clone()),
35311                "ContratoSubjectEmpty",
35312            ),
35313            (
35314                AplicacaoError::contrato_slot_empty(edge.clone()),
35315                "ContratoSlotEmpty",
35316            ),
35317        ];
35318        for (built, label) in variants {
35319            let (de, para) = match built {
35320                AplicacaoError::EmptyWit { de, para }
35321                | AplicacaoError::ContratoEndpointEmpty { de, para }
35322                | AplicacaoError::ContratoSubjectEmpty { de, para }
35323                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
35324                other => panic!("expected {label} pair variant, got {other:?}"),
35325            };
35326            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
35327            assert_eq!(
35328                para, "catalog-v2",
35329                "para field on {label} must thread verbatim",
35330            );
35331        }
35332    }
35333
35334    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
35335    //
35336    // Fixture edge pair + value + reason for every
35337    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
35338    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
35339    // fixed per-axis `<val>` / reason so a byte-equality mistake against
35340    // the fixture default doesn't silently pass. Peer of the sibling
35341    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
35342    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
35343    // (14b81d5, triple + expected-label envelope on
35344    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
35345    // struct_literal_wrap` (17dd504, host + reason envelope on
35346    // `entrada_host_invalid`).
35347    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
35348        ("cart".to_string(), "catalog".to_string())
35349    }
35350
35351    #[test]
35352    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
35353        // Equivalence pin: the ctor produces byte-equal
35354        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
35355        // open-coded struct-literal on the same
35356        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
35357        // silently drift on any future field-addition / reordering /
35358        // string-conversion tweak on the variant. Peer of the sibling
35359        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
35360        // (8580068) on the paired two-slot envelope of the same
35361        // `{ de, para, ... }` prefix, and of
35362        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
35363        // (17dd504) on the sibling `{ <field>: String, reason: String }`
35364        // two-slot envelope.
35365        let (de, para) = contrato_pair_value_reason_ctor_fixture();
35366        let endpoint = "/charge";
35367        let reason = "sample reason text";
35368        let lifted =
35369            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
35370        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
35371            de,
35372            para,
35373            endpoint: endpoint.to_string(),
35374            reason: reason.to_string(),
35375        };
35376        assert_eq!(lifted, struct_literal);
35377    }
35378
35379    #[test]
35380    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
35381        // Equivalence pin peer of the sibling
35382        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
35383        // above on the paired `ContratoSubjectInvalid` variant of the
35384        // same four-slot envelope shape the
35385        // `contrato_pair_value_reason_ctors!` macro closes.
35386        let (de, para) = contrato_pair_value_reason_ctor_fixture();
35387        let subject = "checkout.events.charge.failed";
35388        let reason = "sample reason text";
35389        let lifted =
35390            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
35391        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
35392            de,
35393            para,
35394            subject: subject.to_string(),
35395            reason: reason.to_string(),
35396        };
35397        assert_eq!(lifted, struct_literal);
35398    }
35399
35400    #[test]
35401    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
35402        // Equivalence pin peer of the sibling
35403        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
35404        // above on the paired `ContratoSlotInvalid` variant of the same
35405        // four-slot envelope shape.
35406        let (de, para) = contrato_pair_value_reason_ctor_fixture();
35407        let slot = "checkout/$orderId";
35408        let reason = "sample reason text";
35409        let lifted =
35410            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
35411        let struct_literal = AplicacaoError::ContratoSlotInvalid {
35412            de,
35413            para,
35414            slot: slot.to_string(),
35415            reason: reason.to_string(),
35416        };
35417        assert_eq!(lifted, struct_literal);
35418    }
35419
35420    #[test]
35421    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
35422        // Equivalence pin peer of the sibling
35423        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
35424        // on the paired `ContratoWitInvalid` variant of the same four-
35425        // slot envelope shape the `contrato_pair_value_reason_ctors!`
35426        // macro closes. Fold pinned this test lands with the last
35427        // `{ de, para, <field>: String, reason: String }` open-coded
35428        // struct-literal inside [`WitContract::target`] rewritten to
35429        // route through the macro-generated
35430        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
35431        // between the ctor and the pre-lift struct-literal trips this
35432        // pin ahead of any downstream diagnostic-shape drift on the
35433        // `:contratos :wit` axis.
35434        let (de, para) = contrato_pair_value_reason_ctor_fixture();
35435        let wit = "wasi-http/proxy";
35436        let reason = "sample reason text";
35437        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
35438        let struct_literal = AplicacaoError::ContratoWitInvalid {
35439            de,
35440            para,
35441            wit: wit.to_string(),
35442            reason: reason.to_string(),
35443        };
35444        assert_eq!(lifted, struct_literal);
35445    }
35446
35447    #[test]
35448    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
35449        // Routing pin: the `(de, para)` pair threads verbatim onto
35450        // same-named fields on all four generated ctors, no wrapper-
35451        // side lowercase / trim / re-order. Sweeps a non-default pair
35452        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
35453        // transformation surfaces here rather than at a downstream
35454        // diagnostic-shape drift. Sibling of
35455        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
35456        // (8580068) on the paired two-slot envelope and of
35457        // `contrato_target_ctors_route_edge_triple_through_verbatim`
35458        // (14b81d5) on the paired triple-carrying envelope.
35459        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
35460        let variants: [(AplicacaoError, &'static str); 4] = [
35461            (
35462                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
35463                "ContratoEndpointInvalid",
35464            ),
35465            (
35466                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
35467                "ContratoSubjectInvalid",
35468            ),
35469            (
35470                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
35471                "ContratoSlotInvalid",
35472            ),
35473            (
35474                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
35475                "ContratoWitInvalid",
35476            ),
35477        ];
35478        for (built, label) in variants {
35479            let (de, para) = match built {
35480                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
35481                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
35482                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
35483                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
35484                other => panic!("expected {label} pair variant, got {other:?}"),
35485            };
35486            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
35487            assert_eq!(
35488                para, "catalog-v2",
35489                "para field on {label} must thread verbatim",
35490            );
35491        }
35492    }
35493
35494    #[test]
35495    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
35496        // Cross-arm invariance pin — the four ctors all route
35497        // `reason: impl Into<String>` verbatim onto their respective
35498        // typed variants through the shared
35499        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
35500        // pair (`&str` literal, `format!` output) against every ctor to
35501        // pin that no per-arm wrapper transformation drifted in against
35502        // the uniform macro-generated body. Peer of
35503        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
35504        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
35505        let edge = || ("cart".to_string(), "catalog".to_string());
35506        let via_literal = "literal reason text";
35507        let via_format = format!("{} reason text", "literal");
35508        assert_eq!(
35509            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
35510            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
35511        );
35512        assert_eq!(
35513            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
35514            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
35515        );
35516        assert_eq!(
35517            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
35518            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
35519        );
35520        assert_eq!(
35521            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
35522            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
35523        );
35524    }
35525
35526    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
35527    //
35528    // Fail-before-pass-after pins for the standalone
35529    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
35530    // (see the paired doc-block above the ctor definition) — the fold of
35531    // the last open-coded three-slot `{ de, para, endpoint: <val>
35532    // .to_string() }` struct-literal inside [`WitContract::target`]'s
35533    // HTTP-arm leading-slash gate onto one substrate primitive on the
35534    // envelope. A byte-mismatched ctor body would trip the equivalence
35535    // pin first, ahead of any downstream diagnostic-shape drift.
35536    //
35537    // Peer of the sibling standalone-ctor equivalence pins on the peer
35538    // one-off variants across caixa-core:
35539    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
35540    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
35541    // on the paired two-slot and four-slot per-`:contratos :endpoint`
35542    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
35543    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
35544    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
35545    // reason }` two- and three-slot envelopes; the
35546    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
35547    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
35548    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
35549        ("cart".to_string(), "catalog".to_string())
35550    }
35551
35552    #[test]
35553    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
35554        // Equivalence pin: the ctor produces byte-equal
35555        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
35556        // open-coded struct-literal on the same `(edge_pair, endpoint)`
35557        // pair, so the fold cannot silently drift on any future
35558        // field-addition / reordering / string-conversion tweak on the
35559        // variant. Same equivalence-pin shape as the sibling
35560        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
35561        // (8580068) on the paired two-slot envelope and
35562        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
35563        // (14e13f1) on the paired four-slot envelope of the same
35564        // `{ de, para, ... }`-prefix `:endpoint` axis.
35565        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
35566        let endpoint = "charge";
35567        let lifted =
35568            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
35569        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
35570            de,
35571            para,
35572            endpoint: endpoint.to_string(),
35573        };
35574        assert_eq!(lifted, struct_literal);
35575    }
35576
35577    #[test]
35578    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
35579        // Routing pin on the `(de, para)` axis: sweep a non-default
35580        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
35581        // lowercase / trim / re-order surfaces here rather than at a
35582        // downstream diagnostic-shape drift. Peer of
35583        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
35584        // (8580068) on the paired two-slot envelope and
35585        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
35586        // (14e13f1) on the paired four-slot envelope of the same
35587        // `{ de, para, ... }`-prefix `:contratos` axis.
35588        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
35589        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
35590        match built {
35591            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
35592                assert_eq!(de, "cart-svc", "de field must thread verbatim");
35593                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
35594            }
35595            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
35596        }
35597    }
35598
35599    #[test]
35600    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
35601        // Routing pin on the `endpoint: &str` axis: sweep a non-default
35602        // value (`"charge"` — no leading `/`, the exact shape the
35603        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
35604        // through the sole payload-carrier constructor axis so any
35605        // wrapper-side transformation on the `endpoint.to_string()`
35606        // one-field construction surfaces here rather than at a
35607        // downstream diagnostic-shape mismatch. Sibling of
35608        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
35609        // (14e13f1) on the sibling four-slot envelope's payload-carrier
35610        // routing pin.
35611        let edge = || ("cart".to_string(), "catalog".to_string());
35612        let via_literal = "charge";
35613        let via_string = String::from("charge");
35614        assert_eq!(
35615            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
35616            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
35617        );
35618    }
35619
35620    // ── contrato_self_loop standalone ctor pins ─────────────────────────
35621    //
35622    // Fail-before-pass-after pins for the standalone
35623    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
35624    // doc-block above the ctor definition) — the fold of the last
35625    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
35626    // <ct>.world_ref().to_string() }` struct-literal inside
35627    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
35628    // arm onto one substrate primitive on the [`AplicacaoError`]
35629    // envelope, projecting through the paired [`WitContract::source`] /
35630    // [`WitContract::world_ref`] scalar accessors on the substrate
35631    // primitive. A byte-mismatched ctor body would trip the equivalence
35632    // pin first, ahead of any downstream diagnostic-shape drift.
35633    //
35634    // Peer of the sibling standalone-ctor equivalence pins on the peer
35635    // one-off variants across caixa-core:
35636    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
35637    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
35638    // envelope, the sibling
35639    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
35640    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
35641    // the paired two-slot and four-slot per-`:contratos :endpoint`
35642    // envelopes, and the sibling
35643    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
35644    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
35645    fn contrato_self_loop_ctor_fixture() -> WitContract {
35646        WitContract {
35647            de: "cart".to_string(),
35648            para: "cart".to_string(),
35649            wit: "wasi:http/proxy".to_string(),
35650            endpoint: Some("/self".to_string()),
35651            subject: None,
35652            slot: None,
35653        }
35654    }
35655
35656    #[test]
35657    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
35658        // Equivalence pin: the ctor produces byte-equal
35659        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
35660        // struct-literal that read the same two fields through
35661        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
35662        // any future field-addition / reordering / string-conversion
35663        // tweak on the variant. Same equivalence-pin shape as the
35664        // sibling `contrato_endpoint_not_absolute_ctor_matches_
35665        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
35666        // per-`:contratos :endpoint` envelope.
35667        let contract = contrato_self_loop_ctor_fixture();
35668        let lifted = AplicacaoError::contrato_self_loop(&contract);
35669        let struct_literal = AplicacaoError::ContratoSelfLoop {
35670            caixa: contract.source().to_string(),
35671            wit: contract.world_ref().to_string(),
35672        };
35673        assert_eq!(lifted, struct_literal);
35674    }
35675
35676    #[test]
35677    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
35678        // Routing pin sweeping non-default `caixa` and `:wit` values
35679        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
35680        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
35681        // axes so any wrapper-side lowercase / trim / re-order surfaces
35682        // here rather than at a downstream diagnostic-shape drift.
35683        // Peer of the sibling
35684        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
35685        // (cdf1a2c) routing pin on the sibling three-slot envelope.
35686        let contract = WitContract {
35687            de: "catalog-v2".to_string(),
35688            para: "catalog-v2".to_string(),
35689            wit: "nats:pub-sub".to_string(),
35690            endpoint: None,
35691            subject: Some("orders.>".to_string()),
35692            slot: None,
35693        };
35694        let built = AplicacaoError::contrato_self_loop(&contract);
35695        match built {
35696            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
35697                assert_eq!(
35698                    caixa, "catalog-v2",
35699                    "caixa slot must thread WitContract::source() verbatim"
35700                );
35701                assert_eq!(
35702                    wit, "nats:pub-sub",
35703                    "wit slot must thread WitContract::world_ref() verbatim"
35704                );
35705            }
35706            other => panic!("expected ContratoSelfLoop, got {other:?}"),
35707        }
35708    }
35709
35710    #[test]
35711    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
35712        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
35713        // [`WitContract::source`] accessor (matching the pre-lift open-
35714        // coded body's field selection), not [`WitContract::destination`].
35715        // Under today's `WitContract::is_self_loop()`-gated call site
35716        // the two are equal by that predicate's own contract, but a
35717        // future consumer that constructs the ctor against a not-yet-
35718        // gated candidate contract — an M4
35719        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
35720        // checking a per-`(:de, :para)`-patched candidate before the
35721        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
35722        // resolver rejecting a self-edge introduced by a cluster-local
35723        // `:contratos` override — needs the pre-lift field selection
35724        // pinned so a silent `.destination()` swap at the ctor body
35725        // surfaces here rather than at a downstream diagnostic mis-
35726        // attribution far from the self-loop diagnostic's owner
35727        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
35728        // direction).
35729        //
35730        // Deliberately constructs a non-self-loop pair (`"cart" →
35731        // "catalog"`) so the two accessors yield distinct bytes on the
35732        // fixture — a `.destination()` swap at the ctor body would land
35733        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
35734        // the assertion here.
35735        let contract = WitContract {
35736            de: "cart".to_string(),
35737            para: "catalog".to_string(),
35738            wit: "wasi:http/proxy".to_string(),
35739            endpoint: Some("/charge".to_string()),
35740            subject: None,
35741            slot: None,
35742        };
35743        let built = AplicacaoError::contrato_self_loop(&contract);
35744        match built {
35745            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
35746                assert_eq!(
35747                    caixa, "cart",
35748                    "caixa slot must project WitContract::source() (not destination)"
35749                );
35750            }
35751            other => panic!("expected ContratoSelfLoop, got {other:?}"),
35752        }
35753    }
35754
35755    // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
35756    // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
35757    // family — the sole per-axis ctor projecting through both
35758    // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
35759    // triple) and [`WitTarget::label`] (on the trailing `target` slot).
35760    // Equivalence pin locks the ctor body to the pre-lift struct-literal
35761    // shape under `PartialEq`, so any accessor-side field-selection drift
35762    // or per-arm wrapper transformation surfaces here as a build-time
35763    // test failure rather than at a downstream diagnostic-shape mismatch
35764    // far from the substrate primitive. Peer of the sibling
35765    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
35766    // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
35767    // edge envelope's `WitContract`-projection ctor.
35768    #[test]
35769    fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
35770        let contract = contrato_self_loop_ctor_fixture();
35771        let target = contract.target_projected();
35772        let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
35773        let (de, para, wit) = contract.edge_triple();
35774        let struct_literal = AplicacaoError::ContratoDuplicate {
35775            de,
35776            para,
35777            wit,
35778            target: target.label(),
35779        };
35780        assert_eq!(lifted, struct_literal);
35781    }
35782
35783    // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
35784    // the paired [`WitContract::edge_triple`] projection's three axes
35785    // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
35786    // the `target` axis all yield distinct bytes on the fixture — any
35787    // wrapper-side re-order / accessor-swap on the four axes surfaces
35788    // here rather than at a downstream diagnostic-shape drift. Peer of
35789    // the sibling
35790    // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
35791    // (b30edfe) routing pin on the paired two-slot envelope.
35792    #[test]
35793    fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
35794        let contract = WitContract {
35795            de: "cart".to_string(),
35796            para: "catalog".to_string(),
35797            wit: "wasi:http/proxy".to_string(),
35798            endpoint: Some("/charge".to_string()),
35799            subject: None,
35800            slot: None,
35801        };
35802        let target = contract.target_projected();
35803        let built = AplicacaoError::contrato_duplicate(&contract, &target);
35804        match built {
35805            AplicacaoError::ContratoDuplicate {
35806                de,
35807                para,
35808                wit,
35809                target,
35810            } => {
35811                assert_eq!(
35812                    de, "cart",
35813                    "de slot must thread WitContract::edge_triple().0 verbatim"
35814                );
35815                assert_eq!(
35816                    para, "catalog",
35817                    "para slot must thread WitContract::edge_triple().1 verbatim"
35818                );
35819                assert_eq!(
35820                    wit, "wasi:http/proxy",
35821                    "wit slot must thread WitContract::edge_triple().2 verbatim"
35822                );
35823                assert!(
35824                    target.contains("/charge"),
35825                    "target slot must project through WitTarget::label() \
35826                     (got target = {target:?})"
35827                );
35828            }
35829            other => panic!("expected ContratoDuplicate, got {other:?}"),
35830        }
35831    }
35832
35833    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
35834    // macro definition (see the paired doc-block above the macro definition)
35835    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
35836    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
35837    // struct-literal onto one substrate primitive. The four per-variant
35838    // equivalence pins below (fail-before-pass-after by construction — a
35839    // byte-mismatched macro arm would trip its equivalence pin first) lock
35840    // each generated constructor to its struct-literal peer under
35841    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
35842    // [`AplicacaoSpec::validate_membros`], and
35843    // [`validate_no_self_membership`] on that variant produces a byte-equal
35844    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
35845    // cross-axis pin that follows (non-default caixa name) routes the sole
35846    // constructor input axis through `.to_string()`, so the fold does not
35847    // silently collapse onto a fixed name.
35848    //
35849    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
35850    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
35851    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
35852    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
35853    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
35854    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
35855    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
35856    // of the peer M2 `:behavior` envelope fold (67c31ec,
35857    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
35858    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
35859    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
35860
35861    #[test]
35862    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
35863        assert_eq!(
35864            AplicacaoError::contrato_member_missing("cart"),
35865            AplicacaoError::ContratoMemberMissing {
35866                caixa: "cart".to_string(),
35867            },
35868            "generated contrato_member_missing ctor must produce byte-equal \
35869             AplicacaoError to the open-coded struct-literal wrap on the \
35870             same &str fixture",
35871        );
35872    }
35873
35874    #[test]
35875    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
35876        assert_eq!(
35877            AplicacaoError::membro_versao_empty("cart"),
35878            AplicacaoError::MembroVersaoEmpty {
35879                caixa: "cart".to_string(),
35880            },
35881            "generated membro_versao_empty ctor must produce byte-equal \
35882             AplicacaoError to the open-coded struct-literal wrap on the \
35883             same &str fixture",
35884        );
35885    }
35886
35887    #[test]
35888    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
35889        assert_eq!(
35890            AplicacaoError::membro_duplicate("cart"),
35891            AplicacaoError::MembroDuplicate {
35892                caixa: "cart".to_string(),
35893            },
35894            "generated membro_duplicate ctor must produce byte-equal \
35895             AplicacaoError to the open-coded struct-literal wrap on the \
35896             same &str fixture",
35897        );
35898    }
35899
35900    #[test]
35901    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
35902        assert_eq!(
35903            AplicacaoError::membro_is_self_aplicacao("checkout"),
35904            AplicacaoError::MembroIsSelfAplicacao {
35905                caixa: "checkout".to_string(),
35906            },
35907            "generated membro_is_self_aplicacao ctor must produce byte-equal \
35908             AplicacaoError to the open-coded struct-literal wrap on the \
35909             same &str fixture",
35910        );
35911    }
35912
35913    #[test]
35914    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
35915        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
35916        // &str`) through a non-default fixture name against every generated
35917        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
35918        // wrapper-side lowercase / trim / truncate / re-order on the
35919        // `caixa.to_string()` sole-field construction surfaces here rather
35920        // than at a downstream diagnostic-shape mismatch. Peer of the
35921        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
35922        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
35923        // envelope (db09650), extended here onto the peer `AplicacaoError`
35924        // `{ caixa: String }` envelope so every substrate-primitive ctor
35925        // family in caixa-core carrying a single-slot `{ caixa: String }`
35926        // shape guarantees the sole-field construction routes the caller's
35927        // `&str` through `.to_string()` verbatim.
35928        let name = "cache-v2";
35929        assert_eq!(
35930            AplicacaoError::contrato_member_missing(name),
35931            AplicacaoError::ContratoMemberMissing {
35932                caixa: name.to_string(),
35933            },
35934        );
35935        assert_eq!(
35936            AplicacaoError::membro_versao_empty(name),
35937            AplicacaoError::MembroVersaoEmpty {
35938                caixa: name.to_string(),
35939            },
35940        );
35941        assert_eq!(
35942            AplicacaoError::membro_duplicate(name),
35943            AplicacaoError::MembroDuplicate {
35944                caixa: name.to_string(),
35945            },
35946        );
35947        assert_eq!(
35948            AplicacaoError::membro_is_self_aplicacao(name),
35949            AplicacaoError::MembroIsSelfAplicacao {
35950                caixa: name.to_string(),
35951            },
35952        );
35953    }
35954
35955    #[test]
35956    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
35957        assert_eq!(
35958            AplicacaoError::entrada_path_not_absolute("api/cart"),
35959            AplicacaoError::EntradaPathNotAbsolute {
35960                path: "api/cart".to_string(),
35961            },
35962            "generated entrada_path_not_absolute ctor must produce byte-equal \
35963             AplicacaoError to the open-coded struct-literal wrap on the \
35964             same &str fixture",
35965        );
35966    }
35967
35968    #[test]
35969    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
35970        assert_eq!(
35971            AplicacaoError::entrada_path_duplicate("/api/cart"),
35972            AplicacaoError::EntradaPathDuplicate {
35973                path: "/api/cart".to_string(),
35974            },
35975            "generated entrada_path_duplicate ctor must produce byte-equal \
35976             AplicacaoError to the open-coded struct-literal wrap on the \
35977             same &str fixture",
35978        );
35979    }
35980
35981    // ── membro_versao_invalid ctor pins ────────────────────────────────
35982    //
35983    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
35984    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
35985    // produces an `AplicacaoError` structurally identical to the pre-lift
35986    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
35987    // versao.to_string(), reason: reason.into() }` open-coded three-slot
35988    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
35989    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
35990    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
35991    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
35992    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
35993    // extended here onto the paired per-`:membros :versao` axis on the
35994    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
35995    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
35996    // typed-error surface guarantee the shared three-field construction
35997    // routes through one substrate primitive per envelope.
35998
35999    #[test]
36000    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
36001        let caixa = "cart";
36002        let versao = "not-a-req";
36003        let reason = "sample reason text";
36004        assert_eq!(
36005            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
36006            AplicacaoError::MembroVersaoInvalid {
36007                caixa: caixa.to_string(),
36008                versao: versao.to_string(),
36009                reason: reason.to_string(),
36010            },
36011            "lifted membro_versao_invalid ctor must produce byte-equal \
36012             AplicacaoError to the open-coded struct-literal wrap on the \
36013             same (&str, &str, reason) fixture",
36014        );
36015    }
36016
36017    #[test]
36018    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
36019        // Cross-axis pin: sweep the two `&str`-shaped constructor input
36020        // axes (`caixa`, `versao`) through non-default fixtures so any
36021        // wrapper-side lowercase / trim / truncate / re-order on either
36022        // `.to_string()` field construction surfaces here rather than at
36023        // a downstream diagnostic-shape mismatch. Peer of the sibling
36024        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
36025        // routing pin on the peer `SupervisorError` envelope.
36026        let caixa = "Cart-V2";
36027        let versao = "0.1.0-alpha+build.42";
36028        let reason = "constructed reason";
36029        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
36030        let AplicacaoError::MembroVersaoInvalid {
36031            caixa: got_caixa,
36032            versao: got_versao,
36033            reason: got_reason,
36034        } = err
36035        else {
36036            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
36037        };
36038        assert_eq!(got_caixa, caixa.to_string());
36039        assert_eq!(got_versao, versao.to_string());
36040        assert_eq!(got_reason, reason.to_string());
36041    }
36042
36043    #[test]
36044    fn membro_versao_invalid_ctor_routes_reason_through_into() {
36045        // Route pin: the `reason: impl Into<String>` bound accepts both
36046        // `&str` literals and `format!(…)` / `String` outputs verbatim,
36047        // matching the sibling
36048        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
36049        // routing pin on the peer `SupervisorError::child_versao_invalid`.
36050        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
36051        // `require_valid_versao_requirement`-delivered `reason` closure
36052        // parameter (typed `String`) picks the ctor up without a per-arm
36053        // wrapper transformation, and every future consumer that
36054        // constructs the variant from a `format!(…)` reason surfaces
36055        // byte-equal to the `&str`-literal path.
36056        let caixa = "cart";
36057        let versao = "not-a-req";
36058        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
36059        let from_format =
36060            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
36061        let from_string =
36062            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
36063        assert_eq!(from_literal, from_format);
36064        assert_eq!(from_literal, from_string);
36065    }
36066
36067    #[test]
36068    fn aplicacao_path_only_ctors_route_path_through_to_string() {
36069        // Cross-axis pin: sweep the sole constructor input axis (`path:
36070        // &str`) through a non-default fixture path against every generated
36071        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
36072        // wrapper-side lowercase / trim / truncate / re-order on the
36073        // `path.to_string()` sole-field construction surfaces here rather
36074        // than at a downstream diagnostic-shape mismatch. Peer of the
36075        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
36076        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
36077        // envelope (d9f6867), extended here onto the sibling
36078        // `AplicacaoError` `{ path: String }` envelope so every substrate-
36079        // primitive ctor family in caixa-core carrying a single-slot
36080        // `{ <slot>: String }` shape guarantees the sole-field construction
36081        // routes the caller's `&str` through `.to_string()` verbatim.
36082        let path = "/api/v2/checkout";
36083        assert_eq!(
36084            AplicacaoError::entrada_path_not_absolute(path),
36085            AplicacaoError::EntradaPathNotAbsolute {
36086                path: path.to_string(),
36087            },
36088        );
36089        assert_eq!(
36090            AplicacaoError::entrada_path_duplicate(path),
36091            AplicacaoError::EntradaPathDuplicate {
36092                path: path.to_string(),
36093            },
36094        );
36095    }
36096
36097    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
36098    //
36099    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
36100    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
36101    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
36102    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
36103    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
36104    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
36105    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
36106    // substitution on any one variant surfaces here rather than at a downstream
36107    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
36108    // pins on `aplicacao_field_reason_ctors!` (981060b),
36109    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
36110    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
36111    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
36112    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
36113    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
36114    // per-envelope ctor-macro pins.
36115
36116    #[test]
36117    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
36118        let timeout = Duration::from_micros(1_500);
36119        assert_eq!(
36120            AplicacaoError::policy_timeout_not_canonical(timeout),
36121            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
36122            "generated policy_timeout_not_canonical ctor must produce byte-equal \
36123             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
36124             struct-literal wrap on the same `Copy`-`Duration` fixture",
36125        );
36126    }
36127
36128    #[test]
36129    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
36130        let timeout = Duration::from_secs(3_601);
36131        assert_eq!(
36132            AplicacaoError::policy_timeout_exceeds_cap(timeout),
36133            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
36134            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
36135             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
36136             struct-literal wrap on the same `Copy`-`Duration` fixture",
36137        );
36138    }
36139
36140    #[test]
36141    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
36142        let retries = 47_u32;
36143        assert_eq!(
36144            AplicacaoError::policy_retries_exceeds_cap(retries),
36145            AplicacaoError::PolicyRetriesExceedsCap { retries },
36146            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
36147             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
36148             struct-literal wrap on the same `Copy`-`u32` fixture",
36149        );
36150    }
36151
36152    #[test]
36153    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
36154        let max_failures = 1_337_u32;
36155        assert_eq!(
36156            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
36157            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
36158            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
36159             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
36160             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
36161        );
36162    }
36163
36164    #[test]
36165    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
36166        let window = Duration::from_micros(500);
36167        assert_eq!(
36168            AplicacaoError::policy_breaker_window_not_canonical(window),
36169            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
36170            "generated policy_breaker_window_not_canonical ctor must produce \
36171             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
36172             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
36173        );
36174    }
36175
36176    #[test]
36177    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
36178        let window = Duration::from_secs(3_700);
36179        assert_eq!(
36180            AplicacaoError::policy_breaker_window_exceeds_cap(window),
36181            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
36182            "generated policy_breaker_window_exceeds_cap ctor must produce \
36183             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
36184             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
36185        );
36186    }
36187
36188    #[test]
36189    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
36190        let rate = 1_000_001_u32;
36191        assert_eq!(
36192            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
36193            AplicacaoError::PolicyRateLimitExceedsCap { rate },
36194            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
36195             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
36196             struct-literal wrap on the same `Copy`-`u32` fixture",
36197        );
36198    }
36199
36200    #[test]
36201    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
36202        let window = Duration::from_secs(15);
36203        assert_eq!(
36204            AplicacaoError::policy_rate_limit_window_not_canonical(window),
36205            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
36206            "generated policy_rate_limit_window_not_canonical ctor must produce \
36207             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
36208             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
36209             fixture",
36210        );
36211    }
36212
36213    #[test]
36214    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
36215        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
36216        // constructor input axis through a non-default `Copy` fixture against
36217        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
36218        // wrapper-side silent `.into()` / silent constant-substitution / silent
36219        // field re-name away from the canonical `timeout | retries |
36220        // max_failures | window | rate` axes on any one variant, or a
36221        // `Duration | u32` axis silently rerouted through some other `Copy`
36222        // coercion, surfaces here rather than at a downstream per-`:politicas`
36223        // diagnostic-shape drift. Peer of the sibling
36224        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
36225        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
36226        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
36227        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
36228        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
36229        // families, extended here onto the last M3 per-`:politicas` per-axis
36230        // `AplicacaoError` variant family folded onto a substrate primitive.
36231        //
36232        // Fixtures picked out of each variant's accept-set boundary rather
36233        // than the default value so a silent constant-substitution to `0` /
36234        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
36235        // structural-equality assertion. The two `Duration` fixtures pick the
36236        // sub-millisecond and above-cap ends respectively; the three `u32`
36237        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
36238        // `rate` respectively (each variant's cap sits well below the fixture
36239        // so the pre-lift struct-literal wrap the fixture is compared against
36240        // is the same shape the pre-lift wire-up produced).
36241        let sub_ms = Duration::from_micros(1_500);
36242        let above_hour = Duration::from_secs(3_700);
36243        let non_canonical_rl_window = Duration::from_secs(15);
36244        assert_eq!(
36245            AplicacaoError::policy_timeout_not_canonical(sub_ms),
36246            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
36247        );
36248        assert_eq!(
36249            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
36250            AplicacaoError::PolicyTimeoutExceedsCap {
36251                timeout: above_hour,
36252            },
36253        );
36254        assert_eq!(
36255            AplicacaoError::policy_retries_exceeds_cap(47),
36256            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
36257        );
36258        assert_eq!(
36259            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
36260            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
36261                max_failures: 1_337,
36262            },
36263        );
36264        assert_eq!(
36265            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
36266            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
36267        );
36268        assert_eq!(
36269            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
36270            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
36271        );
36272        assert_eq!(
36273            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
36274            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
36275        );
36276        assert_eq!(
36277            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
36278            AplicacaoError::PolicyRateLimitWindowNotCanonical {
36279                window: non_canonical_rl_window,
36280            },
36281        );
36282    }
36283
36284    #[test]
36285    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
36286        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
36287        // every generated ctor `const fn` so a caller can pin an
36288        // `AplicacaoError` at compile time — the same zero-runtime-work
36289        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
36290        // closure carried on its `Copy`-pass-through construction path (no
36291        // `.to_string()` / `.into()` allocation, no branching). If any future
36292        // edit silently drops the `const` qualifier from the macro body the
36293        // per-arm `const` bindings below fail to compile, which surfaces the
36294        // regression at the substrate-primitive definition rather than at
36295        // some downstream consumer that had come to rely on the `const`-
36296        // constructibility. Peer of the sibling per-variant
36297        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
36298        // equality axis; this pin closes the compile-time-const axis on the
36299        // same generated family.
36300        const TIMEOUT_NC: AplicacaoError =
36301            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
36302        const TIMEOUT_CAP: AplicacaoError =
36303            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
36304        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
36305        const MAX_FAIL_CAP: AplicacaoError =
36306            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
36307        const CB_WIN_NC: AplicacaoError =
36308            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
36309        const CB_WIN_CAP: AplicacaoError =
36310            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
36311        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
36312        const RL_WIN_NC: AplicacaoError =
36313            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
36314        assert!(matches!(
36315            TIMEOUT_NC,
36316            AplicacaoError::PolicyTimeoutNotCanonical { .. }
36317        ));
36318        assert!(matches!(
36319            TIMEOUT_CAP,
36320            AplicacaoError::PolicyTimeoutExceedsCap { .. }
36321        ));
36322        assert!(matches!(
36323            RETRIES_CAP,
36324            AplicacaoError::PolicyRetriesExceedsCap { .. }
36325        ));
36326        assert!(matches!(
36327            MAX_FAIL_CAP,
36328            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
36329        ));
36330        assert!(matches!(
36331            CB_WIN_NC,
36332            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
36333        ));
36334        assert!(matches!(
36335            CB_WIN_CAP,
36336            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
36337        ));
36338        assert!(matches!(
36339            RATE_CAP,
36340            AplicacaoError::PolicyRateLimitExceedsCap { .. }
36341        ));
36342        assert!(matches!(
36343            RL_WIN_NC,
36344            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
36345        ));
36346    }
36347
36348    // Per-variant equivalence + routing pins for the
36349    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
36350    // (see the paired doc-block above the ctor definition) — the
36351    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
36352    // Self` inherent constructor folds the uniform
36353    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
36354    // one-field struct-literal onto one substrate primitive. Same
36355    // shape as the sibling
36356    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
36357    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
36358    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
36359    // ctors — extended here onto the single-slot per-`:placement
36360    // :clusters` dedup-envelope.
36361
36362    #[test]
36363    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
36364        // Equivalence pin: the ctor produces byte-equal
36365        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
36366        // open-coded struct-literal that read the same field through
36367        // `c.clone()` at the caller site inside
36368        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
36369        // field-addition / reordering / string-conversion tweak on the
36370        // variant.
36371        let cluster = "rio";
36372        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
36373        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
36374            cluster: cluster.to_string(),
36375        };
36376        assert_eq!(lifted, struct_literal);
36377    }
36378
36379    #[test]
36380    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
36381        // Routing pin: sweep the sole constructor input axis
36382        // (`cluster: &str`) through a non-default fixture name so any
36383        // wrapper-side lowercase / trim / truncate / re-order on the
36384        // `cluster.to_string()` sole-field construction surfaces here
36385        // rather than at a downstream diagnostic-shape mismatch. Peer of
36386        // the sibling
36387        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
36388        // (d9f6867) cross-axis pin on the sibling one-slot
36389        // `{ caixa: String }` envelope — extended here onto the sibling
36390        // `{ cluster: String }` envelope so the sole `String`-slot
36391        // construction routes the caller's `&str` through `.to_string()`
36392        // verbatim.
36393        let cluster = "sao-paulo-2";
36394        let built = AplicacaoError::placement_cluster_duplicate(cluster);
36395        match built {
36396            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
36397                assert_eq!(
36398                    c, cluster,
36399                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
36400                );
36401            }
36402            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
36403        }
36404    }
36405
36406    // Per-variant equivalence + routing pins for the
36407    // [`AplicacaoError::placement_without_clusters`] standalone ctor
36408    // (see the paired doc-block above the ctor definition) — the
36409    // generated `pub const fn placement_without_clusters(placement:
36410    // &Placement) -> Self` inherent constructor folds the uniform
36411    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
36412    // }` one-field `Copy`-pass-through struct-literal onto one substrate
36413    // primitive. Same shape as the sibling
36414    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
36415    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
36416    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
36417    // ctors — extended here onto the one-slot per-`:placement`
36418    // empty-clusters envelope.
36419
36420    #[test]
36421    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
36422        // Equivalence pin: the ctor produces byte-equal
36423        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
36424        // open-coded struct-literal that read the same field through
36425        // `p.estrategia()` at the caller site inside
36426        // [`AplicacaoSpec::validate_placement`]. Guards any future
36427        // field-addition / reordering / accessor-return tweak on the
36428        // variant.
36429        let placement = Placement {
36430            estrategia: PlacementStrategy::Replicated,
36431            clusters: vec![],
36432            affinity: None,
36433            shard_key: None,
36434        };
36435        let lifted = AplicacaoError::placement_without_clusters(&placement);
36436        let struct_literal = AplicacaoError::PlacementWithoutClusters {
36437            estrategia: placement.estrategia(),
36438        };
36439        assert_eq!(lifted, struct_literal);
36440    }
36441
36442    #[test]
36443    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
36444        // Routing pin: sweep the sole constructor input axis
36445        // (`placement: &Placement`) through every variant in the closed
36446        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
36447        // re-derivation / off-by-one arm-swap / stale-field read on the
36448        // `placement.estrategia()` sole-field projection surfaces here
36449        // rather than at a downstream diagnostic-shape mismatch. Peer of
36450        // the sibling
36451        // `validate_placement_reads_through_lifted_estrategia_accessor`
36452        // three-consumer coherence pin — extended here onto the ctor
36453        // itself so the accessor-projection posture is byte-witnessed at
36454        // the substrate primitive rather than only at the caller-site
36455        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
36456        // future addition to the closed accept-set surfaces as an
36457        // exhaustiveness gap on this iteration list.
36458        for estrategia in [
36459            PlacementStrategy::SingleNode,
36460            PlacementStrategy::Replicated,
36461            PlacementStrategy::Sharded,
36462        ] {
36463            let placement = Placement {
36464                estrategia,
36465                clusters: vec![],
36466                affinity: None,
36467                shard_key: None,
36468            };
36469            let built = AplicacaoError::placement_without_clusters(&placement);
36470            match built {
36471                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
36472                    assert_eq!(
36473                        e,
36474                        placement.estrategia(),
36475                        "estrategia slot must thread the caller's `Placement` verbatim \
36476                         through Placement::estrategia() — the ctor reads through the \
36477                         lifted accessor",
36478                    );
36479                    assert_eq!(
36480                        e, estrategia,
36481                        "estrategia slot must byte-equal the fixture-declared variant",
36482                    );
36483                }
36484                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
36485            }
36486        }
36487    }
36488
36489    #[test]
36490    fn placement_without_clusters_ctor_is_const_fn() {
36491        // Fail-before-pass-after pin on
36492        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
36493        // surface posture. The ctor threads the paired
36494        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
36495        // return through one `const fn` construction — any future
36496        // accidental downgrade to non-`const` (a `.clone()` on the
36497        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
36498        // materialization on the sibling non-`estrategia:` axis) fails
36499        // `placement_without_clusters_via_const_fn` at caixa-core build
36500        // time with E0015 (`cannot call non-const method`), strictly
36501        // stronger than a runtime `assert!`. Sibling of the peer
36502        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
36503        // posture on the sibling per-`:politicas` cap-scalar envelopes
36504        // and the peer [`Placement::estrategia`] const-fn accessor pin at
36505        // [`placement_estrategia_accessor_is_const_fn`] on the paired
36506        // substrate primitive.
36507        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
36508            AplicacaoError::placement_without_clusters(p)
36509        }
36510        let placement = Placement {
36511            estrategia: PlacementStrategy::Sharded,
36512            clusters: vec![],
36513            affinity: None,
36514            shard_key: Some("tenantId".into()),
36515        };
36516        assert_eq!(
36517            placement_without_clusters_via_const_fn(&placement),
36518            AplicacaoError::placement_without_clusters(&placement),
36519        );
36520    }
36521
36522    #[test]
36523    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
36524        // Equivalence pin: the ctor produces byte-equal
36525        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
36526        // open-coded struct-literal that read the same `:para` value
36527        // through `e.destination().to_string()` at the caller site
36528        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
36529        // field-addition / reordering / accessor-return tweak on the
36530        // variant. Sibling of the peer
36531        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
36532        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
36533        // pins on the sibling per-`:placement` envelope, and sibling of
36534        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
36535        // pin on the sibling per-`:membros :caixa` envelope.
36536        let entrada = Entrada {
36537            host: "checkout.quero.cloud".into(),
36538            para: "phantom-shim".into(),
36539            paths: vec!["/api".into()],
36540            port: 8080,
36541        };
36542        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
36543        let via_literal = AplicacaoError::EntradaMemberMissing {
36544            para: entrada.destination().to_string(),
36545        };
36546        assert_eq!(
36547            via_ctor, via_literal,
36548            "entrada_member_missing(&entrada) must byte-equal the open-coded \
36549             EntradaMemberMissing struct-literal on the same &Entrada fixture"
36550        );
36551        assert_eq!(
36552            via_ctor.to_string(),
36553            via_literal.to_string(),
36554            "Display byte-string must byte-equal the open-coded struct-literal"
36555        );
36556    }
36557
36558    #[test]
36559    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
36560        // Boundary-sweep pin on the ctor's substrate-primitive
36561        // projection: the `para` slot is stored verbatim from
36562        // [`Entrada::destination`] across a representative set of
36563        // `:entrada :para` byte-strings, so any wrapper-side silent
36564        // normalization, `.into()` divergence, accidental field
36565        // rebrand, or per-arm ctor divergence on the sole-field
36566        // projection surfaces at caixa-core build time rather than at
36567        // a downstream diagnostic consumer that reads `err.para` back
36568        // and gets a different value than the one it stored. Peer of
36569        // the sibling
36570        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
36571        // boundary-sweep pin on the sibling per-`:placement :shard-key`
36572        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
36573        // sweep on the sibling per-`:placement` empty-clusters envelope
36574        // — extended here onto the [`Entrada`]-borrow-projected sole
36575        // `para` slot on the sibling per-`:entrada :para` envelope. The
36576        // sweep list carries a mixed set (well-shaped phantom, hyphen-
36577        // digit tail, single-character floor, and the digit-start form
36578        // the peer `accepts_canonical_entrada_para_forms` positive-
36579        // control test also sweeps) so a future silent per-input
36580        // normalization surfaces on the arm that diverges.
36581        for para in [
36582            "phantom-shim",
36583            "cart-v2",
36584            "a",
36585            "c0",
36586            "3rd-party-shim",
36587            "x-1-2-3-4",
36588        ] {
36589            let entrada = Entrada {
36590                host: "checkout.quero.cloud".into(),
36591                para: para.into(),
36592                paths: vec!["/api".into()],
36593                port: 8080,
36594            };
36595            let err = AplicacaoError::entrada_member_missing(&entrada);
36596            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
36597                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
36598            };
36599            assert_eq!(
36600                stored_para,
36601                entrada.destination(),
36602                "para slot must round-trip verbatim through Entrada::destination() \
36603                 for {para:?}"
36604            );
36605            assert_eq!(
36606                stored_para, para,
36607                "para slot must byte-equal the fixture-declared value for {para:?}"
36608            );
36609        }
36610    }
36611
36612    #[test]
36613    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
36614        // End-to-end pin: the sole in-crate wire-up site
36615        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
36616        // routes through [`AplicacaoError::entrada_member_missing`] and
36617        // the observed `Err` byte-equals the ctor's output on the same
36618        // well-shaped-phantom `:para` fixture. A future silent de-lift
36619        // of the wire-up back to the open-coded struct-literal trips
36620        // this test at caixa-core build time rather than at a
36621        // downstream diagnostic consumer far from the wire-up commit.
36622        // Sibling of the peer
36623        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
36624        // end-to-end pin on the sibling per-`:placement :shard-key`
36625        // envelope, and sibling of the peer
36626        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
36627        // pattern-match pin on the same wire-up — extended here from a
36628        // `matches!` shape check to a byte-identity + Display parity
36629        // route through the ctor.
36630        let mut s = three_member_spec();
36631        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
36632        let observed = s.validate().unwrap_err();
36633        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
36634        assert_eq!(
36635            observed, expected,
36636            "validate_entrada's phantom-reference-arm Err must byte-equal \
36637             entrada_member_missing(&entrada)"
36638        );
36639        assert_eq!(
36640            observed.to_string(),
36641            expected.to_string(),
36642            "Display byte-string parity"
36643        );
36644    }
36645
36646    #[test]
36647    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
36648        // Equivalence pin: the ctor produces byte-equal
36649        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
36650        // struct-literal that stored the caller-side reconstructed
36651        // cycle path verbatim at the gray-arm cycle-close return inside
36652        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
36653        // field-addition / reordering / re-collect divergence on the
36654        // variant. Sibling of the peer
36655        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
36656        // (deeae5c) pin on the sibling per-`:entrada :para`
36657        // phantom-reference envelope, and sibling of the peer
36658        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
36659        // pin on the sibling per-`:placement` empty-clusters envelope.
36660        let cycle = vec![
36661            "cart".to_string(),
36662            "catalog".to_string(),
36663            "cart".to_string(),
36664        ];
36665        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
36666        let via_literal = AplicacaoError::ContratoCycle {
36667            cycle: cycle.clone(),
36668        };
36669        assert_eq!(
36670            via_ctor, via_literal,
36671            "contrato_cycle(cycle) must byte-equal the open-coded \
36672             ContratoCycle struct-literal on the same Vec<String> fixture"
36673        );
36674        assert_eq!(
36675            via_ctor.to_string(),
36676            via_literal.to_string(),
36677            "Display byte-string must byte-equal the open-coded struct-literal"
36678        );
36679    }
36680
36681    #[test]
36682    fn contrato_cycle_ctor_routes_path_verbatim() {
36683        // Boundary-sweep pin on the ctor's substrate-primitive
36684        // pass-through: the `cycle` slot is stored verbatim across a
36685        // representative set of reconstructed cycle paths (two-node
36686        // closed loop; three-node loop; long chain with repeated
36687        // interior nodes; a fixture whose first/last coincide by the
36688        // gray-arm's own append-target-once-more discipline), so any
36689        // wrapper-side silent normalization, dedup, sort, `.into()`
36690        // divergence, accidental field rebrand, or re-collect on the
36691        // sole-field pass-through surfaces at caixa-core build time
36692        // rather than at a downstream diagnostic consumer that reads
36693        // `err.cycle` back and gets a different value than the one it
36694        // stored. Peer of the sibling
36695        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
36696        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
36697        // :para` envelope — extended here onto the owned-[`Vec<String>`]
36698        // pass-through on the sibling per-`:contratos` cycle envelope.
36699        for cycle in [
36700            vec![
36701                "cart".to_string(),
36702                "catalog".to_string(),
36703                "cart".to_string(),
36704            ],
36705            vec![
36706                "cart".to_string(),
36707                "catalog".to_string(),
36708                "payment".to_string(),
36709                "cart".to_string(),
36710            ],
36711            vec![
36712                "a".to_string(),
36713                "b".to_string(),
36714                "c".to_string(),
36715                "d".to_string(),
36716                "b".to_string(),
36717            ],
36718            vec!["only".to_string(), "only".to_string()],
36719        ] {
36720            let err = AplicacaoError::contrato_cycle(cycle.clone());
36721            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
36722                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
36723            };
36724            assert_eq!(
36725                stored, cycle,
36726                "cycle slot must round-trip the caller-side Vec<String> verbatim \
36727                 for {cycle:?}"
36728            );
36729        }
36730    }
36731
36732    #[test]
36733    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
36734        // End-to-end pin: the sole in-crate wire-up site
36735        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
36736        // return) routes through [`AplicacaoError::contrato_cycle`] and
36737        // the observed `Err` byte-equals the ctor's output on the same
36738        // reconstructed cycle path. A future silent de-lift of the
36739        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
36740        // { cycle }` struct-literal trips this test at caixa-core build
36741        // time rather than at a downstream diagnostic consumer far from
36742        // the wire-up commit. Sibling of the peer
36743        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
36744        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
36745        // envelope, and sibling of the peer
36746        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
36747        // (14bafca) end-to-end pin on the sibling per-`:placement
36748        // :shard-key` envelope — extended here from a bare
36749        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
36750        // check to a byte-identity route through the ctor.
36751        let mut s = three_member_spec();
36752        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
36753        s.contratos = vec![
36754            contract_http("catalog", "cart", "/x"),
36755            contract_http("cart", "payment", "/y"),
36756            contract_http("payment", "catalog", "/z"),
36757        ];
36758        let observed = s.validate().unwrap_err();
36759        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
36760            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
36761        };
36762        let expected = AplicacaoError::contrato_cycle(cycle.clone());
36763        assert_eq!(
36764            observed, expected,
36765            "detect_sync_cycles's gray-arm Err must byte-equal \
36766             contrato_cycle(cycle) on the reconstructed cycle path"
36767        );
36768        assert_eq!(
36769            observed.to_string(),
36770            expected.to_string(),
36771            "Display byte-string parity"
36772        );
36773    }
36774
36775    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
36776    //
36777    // Fail-before-pass-after pins for the standalone
36778    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
36779    // ctor (see the paired doc-block above the ctor definition) — the
36780    // fold of the last open-coded two-slot `{ window: cb.window(),
36781    // timeout: t }` struct-literal inside
36782    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
36783    // arm onto one substrate primitive on the [`AplicacaoError`]
36784    // envelope, projecting through the [`CircuitBreaker::window`] scalar
36785    // accessor on the substrate primitive. A byte-mismatched ctor body
36786    // would trip the equivalence pin first, ahead of any downstream
36787    // diagnostic-shape drift.
36788    //
36789    // Peer of the sibling standalone-ctor equivalence pins on the peer
36790    // per-envelope substrate-primitive-projection ctors across
36791    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
36792    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
36793    // per-`:contratos` self-edge envelope,
36794    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
36795    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
36796    // phantom-reference envelope, and
36797    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
36798    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
36799    // per-`:placement :shard-key` envelope.
36800
36801    #[test]
36802    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
36803        // Equivalence pin: the ctor produces byte-equal
36804        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
36805        // lift open-coded struct-literal that read the same two fields
36806        // through [`CircuitBreaker::window`] and the paired
36807        // `:politicas :timeout` destructure. Guards any future
36808        // field-addition / reordering / accessor-swap tweak on the
36809        // variant. Same equivalence-pin shape as the sibling
36810        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
36811        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
36812        let cb = CircuitBreaker {
36813            max_failures: 5,
36814            window: Duration::from_secs(10),
36815        };
36816        let timeout = Duration::from_secs(30);
36817        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
36818        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
36819            window: cb.window(),
36820            timeout,
36821        };
36822        assert_eq!(
36823            via_ctor, via_literal,
36824            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
36825             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
36826             on the same Copy-Duration fixture"
36827        );
36828        assert_eq!(
36829            via_ctor.to_string(),
36830            via_literal.to_string(),
36831            "Display byte-string must byte-equal the open-coded struct-literal"
36832        );
36833    }
36834
36835    #[test]
36836    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
36837        // Routing pin sweeping non-default `:circuit-breaker :window`
36838        // and `:timeout` pairs (below-boundary window / above-boundary
36839        // window; sub-second window / multi-minute timeout;
36840        // millisecond-precision fixture) through the paired
36841        // [`CircuitBreaker::window`] accessor and the direct `timeout`
36842        // parameter, so any wrapper-side silent normalization,
36843        // rounding, argument re-order, or accidental slot rebrand on
36844        // the two-slot pass-through surfaces at caixa-core build time
36845        // rather than at a downstream diagnostic consumer that reads
36846        // the two [`Duration`]s back and gets different values than
36847        // the ones it stored.
36848        //
36849        // Deliberately routes through a fixture whose `cb.window` and
36850        // `timeout` are distinct — a silent accessor swap
36851        // (`cb.max_failures` casting to `Duration` would fail to
36852        // compile; a hypothetical field-rename swap swapping the two
36853        // slots at the ctor body would land `timeout` in the `window`
36854        // slot instead of `cb.window()` and vice-versa, tripping the
36855        // per-field assertion here). Peer of the sibling
36856        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
36857        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
36858        // envelope.
36859        for (max_failures, window, timeout) in [
36860            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
36861            (
36862                1_u32,
36863                Duration::from_millis(29_999),
36864                Duration::from_secs(30),
36865            ),
36866            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
36867            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
36868        ] {
36869            let cb = CircuitBreaker {
36870                max_failures,
36871                window,
36872            };
36873            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
36874            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
36875                window: stored_window,
36876                timeout: stored_timeout,
36877            } = built
36878            else {
36879                panic!(
36880                    "policy_breaker_window_below_timeout must construct \
36881                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
36882                );
36883            };
36884            assert_eq!(
36885                stored_window, window,
36886                "window slot must thread CircuitBreaker::window() verbatim \
36887                 for cb={cb:?}/timeout={timeout:?}"
36888            );
36889            assert_eq!(
36890                stored_timeout, timeout,
36891                "timeout slot must thread the caller-side :timeout scalar verbatim \
36892                 for cb={cb:?}/timeout={timeout:?}"
36893            );
36894        }
36895    }
36896
36897    #[test]
36898    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
36899        // End-to-end pin: the sole in-crate wire-up site
36900        // ([`MeshPolicy::first_cross_axis_violation`]'s
36901        // window-below-timeout arm) routes through
36902        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
36903        // the observed `Err` byte-equals the ctor's output on the same
36904        // sub-boundary `(:window, :timeout)` fixture. A future silent
36905        // de-lift of the wire-up back to the open-coded
36906        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
36907        // timeout }` struct-literal trips this test at caixa-core build
36908        // time rather than at a downstream diagnostic consumer far from
36909        // the wire-up commit. Sibling of the peer
36910        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
36911        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
36912        // cross-edge cycle envelope,
36913        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
36914        // (deeae5c) on the sibling per-`:entrada :para` phantom-
36915        // reference envelope, and
36916        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
36917        // (14bafca) on the sibling per-`:placement :shard-key`
36918        // envelope — extended here from a bare `matches!(err,
36919        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
36920        // shape check to a byte-identity route through the ctor.
36921        let mut s = three_member_spec();
36922        s.politicas.timeout = Some(Duration::from_secs(30));
36923        s.politicas.circuit_breaker = Some(CircuitBreaker {
36924            max_failures: 5,
36925            window: Duration::from_secs(10),
36926        });
36927        let observed = s.validate().unwrap_err();
36928        let cb = s.politicas.circuit_breaker.unwrap();
36929        let timeout = s.politicas.timeout.unwrap();
36930        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
36931        assert_eq!(
36932            observed, expected,
36933            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
36934             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
36935        );
36936        assert_eq!(
36937            observed.to_string(),
36938            expected.to_string(),
36939            "Display byte-string parity"
36940        );
36941    }
36942
36943    #[test]
36944    fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
36945        // Equivalence pin: the ctor produces byte-equal
36946        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
36947        // pre-lift open-coded struct-literal that read the same four fields
36948        // through [`RateLimit::rate`], [`RateLimit::window`],
36949        // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
36950        // Guards any future field-addition / reordering / accessor-swap
36951        // tweak on the variant. Same equivalence-pin shape as the sibling
36952        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
36953        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
36954        // cross-axis envelope.
36955        let rl = RateLimit {
36956            rate: 1,
36957            window: Duration::from_secs(3600),
36958        };
36959        let cb = CircuitBreaker {
36960            max_failures: 5,
36961            window: Duration::from_secs(10),
36962        };
36963        let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
36964        let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
36965            rate: rl.rate(),
36966            rl_window: rl.window(),
36967            max_failures: cb.max_failures(),
36968            cb_window: cb.window(),
36969        };
36970        assert_eq!(
36971            via_ctor, via_literal,
36972            "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
36973             byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
36974             struct-literal on the same Copy-(u32|Duration) fixture"
36975        );
36976        assert_eq!(
36977            via_ctor.to_string(),
36978            via_literal.to_string(),
36979            "Display byte-string must byte-equal the open-coded struct-literal"
36980        );
36981    }
36982
36983    #[test]
36984    fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
36985        // Routing pin sweeping non-default `(:rate, :rate-limit :window,
36986        // :max-failures, :circuit-breaker :window)` tuples across the
36987        // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
36988        // sub-second breaker window, multi-minute rate-limit window,
36989        // multi-tenant per-cluster ratio — through the paired
36990        // [`RateLimit::rate`] / [`RateLimit::window`] /
36991        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
36992        // accessors, so any wrapper-side silent normalization, rounding,
36993        // argument re-order, or accidental slot rebrand on the four-slot
36994        // pass-through surfaces at caixa-core build time rather than at a
36995        // downstream diagnostic consumer that reads the four scalars back
36996        // and gets different values than the ones it stored.
36997        //
36998        // Deliberately routes through fixtures whose four scalars are
36999        // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
37000        // cb_window`) — a hypothetical field-rename swap swapping any
37001        // two adjacent slots at the ctor body would land the value from
37002        // the wrong axis, tripping the per-field assertion here. Peer of
37003        // the sibling
37004        // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
37005        // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
37006        // :circuit-breaker)` cross-axis envelope.
37007        for (rate, rl_window, max_failures, cb_window) in [
37008            (
37009                1_u32,
37010                Duration::from_secs(3600),
37011                5_u32,
37012                Duration::from_secs(10),
37013            ),
37014            (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
37015            (
37016                2_u32,
37017                Duration::from_millis(500),
37018                10_u32,
37019                Duration::from_secs(300),
37020            ),
37021            (
37022                7_u32,
37023                Duration::from_secs(120),
37024                42_u32,
37025                Duration::from_millis(750),
37026            ),
37027        ] {
37028            let rl = RateLimit {
37029                rate,
37030                window: rl_window,
37031            };
37032            let cb = CircuitBreaker {
37033                max_failures,
37034                window: cb_window,
37035            };
37036            let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
37037            let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
37038                rate: stored_rate,
37039                rl_window: stored_rl_window,
37040                max_failures: stored_max_failures,
37041                cb_window: stored_cb_window,
37042            } = built
37043            else {
37044                panic!(
37045                    "policy_breaker_cannot_trip_under_rate_limit must \
37046                     construct PolicyBreakerCannotTripUnderRateLimit for \
37047                     rl={rl:?}/cb={cb:?}"
37048                );
37049            };
37050            assert_eq!(
37051                stored_rate, rate,
37052                "rate slot must thread RateLimit::rate() verbatim for \
37053                 rl={rl:?}/cb={cb:?}"
37054            );
37055            assert_eq!(
37056                stored_rl_window, rl_window,
37057                "rl_window slot must thread RateLimit::window() verbatim \
37058                 for rl={rl:?}/cb={cb:?}"
37059            );
37060            assert_eq!(
37061                stored_max_failures, max_failures,
37062                "max_failures slot must thread CircuitBreaker::max_failures() \
37063                 verbatim for rl={rl:?}/cb={cb:?}"
37064            );
37065            assert_eq!(
37066                stored_cb_window, cb_window,
37067                "cb_window slot must thread CircuitBreaker::window() verbatim \
37068                 for rl={rl:?}/cb={cb:?}"
37069            );
37070        }
37071    }
37072
37073    #[test]
37074    fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
37075     {
37076        // End-to-end pin: the sole in-crate wire-up site
37077        // ([`MeshPolicy::first_cross_axis_violation`]'s
37078        // starve-under-rate-limit arm) routes through
37079        // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
37080        // and the observed `Err` byte-equals the ctor's output on the same
37081        // token-bucket-starves-breaker fixture. A future silent de-lift of
37082        // the wire-up back to the open-coded
37083        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
37084        // rl_window, max_failures, cb_window }` struct-literal trips this
37085        // test at caixa-core build time rather than at a downstream
37086        // diagnostic consumer far from the wire-up commit. Sibling of the
37087        // peer
37088        // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
37089        // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
37090        // :circuit-breaker)` cross-axis envelope — extended here from a
37091        // bare `matches!(err,
37092        // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
37093        // shape check to a byte-identity route through the ctor. Clears
37094        // `:timeout` so the sibling window-below-timeout arm does not
37095        // fire first on the ordering-precedent it holds over this arm.
37096        let mut s = three_member_spec();
37097        s.politicas.timeout = None;
37098        s.politicas.circuit_breaker = Some(CircuitBreaker {
37099            max_failures: 5,
37100            window: Duration::from_secs(10),
37101        });
37102        s.politicas.rate_limit = Some(RateLimit {
37103            rate: 1,
37104            window: Duration::from_secs(3600),
37105        });
37106        let observed = s.validate().unwrap_err();
37107        let rl = s.politicas.rate_limit.unwrap();
37108        let cb = s.politicas.circuit_breaker.unwrap();
37109        let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
37110        assert_eq!(
37111            observed, expected,
37112            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
37113             arm's Err must byte-equal \
37114             policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
37115        );
37116        assert_eq!(
37117            observed.to_string(),
37118            expected.to_string(),
37119            "Display byte-string parity"
37120        );
37121    }
37122
37123    #[test]
37124    fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
37125        // Equivalence pin: the ctor produces byte-equal
37126        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
37127        // pre-lift open-coded struct-literal that read the same two fields
37128        // through the bare `retries` destructure and
37129        // [`CircuitBreaker::max_failures`]. Guards any future field-addition
37130        // / reordering / accessor-swap tweak on the variant. Same
37131        // equivalence-pin shape as the sibling
37132        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
37133        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
37134        // second cross-axis envelope and
37135        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
37136        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
37137        // cross-axis envelope.
37138        let retries = 5_u32;
37139        let cb = CircuitBreaker {
37140            max_failures: 3,
37141            window: Duration::from_secs(60),
37142        };
37143        let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
37144        let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
37145            retries,
37146            max_failures: cb.max_failures(),
37147        };
37148        assert_eq!(
37149            via_ctor, via_literal,
37150            "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
37151             byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
37152             struct-literal on the same Copy-u32 fixture"
37153        );
37154        assert_eq!(
37155            via_ctor.to_string(),
37156            via_literal.to_string(),
37157            "Display byte-string must byte-equal the open-coded struct-literal"
37158        );
37159    }
37160
37161    #[test]
37162    fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
37163        // Routing pin sweeping non-default `(retries, max_failures)` tuples
37164        // across the production-playbook retries-saturate band — Envoy 5
37165        // retries vs 3 max-failures, boundary retries==max_failures pair (a
37166        // rejecting arm on the strict-inequality invariant), multi-tenant
37167        // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
37168        // through the paired bare-`retries` destructure and
37169        // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
37170        // silent normalization, rounding, argument re-order, or accidental
37171        // slot rebrand on the two-slot pass-through surfaces at caixa-core
37172        // build time rather than at a downstream diagnostic consumer that
37173        // reads the two scalars back and gets different values than the ones
37174        // it stored.
37175        //
37176        // Deliberately routes through fixtures whose two scalars are
37177        // pairwise distinct (`retries ≠ max_failures` on every non-boundary
37178        // arm) — a hypothetical field-rename swap swapping the two slots at
37179        // the ctor body would land the value from the wrong axis, tripping
37180        // the per-field assertion here. Peer of the sibling
37181        // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
37182        // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
37183        // :circuit-breaker)` second cross-axis envelope.
37184        for (retries, max_failures) in [
37185            (5_u32, 3_u32),
37186            (3_u32, 3_u32),
37187            (100_u32, 1_u32),
37188            (7_u32, 42_u32),
37189        ] {
37190            let cb = CircuitBreaker {
37191                max_failures,
37192                window: Duration::from_secs(60),
37193            };
37194            let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
37195            let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
37196                retries: stored_retries,
37197                max_failures: stored_max_failures,
37198            } = built
37199            else {
37200                panic!(
37201                    "policy_breaker_trips_before_retries_exhausted must \
37202                     construct PolicyBreakerTripsBeforeRetriesExhausted for \
37203                     retries={retries}/cb={cb:?}"
37204                );
37205            };
37206            assert_eq!(
37207                stored_retries, retries,
37208                "retries slot must thread the bare-`retries` destructure \
37209                 verbatim for retries={retries}/cb={cb:?}"
37210            );
37211            assert_eq!(
37212                stored_max_failures, max_failures,
37213                "max_failures slot must thread CircuitBreaker::max_failures() \
37214                 verbatim for retries={retries}/cb={cb:?}"
37215            );
37216        }
37217    }
37218
37219    #[test]
37220    fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
37221     {
37222        // End-to-end pin: the sole in-crate wire-up site
37223        // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
37224        // arm) routes through
37225        // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
37226        // and the observed `Err` byte-equals the ctor's output on the same
37227        // retries-saturate fixture. A future silent de-lift of the wire-up
37228        // back to the open-coded
37229        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
37230        // max_failures }` struct-literal trips this test at caixa-core build
37231        // time rather than at a downstream diagnostic consumer far from the
37232        // wire-up commit. Sibling of the peer
37233        // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
37234        // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
37235        // :circuit-breaker)` second cross-axis envelope — extended here from
37236        // a bare `matches!(err,
37237        // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
37238        // shape check to a byte-identity route through the ctor. Clears
37239        // `:timeout` and `:rate-limit` so the sibling window-below-timeout
37240        // and starve-under-rate-limit arms do not fire first on the
37241        // ordering-precedent they hold over this arm.
37242        let mut s = three_member_spec();
37243        s.politicas.timeout = None;
37244        s.politicas.rate_limit = None;
37245        s.politicas.retries = Some(5);
37246        s.politicas.circuit_breaker = Some(CircuitBreaker {
37247            max_failures: 3,
37248            window: Duration::from_secs(60),
37249        });
37250        let observed = s.validate().unwrap_err();
37251        let retries = s.politicas.retries.unwrap();
37252        let cb = s.politicas.circuit_breaker.unwrap();
37253        let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
37254        assert_eq!(
37255            observed, expected,
37256            "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
37257             Err must byte-equal \
37258             policy_breaker_trips_before_retries_exhausted(retries, &cb)"
37259        );
37260        assert_eq!(
37261            observed.to_string(),
37262            expected.to_string(),
37263            "Display byte-string parity"
37264        );
37265    }
37266
37267    #[test]
37268    fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
37269        // Equivalence pin: the ctor produces byte-equal
37270        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
37271        // pre-lift open-coded struct-literal that read the same two fields
37272        // through the bare `retries` destructure and [`RateLimit::rate`].
37273        // Guards any future field-addition / reordering / accessor-swap
37274        // tweak on the variant. Same equivalence-pin shape as the sibling
37275        // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
37276        // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
37277        // third cross-axis envelope,
37278        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
37279        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
37280        // second cross-axis envelope, and
37281        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
37282        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
37283        // first cross-axis envelope.
37284        let retries = 3_u32;
37285        let rl = RateLimit {
37286            rate: 3,
37287            window: Duration::from_secs(1),
37288        };
37289        let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
37290        let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
37291            retries,
37292            rate: rl.rate(),
37293        };
37294        assert_eq!(
37295            via_ctor, via_literal,
37296            "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
37297             byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
37298             struct-literal on the same Copy-u32 fixture"
37299        );
37300        assert_eq!(
37301            via_ctor.to_string(),
37302            via_literal.to_string(),
37303            "Display byte-string must byte-equal the open-coded struct-literal"
37304        );
37305    }
37306
37307    #[test]
37308    fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
37309        // Routing pin sweeping non-default `(retries, rate)` tuples across
37310        // the production-playbook rate-limit-starve band — boundary
37311        // `retries==rate` (a rejecting arm on the `>=` invariant stated as
37312        // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
37313        // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
37314        // through the paired bare-`retries` destructure and
37315        // [`RateLimit::rate`] accessor, so any wrapper-side silent
37316        // normalization, rounding, argument re-order, or accidental slot
37317        // rebrand on the two-slot pass-through surfaces at caixa-core
37318        // build time rather than at a downstream diagnostic consumer that
37319        // reads the two scalars back and gets different values than the
37320        // ones it stored.
37321        //
37322        // Deliberately routes through fixtures whose two scalars are
37323        // pairwise distinct on every non-boundary arm — a hypothetical
37324        // field-rename swap swapping the two slots at the ctor body would
37325        // land the value from the wrong axis, tripping the per-field
37326        // assertion here. Peer of the sibling
37327        // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
37328        // (f54c539) routing pin on the sibling two-slot per-`(:retries,
37329        // :circuit-breaker)` third cross-axis envelope.
37330        for (retries, rate) in [
37331            (3_u32, 3_u32),
37332            (5_u32, 4_u32),
37333            (100_u32, 50_u32),
37334            (2_u32, POLICY_RATE_LIMIT_MAX),
37335        ] {
37336            let rl = RateLimit {
37337                rate,
37338                window: Duration::from_secs(1),
37339            };
37340            let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
37341            let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
37342                retries: stored_retries,
37343                rate: stored_rate,
37344            } = built
37345            else {
37346                panic!(
37347                    "policy_rate_limit_cannot_admit_retry_burst must \
37348                     construct PolicyRateLimitCannotAdmitRetryBurst for \
37349                     retries={retries}/rl={rl:?}"
37350                );
37351            };
37352            assert_eq!(
37353                stored_retries, retries,
37354                "retries slot must thread the bare-`retries` destructure \
37355                 verbatim for retries={retries}/rl={rl:?}"
37356            );
37357            assert_eq!(
37358                stored_rate, rate,
37359                "rate slot must thread RateLimit::rate() verbatim for \
37360                 retries={retries}/rl={rl:?}"
37361            );
37362        }
37363    }
37364
37365    #[test]
37366    fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
37367     {
37368        // End-to-end pin: the sole in-crate wire-up site
37369        // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
37370        // limit arm) routes through
37371        // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
37372        // and the observed `Err` byte-equals the ctor's output on the same
37373        // rate-limit-starve fixture. A future silent de-lift of the
37374        // wire-up back to the open-coded
37375        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
37376        // rate }` struct-literal trips this test at caixa-core build time
37377        // rather than at a downstream diagnostic consumer far from the
37378        // wire-up commit. Sibling of the peer
37379        // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
37380        // (f54c539) end-to-end pin on the sibling per-`(:retries,
37381        // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
37382        // and `:circuit-breaker` so the sibling window-below-timeout /
37383        // starve-under-rate-limit / trips-before-retries-exhausted arms
37384        // do not fire first on the ordering-precedent they hold over this
37385        // arm.
37386        let mut s = three_member_spec();
37387        s.politicas.timeout = None;
37388        s.politicas.circuit_breaker = None;
37389        s.politicas.retries = Some(5);
37390        s.politicas.rate_limit = Some(RateLimit {
37391            rate: 3,
37392            window: Duration::from_secs(1),
37393        });
37394        let observed = s.validate().unwrap_err();
37395        let retries = s.politicas.retries.unwrap();
37396        let rl = s.politicas.rate_limit.unwrap();
37397        let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
37398        assert_eq!(
37399            observed, expected,
37400            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
37401             Err must byte-equal \
37402             policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
37403        );
37404        assert_eq!(
37405            observed.to_string(),
37406            expected.to_string(),
37407            "Display byte-string parity"
37408        );
37409    }
37410}